@executor-js/plugin-mcp 1.5.4 → 1.5.6

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.
@@ -99,7 +99,7 @@ import {
99
99
  tool,
100
100
  ToolResult,
101
101
  ToolName
102
- } from "@executor-js/sdk";
102
+ } from "@executor-js/sdk/core";
103
103
 
104
104
  // src/sdk/connection.ts
105
105
  import { Client } from "@modelcontextprotocol/sdk/client/index.js";
@@ -242,7 +242,7 @@ import {
242
242
  ElicitationId,
243
243
  FormElicitation,
244
244
  UrlElicitation
245
- } from "@executor-js/sdk";
245
+ } from "@executor-js/sdk/core";
246
246
  var ArgsRecord = Schema2.Record(Schema2.String, Schema2.Unknown);
247
247
  var decodeArgsRecord = Schema2.decodeUnknownOption(ArgsRecord);
248
248
  var argsRecord = (value) => Option2.getOrElse(decodeArgsRecord(value), () => ({}));
@@ -1295,4 +1295,4 @@ export {
1295
1295
  userFacingProbeMessage,
1296
1296
  mcpPlugin
1297
1297
  };
1298
- //# sourceMappingURL=chunk-2TXHTMKM.js.map
1298
+ //# sourceMappingURL=chunk-HSJWIVME.js.map
@@ -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}\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 },\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 }),\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, Match, 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 definePlugin,\n IntegrationAlreadyExistsError,\n IntegrationSlug,\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/core\";\n\nimport { createMcpConnector, type ConnectorInput, type McpConnector } from \"./connection\";\nimport { discoverTools } from \"./discover\";\nimport { McpConnectionError, McpToolDiscoveryError } 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 McpAuthTemplate,\n McpRemoteTransport,\n type McpToolAnnotations,\n parseMcpIntegrationConfig,\n type McpIntegrationConfig as McpIntegrationConfigType,\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 (!config || config.transport !== \"remote\" || config.auth.kind !== \"oauth2\") return false;\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 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 /** How a connection's value is applied to requests. Defaults to none. */\n auth: Schema.optional(McpAuthTemplate),\n});\n\nconst McpStdioServerInputSchema = Schema.Struct({\n transport: Schema.Literal(\"stdio\"),\n name: Schema.String,\n command: Schema.String,\n args: Schema.optional(Schema.Array(Schema.String)),\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\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});\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\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\nconst toIntegrationConfig = (input: McpServerInput): McpIntegrationConfigType => {\n if (input.transport === \"stdio\") {\n return {\n transport: \"stdio\",\n command: input.command,\n args: input.args ? [...input.args] : undefined,\n env: input.env,\n cwd: input.cwd,\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 auth: 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 non-MCP probe outcome into a message a user can act on.\n * Exported for tests. */\nexport const userFacingProbeMessage = (\n shape: Extract<McpShapeProbeResult, { kind: \"not-mcp\" } | { kind: \"unreachable\" }>,\n): string => {\n if (shape.kind === \"unreachable\") {\n return \"Couldn't reach this URL. Check the address, your network, and that the server is running.\";\n }\n return Match.value(shape.category).pipe(\n Match.when(\n \"auth-required\",\n () =>\n \"This server requires authentication. Add credentials (Authorization header, query parameter, or API key) below and retry.\",\n ),\n Match.when(\n \"wrong-shape\",\n () =>\n \"This URL doesn't appear to host an MCP server. Double-check the address, including the path.\",\n ),\n Match.exhaustive,\n );\n};\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, executor/no-error-constructor -- boundary: MCP SDK OAuthClientProvider callback can only signal reauthorization by throwing\n throw new Error(\"MCP OAuth re-authorization required\");\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 template into a live `ConnectorInput`.\n// ---------------------------------------------------------------------------\n\nconst buildConnectorInput = (\n config: McpIntegrationConfigType,\n value: string | null,\n allowStdio: boolean,\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 return Effect.succeed({\n transport: \"stdio\" as const,\n command: config.command,\n args: config.args,\n env: config.env,\n cwd: config.cwd,\n } satisfies McpStdioIntegrationConfig);\n }\n\n const headers: Record<string, string> = { ...(config.headers ?? {}) };\n let authProvider: OAuthClientProvider | undefined;\n\n const auth = config.auth;\n if (auth.kind === \"header\" && value !== null) {\n headers[auth.headerName] = auth.prefix ? `${auth.prefix}${value}` : value;\n } else if (auth.kind === \"oauth2\" && value !== null) {\n authProvider = makeOAuthProvider(value);\n }\n\n return Effect.succeed({\n transport: \"remote\" as const,\n endpoint: config.endpoint,\n remoteTransport: config.remoteTransport ?? \"auto\",\n queryParams:\n config.queryParams && Object.keys(config.queryParams).length > 0\n ? config.queryParams\n : undefined,\n headers: Object.keys(headers).length > 0 ? headers : undefined,\n authProvider,\n });\n};\n\n// ---------------------------------------------------------------------------\n// Declared auth methods — project the stored MCP config into the catalog's\n// plugin-agnostic `AuthMethodDescriptor[]`. Pure and tolerant of a malformed or\n// foreign config blob (returns `[]`). Exported for tests.\n//\n// open (`none`) → one none method carrying no credential inputs\n// stdio → [] (no remote connection to configure)\n// header → one apikey method carrying the header placement\n// oauth2 → one oauth method carrying the MCP endpoint to probe\n// (`discoveryUrl`); endpoints are discovered live at\n// connect time, so they are NOT pre-resolved here. We\n// mark `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\nexport const describeMcpAuthMethods = (\n record: IntegrationRecord,\n): readonly AuthMethodDescriptor[] => {\n const config = parseMcpIntegrationConfig(record.config);\n if (!config || config.transport === \"stdio\") return [];\n\n const auth = config.auth;\n if (auth.kind === \"none\") {\n return [\n {\n id: \"none\",\n label: \"No authentication\",\n kind: \"none\",\n template: \"none\",\n },\n ];\n }\n if (auth.kind === \"header\") {\n return [\n {\n id: \"header\",\n label: \"API key (header)\",\n kind: \"apikey\",\n template: \"header\",\n placements: [{ carrier: \"header\", name: auth.headerName, prefix: auth.prefix ?? \"\" }],\n },\n ];\n }\n if (auth.kind === \"oauth2\") {\n return [\n {\n id: \"oauth2\",\n label: \"OAuth\",\n kind: \"oauth\",\n template: \"oauth2\",\n oauth: { discoveryUrl: config.endpoint, supportsDynamicRegistration: true },\n },\n ];\n }\n return [];\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 });\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 } 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 if (shape.kind !== \"mcp\") {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: userFacingProbeMessage(shape),\n });\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 } 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 } 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 description: 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 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 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 return {\n probeEndpoint,\n addServer,\n removeServer,\n getServer,\n configureServer,\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, getValue }) =>\n Effect.gen(function* () {\n const parsed = parseMcpIntegrationConfig(config);\n if (!parsed) return { tools: [] as readonly ToolDef[] };\n\n const value = yield* getValue().pipe(Effect.orElseSucceed(() => null));\n\n const built = yield* buildConnectorInput(parsed, value, allowStdio).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: ({ 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 const connector: McpConnector = yield* buildConnectorInput(\n parsed,\n credential.value,\n allowStdio,\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(\"McpConnectionError\", ({ message }) =>\n Effect.succeed(\n authToolFailure({\n code: \"connection_rejected\",\n message,\n source: { id: String(credential.integration) },\n credential: { kind: \"upstream\", label: String(credential.connection) },\n }),\n ),\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({ transport: \"remote\", endpoint: trimmed });\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 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}\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 { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/sdk/validation/cfworker\";\nimport { Effect } from \"effect\";\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 } 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<McpConnection, McpConnectionError>;\n\n// ---------------------------------------------------------------------------\n// Connector input — extends stored source data with resolved auth\n// ---------------------------------------------------------------------------\n\nexport type RemoteConnectorInput = Omit<\n McpRemoteIntegrationConfig,\n \"auth\" | \"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};\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\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 connectClient = (input: {\n transport: string;\n createTransport: () => Parameters<Client[\"connect\"]>[0];\n}): Effect.Effect<McpConnection, McpConnectionError> =>\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: () =>\n new McpConnectionError({\n transport: input.transport,\n message: `Failed connecting via ${input.transport}`,\n }),\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\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 }),\n });\n\n const connectSse = connectClient({\n transport: \"sse\",\n createTransport: () =>\n new SSEClientTransport(endpoint, {\n requestInit,\n authProvider: input.authProvider,\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\n return connectStreamableHttp.pipe(Effect.catch(() => connectSse));\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 });\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 { 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/core\";\n\nimport { McpConnectionError, McpInvocationError } 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\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> =>\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: () =>\n new McpInvocationError({\n toolName,\n message: `MCP tool call failed for ${toolName}`,\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<unknown, McpConnectionError | McpInvocationError> =>\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;AA+B/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,SA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AC;AAAA,cAChF;AAAA,YACF;AAAA,UACJ,CAAC;AAAA,UACD,KAAK;AAAA,YACH,MAAM;AAAA,YACN,aACE;AAAA,YACF,aAAa;AAAA,YACb,cAAc;AAAA,YACd,SAAS,CAAC,UAAU;AAClB,oBAAM,OAAO;AACb,qBAAOA,QAAO;AAAA,gBAAI,KAAK,UAAU,KAAK,IAAI;AAAA,gBAAG,CAAC,gBAC5C,WAAW,GAAG,EAAE,YAAY,CAAC;AAAA,cAC/B;AAAA,YACF;AAAA,UACF,CAAC;AAAA,UACD,KAAK;AAAA,YACH,MAAM;AAAA,YACN,aACE;AAAA,YACF,aAAa;AAAA,cACX,kBAAkB;AAAA,cAClB,qBAAqB;AAAA,YACvB;AAAA,YACA,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","Schema","Schema","Option","Effect","Effect","Option","Schema","Schema","Option","Effect"]}
package/dist/core.js CHANGED
@@ -4,7 +4,7 @@ import {
4
4
  joinToolPath,
5
5
  mcpPlugin,
6
6
  userFacingProbeMessage
7
- } from "./chunk-2TXHTMKM.js";
7
+ } from "./chunk-HSJWIVME.js";
8
8
  import "./chunk-TW44CBXJ.js";
9
9
  import {
10
10
  McpAuthTemplate,
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  mcpPlugin
3
- } from "./chunk-2TXHTMKM.js";
3
+ } from "./chunk-HSJWIVME.js";
4
4
  import "./chunk-TW44CBXJ.js";
5
5
  import "./chunk-6OEQZ72N.js";
6
6
  export {
@@ -1,5 +1,5 @@
1
1
  import { Effect } from "effect";
2
- import { type Elicit } from "@executor-js/sdk";
2
+ import { type Elicit } from "@executor-js/sdk/core";
3
3
  import { McpConnectionError, McpInvocationError } from "./errors";
4
4
  import type { McpConnector } from "./connection";
5
5
  export interface InvokeMcpToolInput {
@@ -1,6 +1,6 @@
1
1
  import { Effect, Layer, Schema } from "effect";
2
2
  import type { HttpClient } from "effect/unstable/http";
3
- import { IntegrationAlreadyExistsError, type AuthMethodDescriptor, type Integration, type IntegrationConfig, type IntegrationRecord, type StorageFailure } from "@executor-js/sdk";
3
+ import { IntegrationAlreadyExistsError, type AuthMethodDescriptor, type Integration, type IntegrationConfig, type IntegrationRecord, type StorageFailure } from "@executor-js/sdk/core";
4
4
  import { McpConnectionError, McpToolDiscoveryError } from "./errors";
5
5
  import { type McpShapeProbeResult } from "./probe-shape";
6
6
  import { type McpIntegrationConfig as McpIntegrationConfigType } from "./types";
@@ -100,7 +100,7 @@ export interface McpPluginOptions {
100
100
  readonly dangerouslyAllowStdioMCP?: boolean;
101
101
  readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;
102
102
  }
103
- export declare const mcpPlugin: import("@executor-js/sdk").ConfiguredPlugin<"mcp", {
103
+ export declare const mcpPlugin: import("@executor-js/sdk/core").ConfiguredPlugin<"mcp", {
104
104
  probeEndpoint: (input: string | McpProbeEndpointInput) => Effect.Effect<{
105
105
  connected: true;
106
106
  requiresAuthentication: false;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@executor-js/plugin-mcp",
3
- "version": "1.5.4",
3
+ "version": "1.5.6",
4
4
  "homepage": "https://github.com/RhysSullivan/executor/tree/main/packages/plugins/mcp",
5
5
  "bugs": {
6
6
  "url": "https://github.com/RhysSullivan/executor/issues"
@@ -54,8 +54,8 @@
54
54
  "dependencies": {
55
55
  "@cfworker/json-schema": "^4.1.1",
56
56
  "@effect/platform-node": "4.0.0-beta.59",
57
- "@executor-js/config": "1.5.4",
58
- "@executor-js/sdk": "1.5.4",
57
+ "@executor-js/config": "1.5.6",
58
+ "@executor-js/sdk": "1.5.6",
59
59
  "@modelcontextprotocol/sdk": "^1.29.0",
60
60
  "zod": "^4.3.6"
61
61
  },
@@ -1 +0,0 @@
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}\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 },\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 }),\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, Match, 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 definePlugin,\n IntegrationAlreadyExistsError,\n IntegrationSlug,\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 { createMcpConnector, type ConnectorInput, type McpConnector } from \"./connection\";\nimport { discoverTools } from \"./discover\";\nimport { McpConnectionError, McpToolDiscoveryError } 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 McpAuthTemplate,\n McpRemoteTransport,\n type McpToolAnnotations,\n parseMcpIntegrationConfig,\n type McpIntegrationConfig as McpIntegrationConfigType,\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 (!config || config.transport !== \"remote\" || config.auth.kind !== \"oauth2\") return false;\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 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 /** How a connection's value is applied to requests. Defaults to none. */\n auth: Schema.optional(McpAuthTemplate),\n});\n\nconst McpStdioServerInputSchema = Schema.Struct({\n transport: Schema.Literal(\"stdio\"),\n name: Schema.String,\n command: Schema.String,\n args: Schema.optional(Schema.Array(Schema.String)),\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\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});\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\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\nconst toIntegrationConfig = (input: McpServerInput): McpIntegrationConfigType => {\n if (input.transport === \"stdio\") {\n return {\n transport: \"stdio\",\n command: input.command,\n args: input.args ? [...input.args] : undefined,\n env: input.env,\n cwd: input.cwd,\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 auth: 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 non-MCP probe outcome into a message a user can act on.\n * Exported for tests. */\nexport const userFacingProbeMessage = (\n shape: Extract<McpShapeProbeResult, { kind: \"not-mcp\" } | { kind: \"unreachable\" }>,\n): string => {\n if (shape.kind === \"unreachable\") {\n return \"Couldn't reach this URL. Check the address, your network, and that the server is running.\";\n }\n return Match.value(shape.category).pipe(\n Match.when(\n \"auth-required\",\n () =>\n \"This server requires authentication. Add credentials (Authorization header, query parameter, or API key) below and retry.\",\n ),\n Match.when(\n \"wrong-shape\",\n () =>\n \"This URL doesn't appear to host an MCP server. Double-check the address, including the path.\",\n ),\n Match.exhaustive,\n );\n};\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, executor/no-error-constructor -- boundary: MCP SDK OAuthClientProvider callback can only signal reauthorization by throwing\n throw new Error(\"MCP OAuth re-authorization required\");\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 template into a live `ConnectorInput`.\n// ---------------------------------------------------------------------------\n\nconst buildConnectorInput = (\n config: McpIntegrationConfigType,\n value: string | null,\n allowStdio: boolean,\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 return Effect.succeed({\n transport: \"stdio\" as const,\n command: config.command,\n args: config.args,\n env: config.env,\n cwd: config.cwd,\n } satisfies McpStdioIntegrationConfig);\n }\n\n const headers: Record<string, string> = { ...(config.headers ?? {}) };\n let authProvider: OAuthClientProvider | undefined;\n\n const auth = config.auth;\n if (auth.kind === \"header\" && value !== null) {\n headers[auth.headerName] = auth.prefix ? `${auth.prefix}${value}` : value;\n } else if (auth.kind === \"oauth2\" && value !== null) {\n authProvider = makeOAuthProvider(value);\n }\n\n return Effect.succeed({\n transport: \"remote\" as const,\n endpoint: config.endpoint,\n remoteTransport: config.remoteTransport ?? \"auto\",\n queryParams:\n config.queryParams && Object.keys(config.queryParams).length > 0\n ? config.queryParams\n : undefined,\n headers: Object.keys(headers).length > 0 ? headers : undefined,\n authProvider,\n });\n};\n\n// ---------------------------------------------------------------------------\n// Declared auth methods — project the stored MCP config into the catalog's\n// plugin-agnostic `AuthMethodDescriptor[]`. Pure and tolerant of a malformed or\n// foreign config blob (returns `[]`). Exported for tests.\n//\n// open (`none`) → one none method carrying no credential inputs\n// stdio → [] (no remote connection to configure)\n// header → one apikey method carrying the header placement\n// oauth2 → one oauth method carrying the MCP endpoint to probe\n// (`discoveryUrl`); endpoints are discovered live at\n// connect time, so they are NOT pre-resolved here. We\n// mark `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\nexport const describeMcpAuthMethods = (\n record: IntegrationRecord,\n): readonly AuthMethodDescriptor[] => {\n const config = parseMcpIntegrationConfig(record.config);\n if (!config || config.transport === \"stdio\") return [];\n\n const auth = config.auth;\n if (auth.kind === \"none\") {\n return [\n {\n id: \"none\",\n label: \"No authentication\",\n kind: \"none\",\n template: \"none\",\n },\n ];\n }\n if (auth.kind === \"header\") {\n return [\n {\n id: \"header\",\n label: \"API key (header)\",\n kind: \"apikey\",\n template: \"header\",\n placements: [{ carrier: \"header\", name: auth.headerName, prefix: auth.prefix ?? \"\" }],\n },\n ];\n }\n if (auth.kind === \"oauth2\") {\n return [\n {\n id: \"oauth2\",\n label: \"OAuth\",\n kind: \"oauth\",\n template: \"oauth2\",\n oauth: { discoveryUrl: config.endpoint, supportsDynamicRegistration: true },\n },\n ];\n }\n return [];\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 });\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 } 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 if (shape.kind !== \"mcp\") {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: userFacingProbeMessage(shape),\n });\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 } 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 } 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 description: 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 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 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 return {\n probeEndpoint,\n addServer,\n removeServer,\n getServer,\n configureServer,\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, getValue }) =>\n Effect.gen(function* () {\n const parsed = parseMcpIntegrationConfig(config);\n if (!parsed) return { tools: [] as readonly ToolDef[] };\n\n const value = yield* getValue().pipe(Effect.orElseSucceed(() => null));\n\n const built = yield* buildConnectorInput(parsed, value, allowStdio).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: ({ 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 const connector: McpConnector = yield* buildConnectorInput(\n parsed,\n credential.value,\n allowStdio,\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(\"McpConnectionError\", ({ message }) =>\n Effect.succeed(\n authToolFailure({\n code: \"connection_rejected\",\n message,\n source: { id: String(credential.integration) },\n credential: { kind: \"upstream\", label: String(credential.connection) },\n }),\n ),\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({ transport: \"remote\", endpoint: trimmed });\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 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}\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 { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/sdk/validation/cfworker\";\nimport { Effect } from \"effect\";\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 } 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<McpConnection, McpConnectionError>;\n\n// ---------------------------------------------------------------------------\n// Connector input — extends stored source data with resolved auth\n// ---------------------------------------------------------------------------\n\nexport type RemoteConnectorInput = Omit<\n McpRemoteIntegrationConfig,\n \"auth\" | \"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};\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\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 connectClient = (input: {\n transport: string;\n createTransport: () => Parameters<Client[\"connect\"]>[0];\n}): Effect.Effect<McpConnection, McpConnectionError> =>\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: () =>\n new McpConnectionError({\n transport: input.transport,\n message: `Failed connecting via ${input.transport}`,\n }),\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\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 }),\n });\n\n const connectSse = connectClient({\n transport: \"sse\",\n createTransport: () =>\n new SSEClientTransport(endpoint, {\n requestInit,\n authProvider: input.authProvider,\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\n return connectStreamableHttp.pipe(Effect.catch(() => connectSse));\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 });\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 { 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 } 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\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> =>\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: () =>\n new McpInvocationError({\n toolName,\n message: `MCP tool call failed for ${toolName}`,\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<unknown, McpConnectionError | McpInvocationError> =>\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;AA+B/B,I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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","Schema","Schema","Option","Effect","Effect","Option","Schema","Schema","Option","Effect"]}