@executor-js/plugin-mcp 1.4.31 → 1.4.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{AddMcpSource-3HUBFR3K.js → AddMcpSource-PADMBVX2.js} +3 -4
- package/dist/{AddMcpSource-3HUBFR3K.js.map → AddMcpSource-PADMBVX2.js.map} +1 -1
- package/dist/{EditMcpSource-UVGSSC2R.js → EditMcpSource-L5GC2B4J.js} +3 -4
- package/dist/{EditMcpSource-UVGSSC2R.js.map → EditMcpSource-L5GC2B4J.js.map} +1 -1
- package/dist/{McpSourceSummary-UWVCAJOU.js → McpSourceSummary-LE3WXFUE.js} +3 -4
- package/dist/{McpSourceSummary-UWVCAJOU.js.map → McpSourceSummary-LE3WXFUE.js.map} +1 -1
- package/dist/{chunk-3TGDWTNE.js → chunk-6OYEXHU3.js} +6 -3
- package/dist/{chunk-3TGDWTNE.js.map → chunk-6OYEXHU3.js.map} +1 -1
- package/dist/{chunk-2A4H3UVR.js → chunk-FMTVLO5L.js} +2 -2
- package/dist/{chunk-H5PLTEMB.js → chunk-LEGVPKYH.js} +182 -28
- package/dist/chunk-LEGVPKYH.js.map +1 -0
- package/dist/client.js +3 -4
- package/dist/client.js.map +1 -1
- package/dist/core.js +2 -3
- package/dist/index.js +2 -3
- package/dist/sdk/errors.d.ts +19 -0
- package/dist/sdk/invoke.d.ts +5 -5
- package/dist/{stdio-connector-MDW6PW36.js → stdio-connector-AA5S6UUJ.js} +1 -3
- package/dist/{stdio-connector-MDW6PW36.js.map → stdio-connector-AA5S6UUJ.js.map} +1 -1
- package/dist/testing.js +11 -13787
- package/dist/testing.js.map +1 -1
- package/package.json +6 -6
- package/dist/chunk-H5PLTEMB.js.map +0 -1
- package/dist/chunk-PZ5AY32C.js +0 -10
- package/dist/chunk-PZ5AY32C.js.map +0 -1
- /package/dist/{chunk-2A4H3UVR.js.map → chunk-FMTVLO5L.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sdk/binding-store.ts","../src/sdk/plugin.ts","../src/sdk/connection.ts","../src/sdk/discover.ts","../src/sdk/manifest.ts","../src/sdk/invoke.ts","../src/sdk/probe-shape.ts"],"sourcesContent":["import { Effect, Option, Predicate, Schema } from \"effect\";\n\nimport {\n type FumaTables,\n type PluginStorageEntry,\n type StorageDeps,\n type StorageFailure,\n} from \"@executor-js/sdk/core\";\n\nimport { McpStoredSourceData, McpToolBinding } from \"./types\";\n\nexport const mcpSchema = {} satisfies FumaTables;\nexport type McpSchema = typeof mcpSchema;\n\nconst SOURCE_COLLECTION = \"source\";\nconst BINDING_COLLECTION = \"binding\";\n\nconst decodeSourceData = Schema.decodeUnknownSync(McpStoredSourceData);\nconst encodeSourceData = Schema.encodeSync(McpStoredSourceData);\nconst decodeBinding = Schema.decodeUnknownSync(McpToolBinding);\nconst encodeBinding = Schema.encodeSync(McpToolBinding);\nconst decodeJson = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));\n\nconst coerceJson = (value: unknown): unknown => {\n if (typeof value !== \"string\") return value;\n return Option.getOrElse(decodeJson(value), () => value);\n};\n\nexport interface McpStoredSource {\n readonly namespace: string;\n readonly scope: string;\n readonly name: string;\n readonly config: McpStoredSourceData;\n}\n\nexport interface McpBindingStore {\n readonly listBindingsBySource: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<\n ReadonlyArray<{\n readonly toolId: string;\n readonly binding: McpToolBinding;\n }>,\n StorageFailure\n >;\n readonly getBinding: (\n toolId: string,\n scope: string,\n ) => Effect.Effect<\n { readonly binding: McpToolBinding; readonly namespace: string } | null,\n StorageFailure\n >;\n readonly putBindings: (\n namespace: string,\n scope: string,\n entries: ReadonlyArray<{\n readonly toolId: string;\n readonly binding: McpToolBinding;\n }>,\n ) => Effect.Effect<void, StorageFailure>;\n readonly removeBindingsByNamespace: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<void, StorageFailure>;\n readonly getSource: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<McpStoredSource | null, StorageFailure>;\n readonly getSourceConfig: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<McpStoredSourceData | null, StorageFailure>;\n readonly putSource: (source: McpStoredSource) => Effect.Effect<void, StorageFailure>;\n readonly removeSource: (namespace: string, scope: string) => Effect.Effect<void, StorageFailure>;\n}\n\nconst sourceData = (source: McpStoredSource) => ({\n namespace: source.namespace,\n scope: source.scope,\n name: source.name,\n config: encodeSourceData(source.config),\n});\n\nconst bindingData = (\n namespace: string,\n entry: {\n readonly toolId: string;\n readonly binding: McpToolBinding;\n },\n) => ({\n namespace,\n toolId: entry.toolId,\n binding: encodeBinding(entry.binding),\n});\n\nconst rowToSource = (row: PluginStorageEntry): McpStoredSource | null => {\n const raw = coerceJson(row.data);\n if (!raw || typeof raw !== \"object\") return null;\n const record = raw as Record<string, unknown>;\n if (\n typeof record.namespace !== \"string\" ||\n typeof record.scope !== \"string\" ||\n typeof record.name !== \"string\"\n ) {\n return null;\n }\n return {\n namespace: record.namespace,\n scope: record.scope,\n name: record.name,\n config: decodeSourceData(coerceJson(record.config)),\n };\n};\n\nconst rowToBinding = (\n row: PluginStorageEntry,\n): {\n readonly toolId: string;\n readonly namespace: string;\n readonly binding: McpToolBinding;\n} | null => {\n const raw = coerceJson(row.data);\n if (!raw || typeof raw !== \"object\") return null;\n const record = raw as Record<string, unknown>;\n if (typeof record.toolId !== \"string\" || typeof record.namespace !== \"string\") return null;\n return {\n toolId: record.toolId,\n namespace: record.namespace,\n binding: decodeBinding(coerceJson(record.binding)),\n };\n};\n\nexport const makeMcpStore = ({ pluginStorage }: StorageDeps<McpSchema>): McpBindingStore => {\n const listBindingRowsForSourceScope = (namespace: string, scope: string) =>\n pluginStorage\n .list({\n collection: BINDING_COLLECTION,\n keyPrefix: `${namespace}.`,\n })\n .pipe(\n Effect.map((rows) =>\n rows.filter((row) => {\n if (String(row.scopeId) !== scope) return false;\n return rowToBinding(row)?.namespace === namespace;\n }),\n ),\n );\n\n const removeBindingsForSourceScope = (namespace: string, scope: string) =>\n Effect.gen(function* () {\n const rows = yield* listBindingRowsForSourceScope(namespace, scope);\n for (const row of rows) {\n yield* pluginStorage.remove({\n scope,\n collection: BINDING_COLLECTION,\n key: row.key,\n });\n }\n });\n\n return {\n listBindingsBySource: (namespace, scope) =>\n listBindingRowsForSourceScope(namespace, scope).pipe(\n Effect.map((rows) =>\n rows\n .map(rowToBinding)\n .filter(Predicate.isNotNull)\n .map((row) => ({ toolId: row.toolId, binding: row.binding })),\n ),\n ),\n\n getBinding: (toolId, scope) =>\n pluginStorage.getAtScope({ scope, collection: BINDING_COLLECTION, key: toolId }).pipe(\n Effect.map((row) => {\n const binding = row ? rowToBinding(row) : null;\n return binding ? { binding: binding.binding, namespace: binding.namespace } : null;\n }),\n ),\n\n putBindings: (namespace, scope, entries) =>\n Effect.gen(function* () {\n for (const entry of entries) {\n yield* pluginStorage.put({\n scope,\n collection: BINDING_COLLECTION,\n key: entry.toolId,\n data: bindingData(namespace, entry),\n });\n }\n }),\n\n removeBindingsByNamespace: (namespace, scope) => removeBindingsForSourceScope(namespace, scope),\n\n getSource: (namespace, scope) =>\n pluginStorage\n .getAtScope({ scope, collection: SOURCE_COLLECTION, key: namespace })\n .pipe(Effect.map((row) => (row ? rowToSource(row) : null))),\n\n getSourceConfig: (namespace, scope) =>\n pluginStorage.getAtScope({ scope, collection: SOURCE_COLLECTION, key: namespace }).pipe(\n Effect.map((row) => {\n const source = row ? rowToSource(row) : null;\n return source?.config ?? null;\n }),\n ),\n\n putSource: (source) =>\n pluginStorage\n .put({\n scope: source.scope,\n collection: SOURCE_COLLECTION,\n key: source.namespace,\n data: sourceData(source),\n })\n .pipe(Effect.asVoid),\n\n removeSource: (namespace, scope) =>\n Effect.gen(function* () {\n yield* removeBindingsForSourceScope(namespace, scope);\n yield* pluginStorage.remove({\n scope,\n collection: SOURCE_COLLECTION,\n key: namespace,\n });\n }),\n };\n};\n","import {\n Duration,\n Effect,\n Exit,\n Layer,\n Match,\n Option,\n Predicate,\n Result,\n Scope,\n Schema,\n ScopedCache,\n} 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 type CredentialBindingRef,\n type CredentialBindingValue,\n ScopeId,\n SourceDetectionResult,\n ToolResult,\n authToolFailure,\n defaultSourceInstallScopeId,\n definePlugin,\n tool,\n resolveSecretBackedMap as resolveSharedSecretBackedMap,\n type PluginCtx,\n type StaticToolSchema,\n type StorageFailure,\n StorageError,\n type ToolAnnotations,\n} from \"@executor-js/sdk/core\";\nimport {\n compileHttpNamedCredentialMap,\n OAuth2SourceConfig,\n httpCredentialInputToBindingValue,\n type HttpConfiguredValueInput,\n} from \"@executor-js/sdk/http-source\";\n\nimport {\n makeMcpStore,\n mcpSchema,\n type McpBindingStore,\n type McpStoredSource,\n} from \"./binding-store\";\nimport { createMcpConnector, type ConnectorInput, type McpConnection } from \"./connection\";\nimport { discoverTools } from \"./discover\";\nimport {\n McpAuthRequiredError,\n McpConnectionError,\n McpInvocationError,\n McpToolDiscoveryError,\n} from \"./errors\";\nimport { invokeMcpTool } from \"./invoke\";\nimport { deriveMcpNamespace, type McpToolManifest, type McpToolManifestEntry } from \"./manifest\";\nimport { mcpPresets } from \"./presets\";\nimport { probeMcpEndpointShape, type McpShapeProbeResult } from \"./probe-shape\";\nimport {\n MCP_OAUTH_CLIENT_ID_SLOT,\n MCP_OAUTH_CLIENT_SECRET_SLOT,\n MCP_OAUTH_CONNECTION_SLOT,\n McpConnectionAuthInput,\n McpConfiguredValueInput,\n McpCredentialInput,\n McpRemoteTransport,\n McpToolBinding,\n mcpHeaderSlot,\n mcpQueryParamSlot,\n type McpConnectionAuth,\n type McpConfiguredValueInput as McpConfiguredValueInputType,\n SecretBackedValue,\n type McpStoredSourceData,\n type ConfiguredMcpCredentialValue,\n} from \"./types\";\n\nimport {\n type ConfigFileSink,\n type ConfigHeaderValue,\n type McpAuthConfig,\n type McpRemoteSourceConfig as McpRemoteConfigEntry,\n type McpStdioSourceConfig as McpStdioConfigEntry,\n type SourceConfig,\n headerToConfigValue,\n} from \"@executor-js/config\";\n\n// ---------------------------------------------------------------------------\n// Plugin config — discriminated union on transport\n// ---------------------------------------------------------------------------\n\n/**\n * Executor scope id that owns a newly-added MCP source row. Must be one\n * of the executor's configured scopes. Admins adding a shared server at\n * org scope pin here; per-user stdio sources can pin at the inner\n * scope.\n */\ntype McpSourceScopeField = { readonly scope: string };\n\nexport interface McpRemoteSourceConfig extends McpSourceScopeField {\n readonly transport: \"remote\";\n readonly name: string;\n readonly endpoint: string;\n readonly remoteTransport?: \"streamable-http\" | \"sse\" | \"auto\";\n readonly queryParams?: Record<string, McpConfiguredValueInputType>;\n readonly headers?: Record<string, McpConfiguredValueInputType>;\n readonly namespace?: string;\n readonly oauth2?: OAuth2SourceConfig;\n readonly credentials?: McpInitialCredentialsInput;\n}\n\nexport interface McpStdioSourceConfig extends McpSourceScopeField {\n readonly transport: \"stdio\";\n readonly name: string;\n readonly command: string;\n readonly args?: string[];\n readonly env?: Record<string, string>;\n readonly cwd?: string;\n readonly namespace?: string;\n}\n\nexport type McpSourceConfig = McpRemoteSourceConfig | McpStdioSourceConfig;\ntype McpConfigFileRemoteSourceConfig = Omit<\n McpRemoteSourceConfig,\n \"headers\" | \"queryParams\" | \"oauth2\"\n> & {\n readonly headers?: Record<string, McpCredentialInput | McpConfiguredValueInputType>;\n readonly queryParams?: Record<string, McpCredentialInput | McpConfiguredValueInputType>;\n readonly auth?: McpConnectionAuthInput;\n};\ntype McpConfigFileSourceConfig = McpConfigFileRemoteSourceConfig | McpStdioSourceConfig;\n\n// ---------------------------------------------------------------------------\n// Extension types\n// ---------------------------------------------------------------------------\n\n// OAuth start/complete/callback moved to the shared\n// `/scopes/:scopeId/oauth/*` surface in `@executor-js/api` — no\n// plugin-specific types needed here.\n\nexport interface McpProbeResult {\n readonly connected: boolean;\n readonly requiresOAuth: boolean;\n readonly supportsDynamicRegistration: boolean;\n readonly name: string;\n readonly namespace: string;\n readonly toolCount: number | null;\n readonly serverName: string | null;\n}\n\nconst McpConfigureSourcePayloadSchema = Schema.Struct({\n name: Schema.optional(Schema.String),\n endpoint: Schema.optional(Schema.String),\n headers: Schema.optional(Schema.Record(Schema.String, McpCredentialInput)),\n queryParams: Schema.optional(Schema.Record(Schema.String, McpCredentialInput)),\n auth: Schema.optional(McpConnectionAuthInput),\n});\nconst McpConfigureSourceInputSchema = Schema.Struct({\n scope: Schema.String,\n ...McpConfigureSourcePayloadSchema.fields,\n});\nexport type McpConfigureSourceInput = typeof McpConfigureSourceInputSchema.Type;\n\nconst McpInitialCredentialsInputSchema = Schema.Struct({\n scope: Schema.String,\n headers: Schema.optional(Schema.Record(Schema.String, McpCredentialInput)),\n queryParams: Schema.optional(Schema.Record(Schema.String, McpCredentialInput)),\n auth: Schema.optional(McpConnectionAuthInput),\n});\ntype McpInitialCredentialsInput = typeof McpInitialCredentialsInputSchema.Type;\n\nconst McpRemoteAddSourceInputSchema = Schema.Struct({\n transport: Schema.Literal(\"remote\"),\n name: Schema.String,\n endpoint: Schema.String,\n remoteTransport: Schema.optional(McpRemoteTransport),\n queryParams: Schema.optional(Schema.Record(Schema.String, McpConfiguredValueInput)),\n headers: Schema.optional(Schema.Record(Schema.String, McpConfiguredValueInput)),\n namespace: Schema.optional(Schema.String),\n oauth2: Schema.optional(OAuth2SourceConfig),\n credentials: Schema.optional(McpInitialCredentialsInputSchema),\n});\n\nconst McpStdioAddSourceInputSchema = 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 namespace: Schema.optional(Schema.String),\n});\n\nconst McpAddSourceInputSchema = Schema.Union([\n McpRemoteAddSourceInputSchema,\n McpStdioAddSourceInputSchema,\n]);\n\nconst McpAddSourceOutputSchema = Schema.Struct({\n namespace: Schema.String,\n source: Schema.Struct({\n id: Schema.String,\n scope: Schema.String,\n }),\n toolCount: Schema.Number,\n discovery: Schema.optional(\n Schema.Struct({\n status: Schema.Literals([\"ok\", \"failed\"]),\n message: Schema.optional(Schema.String),\n stage: Schema.optional(Schema.String),\n }),\n ),\n});\n\nconst McpProbeEndpointInputSchema = Schema.Struct({\n endpoint: Schema.String,\n headers: Schema.optional(Schema.Record(Schema.String, SecretBackedValue)),\n queryParams: Schema.optional(Schema.Record(Schema.String, SecretBackedValue)),\n});\n\nconst McpProbeEndpointOutputSchema = Schema.Struct({\n connected: Schema.Boolean,\n requiresOAuth: Schema.Boolean,\n supportsDynamicRegistration: Schema.Boolean,\n name: Schema.String,\n namespace: Schema.String,\n toolCount: Schema.NullOr(Schema.Number),\n serverName: Schema.NullOr(Schema.String),\n});\n\nconst McpGetSourceInputSchema = Schema.Struct({\n namespace: Schema.String,\n scope: Schema.String,\n});\n\nconst McpGetSourceOutputSchema = Schema.Struct({\n source: Schema.NullOr(Schema.Unknown),\n});\n\nconst McpStaticConfigureSourceInputSchema = Schema.Struct({\n source: Schema.Struct({\n id: Schema.String,\n scope: Schema.String,\n }),\n scope: Schema.String,\n ...McpConfigureSourcePayloadSchema.fields,\n});\n\nconst McpStaticConfigureSourceOutputSchema = Schema.Struct({\n configured: Schema.Boolean,\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 mcpToolFailure = (code: string, message: string, details?: unknown) =>\n ToolResult.fail({\n code,\n message,\n ...(details === undefined ? {} : { details }),\n });\n\nconst mcpAuthToolFailure = (failure: McpAuthRequiredError) =>\n authToolFailure({\n code: failure.code,\n message: failure.message,\n source: { id: failure.sourceId, scope: failure.sourceScope },\n credential: {\n kind: failure.credentialKind,\n ...(failure.credentialLabel ? { label: failure.credentialLabel } : {}),\n ...(failure.slotKey ? { slotKey: failure.slotKey } : {}),\n ...(failure.secretId ? { secretId: failure.secretId } : {}),\n ...(failure.connectionId ? { connectionId: failure.connectionId } : {}),\n },\n ...(failure.status !== undefined ? { status: failure.status } : {}),\n ...(failure.details !== undefined\n ? {\n upstream: {\n ...(failure.status !== undefined ? { status: failure.status } : {}),\n details: failure.details,\n },\n }\n : {}),\n recovery: { configureSourceTool: \"executor.mcp.configureSource\" },\n });\n\nconst McpAddSourceInputStandardSchema = schemaToStaticToolSchema(McpAddSourceInputSchema);\nconst McpAddSourceOutputStandardSchema = schemaToStaticToolSchema(McpAddSourceOutputSchema);\nconst McpProbeEndpointInputStandardSchema = schemaToStaticToolSchema(McpProbeEndpointInputSchema);\nconst McpProbeEndpointOutputStandardSchema = schemaToStaticToolSchema(McpProbeEndpointOutputSchema);\nconst McpGetSourceInputStandardSchema = schemaToStaticToolSchema(McpGetSourceInputSchema);\nconst McpGetSourceOutputStandardSchema = schemaToStaticToolSchema(McpGetSourceOutputSchema);\nconst McpStaticConfigureSourceInputStandardSchema = schemaToStaticToolSchema(\n McpStaticConfigureSourceInputSchema,\n);\nconst McpStaticConfigureSourceOutputStandardSchema = schemaToStaticToolSchema(\n McpStaticConfigureSourceOutputSchema,\n);\n\nexport type McpProbeEndpointInput = typeof McpProbeEndpointInputSchema.Type;\n\nconst resolveStaticScopeInput = (\n ctx: { readonly scopes: readonly { readonly id: ScopeId; readonly name: string }[] },\n value: string,\n): string =>\n String(\n ctx.scopes.find((scope) => scope.name === value || String(scope.id) === value)?.id ?? value,\n );\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst toStoredSourceData = (\n config: McpSourceConfig,\n remoteCredentials?: {\n readonly headers: Record<string, ConfiguredMcpCredentialValue>;\n readonly queryParams: Record<string, ConfiguredMcpCredentialValue>;\n readonly auth: McpConnectionAuth;\n },\n): McpStoredSourceData => {\n if (config.transport === \"stdio\") {\n return {\n transport: \"stdio\",\n command: config.command,\n args: config.args,\n env: config.env,\n cwd: config.cwd,\n };\n }\n return {\n transport: \"remote\",\n endpoint: config.endpoint,\n remoteTransport: config.remoteTransport ?? \"auto\",\n queryParams: remoteCredentials?.queryParams,\n headers: remoteCredentials?.headers,\n auth: remoteCredentials?.auth ?? { kind: \"none\" },\n };\n};\n\nconst normalizeNamespace = (config: McpSourceConfig): string =>\n config.namespace ??\n deriveMcpNamespace({\n name: config.name,\n endpoint: config.transport === \"remote\" ? config.endpoint : undefined,\n command: config.transport === \"stdio\" ? config.command : undefined,\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\nconst toBinding = (entry: McpToolManifestEntry): McpToolBinding =>\n McpToolBinding.make({\n toolId: entry.toolId,\n toolName: entry.toolName,\n description: entry.description,\n inputSchema: entry.inputSchema,\n outputSchema: entry.outputSchema,\n annotations: entry.annotations,\n });\n\nconst MCP_PLUGIN_ID = \"mcp\";\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.\n * Boundary chars are everything non-alphanumeric, so `/api/mcp`,\n * `mcp.example.com`, `mcp-server`, and `mcp_v1` all match while\n * `mcphost.com` and `/mcpstore` do not. */\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 * The technical `reason` (`401 without Bearer WWW-Authenticate — not an\n * MCP auth challenge`, etc.) stays in telemetry via the probe span; the\n * user gets a sentence pointing at their next step. 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\nconst scopeRanks = (ctx: PluginCtx<McpBindingStore>): ReadonlyMap<string, number> =>\n new Map(ctx.scopes.map((scope, index) => [String(scope.id), index]));\n\nconst scopeRank = (ranks: ReadonlyMap<string, number>, scopeId: string): number =>\n ranks.get(scopeId) ?? Infinity;\n\nconst resolveMcpSourceBinding = (\n ctx: PluginCtx<McpBindingStore>,\n sourceId: string,\n sourceScope: string,\n slot: string,\n): Effect.Effect<CredentialBindingRef | null, StorageFailure> =>\n Effect.gen(function* () {\n const ranks = scopeRanks(ctx);\n const sourceSourceRank = scopeRank(ranks, sourceScope);\n if (sourceSourceRank === Infinity) return null;\n const bindings = yield* ctx.credentialBindings.listForSource({\n pluginId: MCP_PLUGIN_ID,\n sourceId,\n sourceScope: ScopeId.make(sourceScope),\n });\n const binding = bindings\n .filter(\n (candidate) =>\n candidate.slotKey === slot && scopeRank(ranks, candidate.scopeId) <= sourceSourceRank,\n )\n .sort((a, b) => scopeRank(ranks, a.scopeId) - scopeRank(ranks, b.scopeId))[0];\n return binding ?? null;\n });\n\nconst validateMcpBindingTarget = (\n ctx: PluginCtx<McpBindingStore>,\n input: {\n readonly sourceScope: string;\n readonly targetScope: string;\n readonly sourceId: string;\n },\n): Effect.Effect<void, StorageFailure> =>\n Effect.gen(function* () {\n const ranks = scopeRanks(ctx);\n const sourceSourceRank = scopeRank(ranks, input.sourceScope);\n const targetRank = scopeRank(ranks, input.targetScope);\n const scopeList = `[${ctx.scopes.map((s) => s.id).join(\", \")}]`;\n if (sourceSourceRank === Infinity) {\n return yield* new StorageError({\n message:\n `MCP source binding references source scope \"${input.sourceScope}\" ` +\n `which is not in the executor's scope stack ${scopeList}.`,\n cause: undefined,\n });\n }\n if (targetRank === Infinity) {\n return yield* new StorageError({\n message:\n `MCP source binding targets scope \"${input.targetScope}\" which is not ` +\n `in the executor's scope stack ${scopeList}.`,\n cause: undefined,\n });\n }\n if (targetRank > sourceSourceRank) {\n return yield* new StorageError({\n message:\n `MCP source bindings for \"${input.sourceId}\" cannot be written at ` +\n `outer scope \"${input.targetScope}\" because the base source lives at ` +\n `\"${input.sourceScope}\"`,\n cause: undefined,\n });\n }\n });\n\nconst canonicalizeCredentialMap = compileHttpNamedCredentialMap;\n\nconst canonicalizeConfiguredValueMap = (\n values: Record<string, McpConfiguredValueInputType> | undefined,\n slotForName: (name: string) => string,\n): Record<string, ConfiguredMcpCredentialValue> => {\n const next: Record<string, ConfiguredMcpCredentialValue> = {};\n for (const [name, value] of Object.entries(values ?? {})) {\n if (typeof value === \"string\") {\n next[name] = value;\n continue;\n }\n next[name] = {\n kind: \"binding\",\n slot: slotForName(name),\n prefix: value.prefix,\n };\n }\n return next;\n};\n\nconst resolveConfiguredValueMap = (\n values: Record<string, HttpConfiguredValueInput> | undefined,\n): Record<string, string> | undefined => {\n if (!values) return undefined;\n const resolved: Record<string, string> = {};\n for (const [name, value] of Object.entries(values)) {\n if (typeof value === \"string\") resolved[name] = value;\n }\n return Object.keys(resolved).length > 0 ? resolved : undefined;\n};\n\nconst authFromOAuth2Source = (oauth2: OAuth2SourceConfig | undefined): McpConnectionAuth =>\n oauth2\n ? {\n kind: \"oauth2\",\n connectionSlot: oauth2.connectionSlot,\n clientIdSlot: oauth2.clientIdSlot,\n ...(oauth2.clientSecretSlot ? { clientSecretSlot: oauth2.clientSecretSlot } : {}),\n }\n : { kind: \"none\" };\n\nconst canonicalizeAuth = (\n auth: McpConnectionAuthInput | undefined,\n): {\n readonly auth: McpConnectionAuth;\n readonly bindings: ReadonlyArray<{\n readonly slot: string;\n readonly value: CredentialBindingValue;\n readonly targetScope?: string;\n }>;\n} => {\n if (!auth || \"kind\" in auth || !auth.oauth2) return { auth: { kind: \"none\" }, bindings: [] };\n const oauth = auth.oauth2;\n const bindings: Array<{ slot: string; value: CredentialBindingValue; targetScope?: string }> = [];\n if (oauth.connection) {\n bindings.push({\n slot: MCP_OAUTH_CONNECTION_SLOT,\n value: httpCredentialInputToBindingValue(oauth.connection),\n });\n }\n if (oauth.clientId) {\n bindings.push({\n slot: MCP_OAUTH_CLIENT_ID_SLOT,\n value: httpCredentialInputToBindingValue(oauth.clientId),\n });\n }\n if (oauth.clientSecret) {\n bindings.push({\n slot: MCP_OAUTH_CLIENT_SECRET_SLOT,\n value: httpCredentialInputToBindingValue(oauth.clientSecret),\n });\n }\n return {\n auth: {\n kind: \"oauth2\",\n connectionSlot: MCP_OAUTH_CONNECTION_SLOT,\n ...(oauth.clientId ? { clientIdSlot: MCP_OAUTH_CLIENT_ID_SLOT } : {}),\n ...(oauth.clientSecret ? { clientSecretSlot: MCP_OAUTH_CLIENT_SECRET_SLOT } : {}),\n },\n bindings,\n };\n};\n\n// ---------------------------------------------------------------------------\n// MCP-SDK OAuth provider adapter — builds the `OAuthClientProvider` the\n// MCP SDK's StreamableHTTP/SSE transports want, wrapping a pre-resolved\n// access token.\n//\n// Refresh is NOT driven through this provider — `ctx.connections.access\n// Token` owns that lifecycle at the core level via the canonical\n// \"oauth2\" ConnectionProvider. This adapter only injects the current\n// token into the transport's Authorization header and fails loudly if\n// the SDK ever tries to initiate a new OAuth flow (which would bypass\n// our refresh machinery).\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\nconst resolveSecretBackedMap = (\n values: Record<string, SecretBackedValue> | undefined,\n ctx: PluginCtx<McpBindingStore>,\n): Effect.Effect<Record<string, string> | undefined, McpConnectionError | StorageFailure> =>\n resolveSharedSecretBackedMap({\n values,\n getSecret: ctx.secrets.get,\n onMissing: (_name, value) =>\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve secret \"${value.secretId}\"`,\n }),\n onError: (err, _name, value) =>\n Predicate.isTagged(\"SecretOwnedByConnectionError\")(err)\n ? new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve secret \"${value.secretId}\"`,\n })\n : err,\n }).pipe(\n Effect.mapError((err) =>\n Predicate.isTagged(\"SecretOwnedByConnectionError\")(err)\n ? new McpConnectionError({ transport: \"remote\", message: \"Failed to resolve secret\" })\n : err,\n ),\n );\n\nconst credentialInputMapToConfigValues = (\n values: Record<string, McpConfiguredValueInputType | McpCredentialInput> | undefined,\n): Record<string, ConfigHeaderValue> | undefined => {\n if (!values) return undefined;\n const out: Record<string, ConfigHeaderValue> = {};\n for (const [name, value] of Object.entries(values)) {\n if (typeof value === \"string\") {\n out[name] = value;\n continue;\n }\n if (value.kind === \"secret\" && \"secretId\" in value) {\n out[name] = headerToConfigValue({ secretId: value.secretId, prefix: value.prefix });\n continue;\n }\n if (value.kind === \"text\") {\n out[name] = value.prefix ? `${value.prefix}${value.text}` : value.text;\n }\n }\n return Object.keys(out).length > 0 ? out : undefined;\n};\n\nconst resolveMcpBindingValueMap = (\n ctx: PluginCtx<McpBindingStore>,\n values: Record<string, ConfiguredMcpCredentialValue> | undefined,\n params: {\n readonly sourceId: string;\n readonly sourceScope: string;\n readonly targetScope?: string;\n readonly missingLabel: string;\n },\n): Effect.Effect<Record<string, string> | undefined, McpAuthRequiredError | StorageFailure> =>\n Effect.gen(function* () {\n if (!values) return undefined;\n const resolved: Record<string, string> = {};\n for (const [name, value] of Object.entries(values)) {\n if (typeof value === \"string\") {\n resolved[name] = value;\n continue;\n }\n const binding = yield* resolveMcpSourceBinding(\n ctx,\n params.sourceId,\n params.sourceScope,\n value.slot,\n );\n if (binding?.value.kind === \"secret\") {\n const secretBinding = binding.value;\n const secret = yield* ctx.secrets.getAtScope(secretBinding.secretId, binding.scopeId).pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () =>\n Effect.fail(\n new McpAuthRequiredError({\n code: \"credential_secret_missing\",\n sourceId: params.sourceId,\n sourceScope: params.sourceScope,\n credentialKind: \"secret\",\n credentialLabel: name,\n slotKey: value.slot,\n secretId: String(secretBinding.secretId),\n message: `Failed to resolve secret for ${params.missingLabel} \"${name}\"`,\n }),\n ),\n ),\n );\n if (secret === null) {\n return yield* new McpAuthRequiredError({\n code: \"credential_secret_missing\",\n sourceId: params.sourceId,\n sourceScope: params.sourceScope,\n credentialKind: \"secret\",\n credentialLabel: name,\n slotKey: value.slot,\n secretId: String(secretBinding.secretId),\n message: `Missing secret \"${secretBinding.secretId}\" for ${params.missingLabel} \"${name}\"`,\n });\n }\n resolved[name] = value.prefix ? `${value.prefix}${secret}` : secret;\n continue;\n }\n if (binding?.value.kind === \"text\") {\n resolved[name] = value.prefix ? `${value.prefix}${binding.value.text}` : binding.value.text;\n continue;\n }\n return yield* new McpAuthRequiredError({\n code: \"credential_binding_missing\",\n sourceId: params.sourceId,\n sourceScope: params.sourceScope,\n credentialKind: \"secret\",\n credentialLabel: name,\n slotKey: value.slot,\n message: `Missing binding for ${params.missingLabel} \"${name}\"`,\n });\n }\n return Object.keys(resolved).length > 0 ? resolved : undefined;\n });\n\nconst resolveInitialMcpCredentialValueMap = (\n ctx: PluginCtx<McpBindingStore>,\n values: Record<string, ConfiguredMcpCredentialValue>,\n bindings: ReadonlyArray<{ readonly slot: string; readonly value: CredentialBindingValue }>,\n targetScope: string,\n missingLabel: string,\n): Effect.Effect<Record<string, string> | undefined, McpConnectionError | StorageFailure> =>\n Effect.gen(function* () {\n const bySlot = new Map(bindings.map((binding) => [binding.slot, binding.value] as const));\n const resolved: Record<string, string> = {};\n for (const [name, value] of Object.entries(values)) {\n if (typeof value === \"string\") {\n resolved[name] = value;\n continue;\n }\n const binding = bySlot.get(value.slot);\n if (binding?.kind === \"secret\") {\n const secret = yield* ctx.secrets\n .getAtScope(binding.secretId, binding.secretScopeId ?? ScopeId.make(targetScope))\n .pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () =>\n Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve secret for ${missingLabel} \"${name}\"`,\n }),\n ),\n ),\n );\n if (secret === null) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: `Missing secret \"${binding.secretId}\" for ${missingLabel} \"${name}\"`,\n });\n }\n resolved[name] = value.prefix ? `${value.prefix}${secret}` : secret;\n continue;\n }\n if (binding?.kind === \"text\") {\n resolved[name] = value.prefix ? `${value.prefix}${binding.text}` : binding.text;\n }\n }\n return Object.keys(resolved).length > 0 ? resolved : undefined;\n });\n\nconst resolveInitialMcpOauthProvider = (\n ctx: PluginCtx<McpBindingStore>,\n bindings: ReadonlyArray<{ readonly slot: string; readonly value: CredentialBindingValue }>,\n targetScope: string,\n): Effect.Effect<OAuthClientProvider | undefined, McpConnectionError | StorageFailure> =>\n Effect.gen(function* () {\n const connection = bindings.find(\n (binding) =>\n binding.slot === MCP_OAUTH_CONNECTION_SLOT && binding.value.kind === \"connection\",\n );\n if (!connection || connection.value.kind !== \"connection\") return undefined;\n const connectionId = connection.value.connectionId;\n const accessToken = yield* ctx.connections\n .accessTokenAtScope(connectionId, ScopeId.make(targetScope))\n .pipe(\n Effect.mapError(\n ({ message }) =>\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve OAuth connection \"${connectionId}\": ${message}`,\n }),\n ),\n );\n return makeOAuthProvider(accessToken);\n });\n\nconst resolveMcpHeaderAuth = (\n ctx: PluginCtx<McpBindingStore>,\n sourceId: string,\n sourceScope: string,\n auth: McpConnectionAuth,\n): Effect.Effect<Record<string, string>, McpAuthRequiredError | StorageFailure> =>\n Effect.gen(function* () {\n if (auth.kind !== \"header\") return {};\n const binding = yield* resolveMcpSourceBinding(ctx, sourceId, sourceScope, auth.secretSlot);\n if (binding?.value.kind === \"secret\") {\n const secretBinding = binding.value;\n const secret = yield* ctx.secrets.getAtScope(secretBinding.secretId, binding.scopeId).pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () =>\n Effect.fail(\n new McpAuthRequiredError({\n code: \"credential_secret_missing\",\n sourceId,\n sourceScope,\n credentialKind: \"secret\",\n credentialLabel: auth.headerName,\n slotKey: auth.secretSlot,\n secretId: String(secretBinding.secretId),\n message: `Failed to resolve header auth binding \"${auth.secretSlot}\"`,\n }),\n ),\n ),\n );\n if (secret === null) {\n return yield* new McpAuthRequiredError({\n code: \"credential_secret_missing\",\n sourceId,\n sourceScope,\n credentialKind: \"secret\",\n credentialLabel: auth.headerName,\n slotKey: auth.secretSlot,\n secretId: String(secretBinding.secretId),\n message: `Missing secret for header auth binding \"${auth.secretSlot}\"`,\n });\n }\n return { [auth.headerName]: auth.prefix ? `${auth.prefix}${secret}` : secret };\n }\n if (binding?.value.kind === \"text\") {\n return {\n [auth.headerName]: auth.prefix ? `${auth.prefix}${binding.value.text}` : binding.value.text,\n };\n }\n return yield* new McpAuthRequiredError({\n code: \"credential_binding_missing\",\n sourceId,\n sourceScope,\n credentialKind: \"secret\",\n credentialLabel: auth.headerName,\n slotKey: auth.secretSlot,\n message: `Missing header auth binding \"${auth.secretSlot}\"`,\n });\n });\n\nconst resolveMcpStoredOauthProvider = (\n ctx: PluginCtx<McpBindingStore>,\n sourceId: string,\n sourceScope: string,\n auth: McpConnectionAuth,\n): Effect.Effect<OAuthClientProvider | undefined, McpAuthRequiredError | StorageFailure> =>\n Effect.gen(function* () {\n if (auth.kind !== \"oauth2\") return undefined;\n const binding = yield* resolveMcpSourceBinding(ctx, sourceId, sourceScope, auth.connectionSlot);\n if (binding?.value.kind !== \"connection\") {\n return yield* new McpAuthRequiredError({\n code: \"oauth_connection_missing\",\n sourceId,\n sourceScope,\n credentialKind: \"connection\",\n credentialLabel: \"OAuth sign-in\",\n slotKey: auth.connectionSlot,\n message: `Missing OAuth connection binding for MCP source \"${sourceId}\"`,\n });\n }\n const connectionId = binding.value.connectionId;\n const accessToken = yield* ctx.connections\n .accessTokenAtScope(connectionId, binding.scopeId)\n .pipe(\n Effect.catchTags({\n ConnectionReauthRequiredError: ({ message, connectionId: failedConnectionId }) =>\n Effect.fail(\n new McpAuthRequiredError({\n code: \"oauth_reauth_required\",\n sourceId,\n sourceScope,\n credentialKind: \"oauth\",\n credentialLabel: \"OAuth sign-in\",\n slotKey: auth.connectionSlot,\n connectionId: String(failedConnectionId),\n message: `OAuth connection \"${failedConnectionId}\" needs re-authentication: ${message}`,\n }),\n ),\n ConnectionNotFoundError: ({ connectionId: failedConnectionId }) =>\n Effect.fail(\n new McpAuthRequiredError({\n code: \"oauth_connection_missing\",\n sourceId,\n sourceScope,\n credentialKind: \"connection\",\n credentialLabel: \"OAuth sign-in\",\n slotKey: auth.connectionSlot,\n connectionId: String(failedConnectionId),\n message: `OAuth connection \"${failedConnectionId}\" was not found for MCP source \"${sourceId}\"`,\n }),\n ),\n ConnectionProviderNotRegisteredError: ({ provider }) =>\n Effect.fail(\n new McpAuthRequiredError({\n code: \"oauth_connection_failed\",\n sourceId,\n sourceScope,\n credentialKind: \"oauth\",\n credentialLabel: \"OAuth sign-in\",\n slotKey: auth.connectionSlot,\n connectionId: String(connectionId),\n message: `OAuth provider \"${provider}\" is not registered`,\n }),\n ),\n ConnectionRefreshNotSupportedError: ({ provider, connectionId: failedConnectionId }) =>\n Effect.fail(\n new McpAuthRequiredError({\n code: \"oauth_connection_failed\",\n sourceId,\n sourceScope,\n credentialKind: \"oauth\",\n credentialLabel: \"OAuth sign-in\",\n slotKey: auth.connectionSlot,\n connectionId: String(failedConnectionId),\n message: `OAuth provider \"${provider}\" cannot refresh connection \"${failedConnectionId}\"`,\n }),\n ),\n ConnectionRefreshError: ({ message, connectionId: failedConnectionId }) =>\n Effect.fail(\n new McpAuthRequiredError({\n code: \"oauth_connection_failed\",\n sourceId,\n sourceScope,\n credentialKind: \"oauth\",\n credentialLabel: \"OAuth sign-in\",\n slotKey: auth.connectionSlot,\n connectionId: String(failedConnectionId),\n message: `OAuth connection \"${failedConnectionId}\" refresh failed: ${message}`,\n }),\n ),\n }),\n );\n return makeOAuthProvider(accessToken);\n });\n\n// ---------------------------------------------------------------------------\n// Shared connector resolution — reads secrets, builds stdio/remote input\n// ---------------------------------------------------------------------------\n\nconst resolveConnectorInput = (\n sourceId: string,\n sourceScope: string,\n sd: McpStoredSourceData,\n ctx: PluginCtx<McpBindingStore>,\n allowStdio: boolean,\n): Effect.Effect<ConnectorInput, McpAuthRequiredError | McpConnectionError | StorageFailure> => {\n if (sd.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: sd.command,\n args: sd.args,\n env: sd.env,\n cwd: sd.cwd,\n });\n }\n\n return Effect.gen(function* () {\n const resolvedHeaders = yield* resolveMcpBindingValueMap(ctx, sd.headers, {\n sourceId,\n sourceScope,\n missingLabel: \"header\",\n });\n const resolvedQueryParams = yield* resolveMcpBindingValueMap(ctx, sd.queryParams, {\n sourceId,\n sourceScope,\n missingLabel: \"query parameter\",\n });\n const headers: Record<string, string> = { ...(resolvedHeaders ?? {}) };\n\n const auth = sd.auth;\n if (auth.kind === \"header\") {\n Object.assign(headers, yield* resolveMcpHeaderAuth(ctx, sourceId, sourceScope, auth));\n }\n const authProvider = yield* resolveMcpStoredOauthProvider(ctx, sourceId, sourceScope, auth);\n\n return {\n transport: \"remote\" as const,\n endpoint: sd.endpoint,\n remoteTransport: sd.remoteTransport,\n queryParams: resolvedQueryParams,\n headers: Object.keys(headers).length > 0 ? headers : undefined,\n authProvider,\n };\n });\n};\n\n// ---------------------------------------------------------------------------\n// Connection cache — kept as plugin-module state so both invokeTool and\n// the close hook see the same ScopedCache instance. The ScopedCache's\n// lookup key is the stringified stored source data identity.\n// ---------------------------------------------------------------------------\n\ninterface McpRuntime {\n readonly connectionCache: ScopedCache.ScopedCache<\n string,\n McpConnection,\n McpAuthRequiredError | McpConnectionError\n >;\n readonly pendingConnectors: Map<\n string,\n Effect.Effect<McpConnection, McpAuthRequiredError | McpConnectionError>\n >;\n readonly cacheScope: Scope.Closeable;\n}\n\nconst makeRuntime = (): Effect.Effect<McpRuntime, never> =>\n Effect.gen(function* () {\n const cacheScope = yield* Scope.make();\n const pendingConnectors = new Map<\n string,\n Effect.Effect<McpConnection, McpAuthRequiredError | McpConnectionError>\n >();\n const connectionCache = yield* ScopedCache.make({\n lookup: (key: string) =>\n Effect.acquireRelease(\n Effect.suspend(() => {\n const connector = pendingConnectors.get(key);\n if (!connector) {\n return Effect.fail(\n new McpConnectionError({\n transport: \"auto\",\n message: `No pending connector for key: ${key}`,\n }),\n );\n }\n return connector;\n }),\n (connection) =>\n Effect.ignore(\n Effect.tryPromise({\n try: () => connection.close(),\n catch: () =>\n new McpConnectionError({\n transport: \"auto\",\n message: \"Failed to close MCP connection\",\n }),\n }),\n ),\n ),\n capacity: 64,\n timeToLive: Duration.minutes(5),\n }).pipe(Scope.provide(cacheScope));\n\n return { connectionCache, pendingConnectors, cacheScope };\n });\n\n// ---------------------------------------------------------------------------\n// Plugin factory\n// ---------------------------------------------------------------------------\n\nexport interface McpPluginOptions {\n /**\n * Allow configuring stdio-transport MCP sources. Off by default.\n *\n * Stdio sources 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 /** If provided, source add/remove is mirrored to executor.jsonc\n * (best-effort — file errors are logged, not raised). */\n readonly configFile?: ConfigFileSink;\n}\n\nconst authToConfig = (auth: McpConnectionAuthInput | undefined): McpAuthConfig | undefined => {\n if (!auth) return undefined;\n if (\"kind\" in auth) return { kind: \"none\" };\n const connection = auth.oauth2?.connection;\n if (!connection || typeof connection === \"string\" || connection.kind !== \"connection\") {\n return undefined;\n }\n return {\n kind: \"oauth2\",\n connectionId: connection.connectionId,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Storage-form → input-form reconstruction\n//\n// `toMcpConfigEntry` consumes the `McpSourceConfig` *input* shape — the\n// configure form, which `authToConfig` and `credentialInputMapToConfigValues`\n// know how to render into the file. Stored remote data\n// is in slot form (`secretSlot`, `{kind: \"binding\", slot}`), so writing\n// the file from a stored row needs the slot → secret/connection lookups\n// realized first. Walk the source's `credential_binding` rows and rebuild\n// the input shape; any slot whose binding is missing is dropped.\n// ---------------------------------------------------------------------------\n\nconst toCredentialInput = (\n bySlot: Map<string, CredentialBindingValue>,\n configured: ConfiguredMcpCredentialValue,\n): McpCredentialInput | undefined => {\n if (typeof configured === \"string\") return configured;\n const value = bySlot.get(configured.slot);\n if (!value) return undefined;\n if (value.kind === \"secret\") {\n return {\n kind: \"secret\",\n secretId: value.secretId,\n ...(value.secretScopeId ? { secretScope: value.secretScopeId } : {}),\n ...(configured.prefix ? { prefix: configured.prefix } : {}),\n };\n }\n if (value.kind === \"text\") return value.text;\n // headers / queryParams cannot reference connections — only auth can.\n return undefined;\n};\n\nconst toCredentialInputMap = (\n bySlot: Map<string, CredentialBindingValue>,\n values: Record<string, ConfiguredMcpCredentialValue> | undefined,\n): Record<string, McpCredentialInput> | undefined => {\n if (!values) return undefined;\n const out: Record<string, McpCredentialInput> = {};\n for (const [name, configured] of Object.entries(values)) {\n const input = toCredentialInput(bySlot, configured);\n if (input !== undefined) out[name] = input;\n }\n return Object.keys(out).length > 0 ? out : undefined;\n};\n\nconst toAuthInput = (\n bySlot: Map<string, CredentialBindingValue>,\n auth: McpConnectionAuth,\n): McpConnectionAuthInput | undefined => {\n if (auth.kind === \"none\") return { kind: \"none\" };\n if (auth.kind === \"header\") {\n const value = bySlot.get(auth.secretSlot);\n if (value?.kind !== \"secret\") return undefined;\n return {\n kind: \"none\",\n };\n }\n const connection = bySlot.get(auth.connectionSlot);\n return {\n oauth2: {\n ...(connection?.kind === \"connection\"\n ? { connection: { kind: \"connection\" as const, connectionId: connection.connectionId } }\n : {}),\n },\n };\n};\n\nconst inputFormFromStored = (\n bindings: ReadonlyArray<CredentialBindingRef>,\n stored: McpStoredSourceData,\n scope: string,\n sourceName: string,\n namespace: string,\n): McpConfigFileSourceConfig => {\n if (stored.transport === \"stdio\") {\n return {\n transport: \"stdio\",\n scope,\n name: sourceName,\n namespace,\n command: stored.command,\n args: stored.args ? [...stored.args] : undefined,\n env: stored.env,\n cwd: stored.cwd,\n };\n }\n const bySlot = new Map(bindings.map((b) => [b.slotKey, b.value] as const));\n return {\n transport: \"remote\",\n scope,\n name: sourceName,\n namespace,\n endpoint: stored.endpoint,\n remoteTransport: stored.remoteTransport,\n headers: toCredentialInputMap(bySlot, stored.headers),\n queryParams: toCredentialInputMap(bySlot, stored.queryParams),\n auth: toAuthInput(bySlot, stored.auth),\n };\n};\n\nconst toMcpConfigEntry = (\n namespace: string,\n sourceName: string,\n config: McpConfigFileSourceConfig,\n): SourceConfig => {\n if (config.transport === \"stdio\") {\n const entry: McpStdioConfigEntry = {\n kind: \"mcp\",\n transport: \"stdio\",\n name: sourceName,\n command: config.command,\n args: config.args,\n env: config.env,\n cwd: config.cwd,\n namespace,\n };\n return entry;\n }\n const entry: McpRemoteConfigEntry = {\n kind: \"mcp\",\n transport: \"remote\",\n name: sourceName,\n endpoint: config.endpoint,\n remoteTransport: config.remoteTransport,\n queryParams: credentialInputMapToConfigValues(config.queryParams),\n headers: credentialInputMapToConfigValues(config.headers),\n namespace,\n auth: authToConfig(config.auth),\n };\n return entry;\n};\n\nexport const mcpPlugin = definePlugin((options?: McpPluginOptions) => {\n const allowStdio = options?.dangerouslyAllowStdioMCP ?? false;\n // Per-plugin-instance runtime holder. Captured by closures in\n // `extension`, `invokeTool`, and `close`, so all three see the same\n // connection cache across a single createExecutor lifecycle.\n const runtimeRef: { current: McpRuntime | null } = { current: null };\n\n const ensureRuntime = (): Effect.Effect<McpRuntime, never> =>\n runtimeRef.current\n ? Effect.succeed(runtimeRef.current)\n : makeRuntime().pipe(\n Effect.tap((rt) =>\n Effect.sync(() => {\n runtimeRef.current = rt;\n }),\n ),\n );\n\n return {\n id: \"mcp\" as const,\n packageName: \"@executor-js/plugin-mcp\",\n sourcePresets: allowStdio\n ? mcpPresets.map((preset) => ({\n ...preset,\n transport: \"transport\" in preset ? preset.transport : \"remote\",\n }))\n : mcpPresets\n .filter((preset) => !(\"transport\" in preset && preset.transport === \"stdio\"))\n .map((preset) => ({\n ...preset,\n transport: \"remote\" as const,\n })),\n // Surfaced to the client bundle via the Vite plugin (see\n // `@executor-js/vite-plugin`). The MCP `./client` factory reads\n // `allowStdio` and gates the stdio tab + presets in AddMcpSource —\n // so the server's `dangerouslyAllowStdioMCP` flag is the single\n // source of truth for both runtime and UI.\n clientConfig: { allowStdio },\n schema: mcpSchema,\n storage: (deps): McpBindingStore => makeMcpStore(deps),\n\n extension: (ctx) => {\n const httpClientLayer = options?.httpClientLayer ?? ctx.httpClientLayer;\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 namespace = deriveMcpNamespace({ endpoint: trimmed });\n\n const probeHeaders =\n typeof input === \"string\"\n ? undefined\n : yield* resolveSecretBackedMap(input.headers, ctx);\n const probeQueryParams =\n typeof input === \"string\"\n ? undefined\n : yield* resolveSecretBackedMap(input.queryParams, ctx);\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 requiresOAuth: false,\n supportsDynamicRegistration: false,\n name: result.manifest.server?.name ?? name,\n namespace,\n toolCount: result.manifest.tools.length,\n serverName: result.manifest.server?.name ?? null,\n } satisfies McpProbeResult;\n }\n\n // Before asking the core OAuth service to look for metadata,\n // confirm the endpoint actually speaks MCP. An OAuth-protected\n // non-MCP service (e.g. a GraphQL API whose host publishes\n // RFC 9728 + 8414 metadata) would otherwise pass the OAuth\n // probe and be misclassified as MCP. The shape probe rejects\n // anything whose initialize response isn't 2xx or 401+Bearer.\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\n .probe({\n endpoint: trimmed,\n headers: probeHeaders,\n queryParams: probeQueryParams,\n })\n .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 requiresOAuth: true,\n supportsDynamicRegistration: probeResult.oauth.supportsDynamicRegistration,\n name,\n namespace,\n toolCount: null,\n serverName: null,\n } satisfies McpProbeResult;\n }\n\n return yield* new McpConnectionError({\n transport: \"remote\",\n message:\n \"This server requires authentication, but OAuth metadata wasn't found. Add credentials (Authorization header, query parameter, or API key) below and retry.\",\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 configFile = options?.configFile;\n\n const addSource = (config: McpSourceConfig) =>\n Effect.gen(function* () {\n const namespace = normalizeNamespace(config);\n const canonicalRemote =\n config.transport === \"remote\"\n ? {\n headers: canonicalizeConfiguredValueMap(config.headers, mcpHeaderSlot),\n queryParams: canonicalizeConfiguredValueMap(\n config.queryParams,\n mcpQueryParamSlot,\n ),\n }\n : null;\n const initialRemote =\n config.transport === \"remote\" && config.credentials\n ? {\n scope: config.credentials.scope,\n headers:\n config.credentials.headers !== undefined\n ? canonicalizeCredentialMap(config.credentials.headers, mcpHeaderSlot)\n : null,\n queryParams:\n config.credentials.queryParams !== undefined\n ? canonicalizeCredentialMap(config.credentials.queryParams, mcpQueryParamSlot)\n : null,\n auth:\n config.credentials.auth !== undefined\n ? canonicalizeAuth(config.credentials.auth)\n : null,\n }\n : null;\n const remoteAuth =\n config.transport === \"remote\"\n ? config.oauth2\n ? authFromOAuth2Source(config.oauth2)\n : (initialRemote?.auth?.auth ?? ({ kind: \"none\" } as McpConnectionAuth))\n : null;\n const remoteCredentials =\n canonicalRemote && remoteAuth\n ? {\n headers: canonicalRemote.headers,\n queryParams: canonicalRemote.queryParams,\n auth: remoteAuth,\n }\n : undefined;\n const initialBindings = [\n ...(initialRemote?.headers?.bindings ?? []),\n ...(initialRemote?.queryParams?.bindings ?? []),\n ...(initialRemote?.auth?.bindings ?? []),\n ];\n if (initialRemote && initialBindings.length > 0) {\n yield* validateMcpBindingTarget(ctx, {\n sourceId: namespace,\n sourceScope: config.scope,\n targetScope: initialRemote.scope,\n });\n }\n const sd = toStoredSourceData(config, remoteCredentials);\n\n // Stdio sources are gated — a resolver failure there is a\n // config error the admin must fix before the source makes\n // sense to persist at all. For remote sources we defer the\n // resolver failure: auth might not be ready yet (oauth2\n // connection awaiting per-user sign-in, header secret\n // awaiting upload) but the source row should still land so\n // it shows up in the list and exposes a Sign-in affordance.\n const initialQueryParams =\n initialRemote?.queryParams &&\n (yield* resolveInitialMcpCredentialValueMap(\n ctx,\n canonicalRemote?.queryParams ?? initialRemote.queryParams.values,\n initialRemote.queryParams.bindings,\n initialRemote.scope,\n \"query parameter\",\n ));\n const initialHeaders =\n initialRemote?.headers &&\n (yield* resolveInitialMcpCredentialValueMap(\n ctx,\n canonicalRemote?.headers ?? initialRemote.headers.values,\n initialRemote.headers.bindings,\n initialRemote.scope,\n \"header\",\n ));\n const remoteQueryParams = {\n ...(config.transport === \"remote\"\n ? (resolveConfiguredValueMap(config.queryParams) ?? {})\n : {}),\n ...(initialQueryParams || {}),\n };\n const remoteHeaders = {\n ...(config.transport === \"remote\"\n ? (resolveConfiguredValueMap(config.headers) ?? {})\n : {}),\n ...(initialHeaders || {}),\n };\n const initialAuthProvider =\n initialRemote?.auth !== null && initialRemote?.auth !== undefined\n ? yield* resolveInitialMcpOauthProvider(\n ctx,\n initialRemote.auth.bindings,\n initialRemote.scope,\n )\n : undefined;\n const resolved: Result.Result<\n ConnectorInput,\n McpAuthRequiredError | McpConnectionError | StorageFailure\n > =\n config.transport === \"remote\"\n ? Result.succeed({\n transport: \"remote\" as const,\n endpoint: config.endpoint,\n remoteTransport: config.remoteTransport ?? \"auto\",\n queryParams:\n Object.keys(remoteQueryParams).length > 0 ? remoteQueryParams : undefined,\n headers: Object.keys(remoteHeaders).length > 0 ? remoteHeaders : undefined,\n authProvider: initialAuthProvider,\n })\n : yield* resolveConnectorInput(namespace, config.scope, sd, ctx, allowStdio).pipe(\n Effect.result,\n Effect.withSpan(\"mcp.plugin.resolve_connector\", {\n attributes: {\n \"mcp.source.namespace\": namespace,\n \"mcp.source.transport\": sd.transport,\n },\n }),\n );\n\n if (Result.isFailure(resolved) && sd.transport === \"stdio\") {\n if (Predicate.isTagged(resolved.failure, \"McpAuthRequiredError\")) {\n return yield* new McpConnectionError({\n transport: sd.transport,\n message: resolved.failure.message,\n });\n }\n return yield* Effect.fail(resolved.failure);\n }\n\n // Try discovery only if we have a live connector input.\n // Otherwise fall straight through to the persist step with\n // an empty manifest and surface the resolver failure to\n // the caller at the end.\n const discovery: Result.Result<\n McpToolManifest,\n McpAuthRequiredError | McpToolDiscoveryError | McpConnectionError | StorageFailure\n > = Result.isSuccess(resolved)\n ? yield* discoverTools(createMcpConnector(resolved.success)).pipe(\n Effect.mapError(\n ({ message }) =>\n new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: `MCP discovery failed: ${message}`,\n }),\n ),\n Effect.result,\n Effect.withSpan(\"mcp.plugin.discover_tools\", {\n attributes: { \"mcp.source.namespace\": namespace },\n }),\n )\n : Result.fail(resolved.failure);\n const manifest = Result.isSuccess(discovery)\n ? discovery.success\n : { server: undefined, tools: [] as const };\n\n const sourceName = config.name ?? manifest.server?.name ?? namespace;\n\n yield* ctx\n .transaction(\n Effect.gen(function* () {\n // Remove stale rows at the target scope (plugin-owned).\n // Pinning scope keeps a shadowed outer-scope row intact\n // when a per-user addSource re-uses the same namespace.\n yield* ctx.storage.removeBindingsByNamespace(namespace, config.scope);\n yield* ctx.storage.removeSource(namespace, config.scope);\n\n yield* ctx.storage.putSource({\n namespace,\n scope: config.scope,\n name: sourceName,\n config: sd,\n });\n\n yield* ctx.storage.putBindings(\n namespace,\n config.scope,\n manifest.tools.map((e) => ({\n toolId: `${namespace}.${e.toolId}`,\n binding: toBinding(e),\n })),\n );\n yield* ctx.core.sources.register({\n id: namespace,\n scope: config.scope,\n kind: \"mcp\",\n name: sourceName,\n url: sd.transport === \"remote\" ? sd.endpoint : undefined,\n canRemove: true,\n canRefresh: true,\n canEdit: sd.transport === \"remote\",\n tools: manifest.tools.map((e) => ({\n name: e.toolId,\n description: e.description ?? `MCP tool: ${e.toolName}`,\n inputSchema: e.inputSchema,\n outputSchema: mcpCallToolResultOutputSchema(e.outputSchema),\n })),\n });\n if (initialRemote && initialBindings.length > 0) {\n yield* ctx.credentialBindings.replaceForSource({\n targetScope: ScopeId.make(initialRemote.scope),\n pluginId: MCP_PLUGIN_ID,\n sourceId: namespace,\n sourceScope: ScopeId.make(config.scope),\n slotPrefixes: [\n ...(initialRemote.headers !== null ? [\"header:\"] : []),\n ...(initialRemote.queryParams !== null ? [\"query_param:\"] : []),\n ...(initialRemote.auth !== null ? [\"auth:\"] : []),\n ],\n bindings: initialBindings.map((binding) => ({\n slotKey: binding.slot,\n value: binding.value,\n })),\n });\n }\n }),\n )\n .pipe(\n Effect.withSpan(\"mcp.plugin.persist_source\", {\n attributes: {\n \"mcp.source.namespace\": namespace,\n \"mcp.source.tool_count\": manifest.tools.length,\n },\n }),\n );\n\n if (configFile) {\n yield* configFile\n .upsertSource(toMcpConfigEntry(namespace, sourceName, config))\n .pipe(Effect.withSpan(\"mcp.plugin.config_file.upsert\"));\n }\n\n if (Result.isFailure(discovery)) {\n if (Predicate.isTagged(discovery.failure, \"McpAuthRequiredError\")) {\n return yield* new McpConnectionError({\n transport: sd.transport,\n message: discovery.failure.message,\n });\n }\n return yield* Effect.fail(discovery.failure);\n }\n return { toolCount: manifest.tools.length, namespace };\n }).pipe(\n Effect.withSpan(\"mcp.plugin.add_source\", {\n attributes: {\n \"mcp.source.transport\": config.transport,\n \"mcp.source.name\": config.name,\n },\n }),\n );\n\n const removeSource = (namespace: string, scope: string) =>\n Effect.gen(function* () {\n yield* ctx\n .transaction(\n Effect.gen(function* () {\n yield* ctx.credentialBindings.removeForSource({\n pluginId: MCP_PLUGIN_ID,\n sourceId: namespace,\n sourceScope: ScopeId.make(scope),\n });\n yield* ctx.storage.removeBindingsByNamespace(namespace, scope);\n yield* ctx.storage.removeSource(namespace, scope);\n yield* ctx.core.sources.unregister({ id: namespace, targetScope: scope });\n }),\n )\n .pipe(Effect.withSpan(\"mcp.plugin.persist_remove\"));\n if (configFile) {\n yield* configFile\n .removeSource(namespace)\n .pipe(Effect.withSpan(\"mcp.plugin.config_file.remove\"));\n }\n }).pipe(\n Effect.withSpan(\"mcp.plugin.remove_source\", {\n attributes: { \"mcp.source.namespace\": namespace },\n }),\n );\n\n const refreshSource = (namespace: string, scope: string) =>\n Effect.gen(function* () {\n const sd = yield* ctx.storage.getSourceConfig(namespace, scope).pipe(\n Effect.withSpan(\"mcp.plugin.load_source_config\", {\n attributes: { \"mcp.source.namespace\": namespace },\n }),\n );\n if (!sd) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: `No stored config for MCP source \"${namespace}\"`,\n });\n }\n\n const ci = yield* resolveConnectorInput(namespace, scope, sd, ctx, allowStdio).pipe(\n Effect.catchTag(\"McpAuthRequiredError\", ({ message }) =>\n Effect.fail(new McpConnectionError({ transport: sd.transport, message })),\n ),\n Effect.withSpan(\"mcp.plugin.resolve_connector\", {\n attributes: {\n \"mcp.source.namespace\": namespace,\n \"mcp.source.transport\": sd.transport,\n },\n }),\n );\n const manifest = yield* discoverTools(createMcpConnector(ci)).pipe(\n Effect.mapError(\n ({ message }) =>\n new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: `MCP refresh failed: ${message}`,\n }),\n ),\n Effect.withSpan(\"mcp.plugin.discover_tools\", {\n attributes: { \"mcp.source.namespace\": namespace },\n }),\n );\n\n const existing = yield* ctx.storage.getSource(namespace, scope);\n const sourceName = manifest.server?.name ?? existing?.name ?? namespace;\n\n yield* ctx\n .transaction(\n Effect.gen(function* () {\n yield* ctx.storage.removeBindingsByNamespace(namespace, scope);\n yield* ctx.core.sources.unregister({ id: namespace, targetScope: scope });\n\n yield* ctx.storage.putBindings(\n namespace,\n scope,\n manifest.tools.map((e) => ({\n toolId: `${namespace}.${e.toolId}`,\n binding: toBinding(e),\n })),\n );\n yield* ctx.core.sources.register({\n id: namespace,\n scope,\n kind: \"mcp\",\n name: sourceName,\n url: sd.transport === \"remote\" ? sd.endpoint : undefined,\n canRemove: true,\n canRefresh: true,\n canEdit: sd.transport === \"remote\",\n tools: manifest.tools.map((e) => ({\n name: e.toolId,\n description: e.description ?? `MCP tool: ${e.toolName}`,\n inputSchema: e.inputSchema,\n outputSchema: mcpCallToolResultOutputSchema(e.outputSchema),\n })),\n });\n }),\n )\n .pipe(\n Effect.withSpan(\"mcp.plugin.persist_source\", {\n attributes: {\n \"mcp.source.namespace\": namespace,\n \"mcp.source.tool_count\": manifest.tools.length,\n },\n }),\n );\n\n return { toolCount: manifest.tools.length };\n }).pipe(\n Effect.withSpan(\"mcp.plugin.refresh_source\", {\n attributes: { \"mcp.source.namespace\": namespace },\n }),\n );\n\n const getSource = (namespace: string, scope: string) =>\n ctx.storage.getSource(namespace, scope).pipe(\n Effect.withSpan(\"mcp.plugin.get_source\", {\n attributes: { \"mcp.source.namespace\": namespace },\n }),\n );\n\n return {\n probeEndpoint,\n addSource,\n removeSource,\n refreshSource,\n getSource,\n };\n },\n\n sourceConfigure: {\n type: \"mcp\",\n schema: McpConfigureSourcePayloadSchema,\n configure: ({ ctx, sourceId, sourceScope, targetScope, config }) =>\n Effect.gen(function* () {\n const input = config as Omit<McpConfigureSourceInput, \"scope\">;\n const existing = yield* ctx.storage.getSource(sourceId, sourceScope);\n if (!existing || existing.config.transport !== \"remote\") return;\n\n const canonicalHeaders =\n input.headers !== undefined\n ? canonicalizeCredentialMap(input.headers, mcpHeaderSlot)\n : null;\n const canonicalQueryParams =\n input.queryParams !== undefined\n ? canonicalizeCredentialMap(input.queryParams, mcpQueryParamSlot)\n : null;\n const canonicalAuth = input.auth !== undefined ? canonicalizeAuth(input.auth) : null;\n const directBindings = [\n ...(canonicalHeaders?.bindings ?? []),\n ...(canonicalQueryParams?.bindings ?? []),\n ...(canonicalAuth?.bindings ?? []),\n ];\n if (directBindings.length > 0) {\n yield* validateMcpBindingTarget(ctx, {\n sourceId,\n sourceScope,\n targetScope,\n });\n }\n\n const updatedConfig: McpStoredSourceData = {\n ...existing.config,\n ...(input.endpoint !== undefined ? { endpoint: input.endpoint } : {}),\n ...(canonicalHeaders ? { headers: canonicalHeaders.values } : {}),\n ...(canonicalAuth ? { auth: canonicalAuth.auth } : {}),\n ...(canonicalQueryParams ? { queryParams: canonicalQueryParams.values } : {}),\n };\n const affectedPrefixes = [\n ...(input.headers !== undefined ? [\"header:\"] : []),\n ...(input.queryParams !== undefined ? [\"query_param:\"] : []),\n ...(input.auth !== undefined ? [\"auth:\"] : []),\n ];\n\n const sourceName = input.name?.trim() || existing.name;\n yield* ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.storage.putSource({\n namespace: sourceId,\n scope: sourceScope,\n name: sourceName,\n config: updatedConfig,\n });\n if (affectedPrefixes.length > 0 || directBindings.length > 0) {\n yield* ctx.credentialBindings.replaceForSource({\n targetScope: ScopeId.make(targetScope),\n pluginId: MCP_PLUGIN_ID,\n sourceId,\n sourceScope: ScopeId.make(sourceScope),\n slotPrefixes: affectedPrefixes,\n bindings: directBindings.map((binding) => ({\n slotKey: binding.slot,\n value: binding.value,\n })),\n });\n }\n }),\n );\n if (options?.configFile) {\n const bindings = yield* ctx.credentialBindings.listForSource({\n pluginId: MCP_PLUGIN_ID,\n sourceId,\n sourceScope: ScopeId.make(sourceScope),\n });\n const inputForm = inputFormFromStored(\n bindings,\n updatedConfig,\n sourceScope,\n sourceName,\n sourceId,\n );\n yield* options.configFile\n .upsertSource(toMcpConfigEntry(sourceId, sourceName, inputForm))\n .pipe(Effect.withSpan(\"mcp.plugin.config_file.upsert\"));\n }\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, call `executor.coreTools.oauth.probe` and `executor.coreTools.oauth.start` with `credentialScope` set to the user's chosen personal or organization credential scope first, then pass the resulting connection through `addSource` credentials or `mcp.configureSource`.\",\n inputSchema: McpProbeEndpointInputStandardSchema,\n outputSchema: McpProbeEndpointOutputStandardSchema,\n execute: (input) =>\n self.probeEndpoint(input).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: \"getSource\",\n description:\n \"Inspect an existing MCP source, including transport, endpoint/command, auth mode, configured headers/query params, and credential slots. Use this before repairing an existing source with `mcp.configureSource`, `secrets.create`, or `oauth.start`.\",\n inputSchema: McpGetSourceInputStandardSchema,\n outputSchema: McpGetSourceOutputStandardSchema,\n execute: (input, { ctx }) => {\n const args = input as typeof McpGetSourceInputSchema.Type;\n return Effect.map(\n self.getSource(args.namespace, resolveStaticScopeInput(ctx, args.scope)),\n (source) => ToolResult.ok({ source }),\n );\n },\n }),\n tool({\n name: \"addSource\",\n description:\n \"Add an MCP source and register its tools. Executor chooses the source install scope (local scope locally, organization scope in cloud) and returns it as `source`. For remote OAuth-protected servers, first use `probeEndpoint` and the core OAuth browser handoff (`oauth.probe`, `oauth.start` with the user's chosen `credentialScope`), then bind the completed connection with `mcp.configureSource` if needed. For header/API-key auth, first call `secrets.create` at the user's chosen credential scope so the value is entered in the browser, then pass the secret reference in `credentials`. Remote sources are still saved if discovery fails; inspect the returned `discovery` field and use `sources.refresh` after credentials or network access are fixed.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Add an MCP source\",\n },\n inputSchema: McpAddSourceInputStandardSchema,\n outputSchema: McpAddSourceOutputStandardSchema,\n execute: (rawInput, { ctx }) => {\n const input = rawInput as typeof McpAddSourceInputSchema.Type;\n const sourceScope = defaultSourceInstallScopeId(ctx.scopes);\n if (sourceScope === null) {\n return Effect.succeed(\n mcpToolFailure(\n \"source_scope_unavailable\",\n \"Cannot add an MCP source because this executor has no source install scope.\",\n ),\n );\n }\n const normalizedInput = {\n ...input,\n scope: sourceScope,\n } as McpSourceConfig;\n const added = self.addSource(normalizedInput).pipe(\n Effect.map((result) =>\n ToolResult.ok({\n ...result,\n source: { id: result.namespace, scope: sourceScope },\n discovery: { status: \"ok\" },\n }),\n ),\n );\n if (normalizedInput.transport !== \"remote\") return added;\n\n const savedWithDiscoveryFailure = (failure: {\n readonly message: string;\n readonly stage?: string;\n }) =>\n Effect.succeed(\n ToolResult.ok({\n namespace:\n normalizedInput.namespace ??\n deriveMcpNamespace({\n name: normalizedInput.name,\n endpoint: normalizedInput.endpoint,\n }),\n source: {\n id:\n normalizedInput.namespace ??\n deriveMcpNamespace({\n name: normalizedInput.name,\n endpoint: normalizedInput.endpoint,\n }),\n scope: sourceScope,\n },\n toolCount: 0,\n discovery: {\n status: \"failed\" as const,\n message: failure.message,\n ...(failure.stage ? { stage: failure.stage } : {}),\n },\n }),\n );\n\n return added.pipe(\n Effect.catchTags({\n McpToolDiscoveryError: savedWithDiscoveryFailure,\n McpConnectionError: ({ message }) =>\n Effect.succeed(\n ToolResult.ok({\n namespace:\n normalizedInput.namespace ??\n deriveMcpNamespace({\n name: normalizedInput.name,\n endpoint: normalizedInput.endpoint,\n }),\n source: {\n id:\n normalizedInput.namespace ??\n deriveMcpNamespace({\n name: normalizedInput.name,\n endpoint: normalizedInput.endpoint,\n }),\n scope: sourceScope,\n },\n toolCount: 0,\n discovery: {\n status: \"failed\" as const,\n message,\n },\n }),\n ),\n }),\n );\n },\n }),\n tool({\n name: \"configureSource\",\n description:\n 'Configure an existing remote MCP source with concrete fields. Use `source` returned by `mcp.addSource` or `sources.list`. The top-level `scope` is the credential target scope for bindings; in cloud, choose the user or organization credential scope deliberately. Pass secret refs as `{kind:\"secret\", secretId}` and OAuth connections as `{kind:\"connection\", connectionId}`.',\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Configure an MCP source\",\n },\n inputSchema: McpStaticConfigureSourceInputStandardSchema,\n outputSchema: McpStaticConfigureSourceOutputStandardSchema,\n execute: (rawInput, { ctx }) =>\n Effect.gen(function* () {\n const { source, ...config } =\n rawInput as typeof McpStaticConfigureSourceInputSchema.Type;\n const sourceScope = resolveStaticScopeInput(ctx, source.scope);\n const targetScope = resolveStaticScopeInput(ctx, config.scope);\n yield* ctx.core.sources.configure({\n source: { id: source.id, scope: sourceScope },\n scope: targetScope,\n type: \"mcp\",\n config: {\n ...(config.name !== undefined ? { name: config.name } : {}),\n ...(config.endpoint !== undefined ? { endpoint: config.endpoint } : {}),\n ...(config.headers !== undefined ? { headers: config.headers } : {}),\n ...(config.queryParams !== undefined\n ? { queryParams: config.queryParams }\n : {}),\n ...(config.auth !== undefined ? { auth: config.auth } : {}),\n },\n });\n return ToolResult.ok({ configured: true });\n }),\n }),\n ],\n },\n ],\n\n invokeTool: ({ ctx, toolRow, args, elicit }) =>\n Effect.gen(function* () {\n const runtime = yield* ensureRuntime();\n\n // toolRow.scope_id is the resolved owning scope of the tool\n // (innermost-wins from the executor's stack). The matching\n // MCP binding + source plugin-storage rows live at the same scope, so\n // pin every store lookup to it instead of relying on stack-wide\n // scope fall-through.\n const toolScope = toolRow.scope_id;\n const entry = yield* ctx.storage.getBinding(toolRow.id, toolScope).pipe(\n Effect.withSpan(\"mcp.plugin.load_binding\", {\n attributes: { \"mcp.tool.name\": toolRow.id },\n }),\n );\n if (!entry) {\n return yield* new McpInvocationError({\n toolName: toolRow.id,\n message: `No MCP binding found for tool \"${toolRow.id}\"`,\n });\n }\n\n const sd = yield* ctx.storage.getSourceConfig(entry.namespace, toolScope).pipe(\n Effect.withSpan(\"mcp.plugin.load_source_config\", {\n attributes: { \"mcp.source.namespace\": entry.namespace },\n }),\n );\n if (!sd) {\n return yield* new McpConnectionError({\n transport: \"auto\",\n message: `No MCP source config for namespace \"${entry.namespace}\"`,\n });\n }\n\n const raw = yield* invokeMcpTool({\n toolId: toolRow.id,\n toolName: entry.binding.toolName,\n args,\n sourceData: sd,\n sourceId: entry.namespace,\n sourceScope: toolScope,\n invokerScope: ctx.scopes[0]!.id,\n resolveConnector: () =>\n resolveConnectorInput(entry.namespace, toolScope, sd, ctx, allowStdio).pipe(\n Effect.catchTags({\n StorageError: () =>\n Effect.fail(\n new McpConnectionError({\n transport: sd.transport,\n message: \"Failed to resolve MCP connector storage state\",\n }),\n ),\n UniqueViolationError: () =>\n Effect.fail(\n new McpConnectionError({\n transport: sd.transport,\n message: \"Failed to resolve MCP connector storage state\",\n }),\n ),\n }),\n Effect.flatMap((ci) => createMcpConnector(ci)),\n Effect.withSpan(\"mcp.plugin.resolve_connector\", {\n attributes: {\n \"mcp.source.namespace\": entry.namespace,\n \"mcp.source.transport\": sd.transport,\n },\n }),\n ),\n connectionCache: runtime.connectionCache,\n pendingConnectors: runtime.pendingConnectors,\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(\"McpAuthRequiredError\", (error) =>\n Effect.succeed(mcpAuthToolFailure(error)),\n ),\n Effect.withSpan(\"mcp.plugin.invoke_tool\", {\n attributes: {\n \"mcp.tool.name\": toolRow.id,\n \"mcp.tool.source_id\": toolRow.source_id,\n },\n }),\n ),\n\n detect: ({ ctx, url }) =>\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 namespace = deriveMcpNamespace({ endpoint: trimmed });\n\n const connector = createMcpConnector({\n transport: \"remote\",\n endpoint: trimmed,\n });\n\n const connected = yield* discoverTools(connector).pipe(\n Effect.map(() => true),\n Effect.catch(() => Effect.succeed(false)),\n Effect.withSpan(\"mcp.plugin.discover_tools\"),\n );\n\n if (connected) {\n return SourceDetectionResult.make({\n kind: \"mcp\",\n confidence: \"high\",\n endpoint: trimmed,\n name,\n namespace,\n });\n }\n\n // The shape probe inspects the JSON-RPC `initialize` response\n // and only classifies as MCP when the wire shape is\n // unambiguous (2xx + JSON-RPC body, 2xx SSE, or 401 + Bearer +\n // JSON-RPC error envelope). That body-shape gate is what\n // separates real MCP servers — including those that\n // authenticate with static API keys and publish no OAuth\n // metadata — from unrelated OAuth-protected services whose\n // host happens to expose RFC 9728/8414 documents.\n const shape = yield* probeMcpEndpointShape(trimmed, { httpClientLayer });\n if (shape.kind === \"mcp\") {\n return SourceDetectionResult.make({\n kind: \"mcp\",\n confidence: \"high\",\n endpoint: trimmed,\n name,\n namespace,\n });\n }\n\n // Low-confidence URL-token fallback. When wire-shape detection\n // can't confirm MCP (server unreachable, behind unusual auth,\n // returns a non-canonical body, etc.) but the URL itself is a\n // strong hint, surface a candidate so the user can still pick\n // it from the detect dropdown rather than getting nothing.\n if (urlMatchesToken(parsed.value, \"mcp\")) {\n return SourceDetectionResult.make({\n kind: \"mcp\",\n confidence: \"low\",\n endpoint: trimmed,\n name,\n namespace,\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 // Honor upstream destructiveHint from MCP ToolAnnotations.\n // Bindings are fetched per scope so shadowed sources (e.g. an org-level\n // source overridden per-user) each resolve against their own scope's\n // row rather than collapsing onto whichever visible row would otherwise\n // win first.\n resolveAnnotations: ({ ctx, sourceId, toolRows }) =>\n Effect.gen(function* () {\n const scopes = new Set(toolRows.map((row) => row.scope_id));\n const entries = yield* Effect.forEach(\n [...scopes],\n (scope) =>\n Effect.gen(function* () {\n const list = yield* ctx.storage.listBindingsBySource(sourceId, scope);\n const byId = new Map(list.map((e) => [e.toolId, e.binding]));\n return [scope, byId] as const;\n }),\n { concurrency: \"unbounded\" },\n );\n const byScope = new Map(entries);\n\n const out: Record<string, ToolAnnotations> = {};\n for (const row of toolRows) {\n const binding = byScope.get(row.scope_id)?.get(row.id);\n const ann = binding?.annotations;\n if (ann?.destructiveHint === true) {\n out[row.id] = {\n requiresApproval: true,\n approvalDescription: ann.title ?? binding?.toolName ?? row.id,\n };\n } else {\n out[row.id] = { requiresApproval: false };\n }\n }\n return out;\n }),\n\n removeSource: ({ ctx, sourceId, scope }) =>\n Effect.gen(function* () {\n yield* ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.credentialBindings.removeForSource({\n pluginId: MCP_PLUGIN_ID,\n sourceId,\n sourceScope: ScopeId.make(scope),\n });\n yield* ctx.storage.removeBindingsByNamespace(sourceId, scope);\n yield* ctx.storage.removeSource(sourceId, scope);\n }),\n );\n if (options?.configFile) {\n yield* options.configFile.removeSource(sourceId);\n }\n }),\n\n usagesForSecret: () => Effect.succeed([]),\n\n usagesForConnection: () => Effect.succeed([]),\n\n refreshSource: () => Effect.void,\n\n // Connection refresh for oauth2-minted sources is owned by the\n // canonical `\"oauth2\"` ConnectionProvider that core registers via\n // `makeOAuth2Service`. No MCP-specific provider needed.\n\n close: () =>\n Effect.gen(function* () {\n const runtime = runtimeRef.current;\n if (runtime) {\n runtime.pendingConnectors.clear();\n yield* ScopedCache.invalidateAll(runtime.connectionCache);\n yield* Scope.close(runtime.cacheScope, Exit.void);\n runtimeRef.current = null;\n }\n }).pipe(Effect.withSpan(\"mcp.plugin.close\")),\n };\n // HTTP transport (routes/handlers/extensionService) is layered on by\n // the api-aware factory in `@executor-js/plugin-mcp/api`. Hosts that\n // want the HTTP surface import the plugin from there; SDK-only\n // consumers stay on this entry and avoid the server-only deps.\n});\n\n// ---------------------------------------------------------------------------\n// McpPluginExtension — shape of `executor.mcp` for consumers that want\n// to type against it directly (api/, react/). Mirrors what `extension`\n// returns above.\n// ---------------------------------------------------------------------------\n\n/**\n * Errors any MCP extension method may surface. The first four are\n * plugin-domain tagged errors that flow directly to clients (4xx, each\n * carrying its own `HttpApiSchema` status). `StorageFailure` covers\n * raw backend failures (`StorageError`) plus `UniqueViolationError`;\n * the HTTP edge (`@executor-js/api`'s `withCapture`) translates\n * `StorageError` to the opaque `InternalError({ traceId })` at Layer\n * composition. `UniqueViolationError` passes through — plugins can\n * `Effect.catchTag` it if they want a friendlier user-facing error.\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 addSource: (\n config: McpSourceConfig,\n ) => Effect.Effect<\n { readonly toolCount: number; readonly namespace: string },\n McpExtensionFailure\n >;\n readonly removeSource: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<void, McpExtensionFailure>;\n readonly refreshSource: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<{ readonly toolCount: number }, McpExtensionFailure>;\n readonly getSource: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<McpStoredSource | null, 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 { McpRemoteSourceData, McpStdioSourceData } 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 McpRemoteSourceData,\n \"auth\" | \"remoteTransport\" | \"headers\" | \"queryParams\"\n> & {\n readonly remoteTransport?: McpRemoteSourceData[\"remoteTransport\"];\n readonly headers?: Record<string, string>;\n readonly queryParams?: Record<string, string>;\n readonly authProvider?: OAuthClientProvider;\n};\n\nexport type StdioConnectorInput = McpStdioSourceData;\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","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","// ---------------------------------------------------------------------------\n// MCP tool invocation — shared helper called from plugin.invokeTool.\n//\n// Responsible for:\n// 1. Finding/creating a cached MCP client connection for the source.\n// 2. Installing a per-invocation `ElicitRequestSchema` handler that\n// bridges MCP's elicit capability into the host's elicit function\n// threaded via `InvokeToolInput.elicit`.\n// 3. Calling `client.callTool({ name, arguments })`.\n// 4. Retrying once on connection failure (invalidate + reconnect).\n// ---------------------------------------------------------------------------\n\nimport { Cause, Effect, Exit, Option, Predicate, Schema, ScopedCache } from \"effect\";\n\nimport { ElicitRequestSchema } from \"@modelcontextprotocol/sdk/types.js\";\n\nimport {\n FormElicitation,\n UrlElicitation,\n type Elicit,\n type ElicitationRequest,\n} from \"@executor-js/sdk/core\";\n\nimport { McpAuthRequiredError, McpConnectionError, McpInvocationError } from \"./errors\";\nimport type { McpConnection } from \"./connection\";\nimport type { McpStoredSourceData } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst ArgsRecord = Schema.Record(Schema.String, Schema.Unknown);\nconst decodeArgsRecord = Schema.decodeUnknownOption(ArgsRecord);\n\nconst argsRecord = (value: unknown): Record<string, unknown> =>\n Option.getOrElse(decodeArgsRecord(value), () => ({}));\n\nconst stableJson = (value: unknown): string => {\n if (Array.isArray(value)) return `[${value.map(stableJson).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n return `{${Object.entries(value as Record<string, unknown>)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value);\n};\n\nconst fingerprint = (value: unknown): string => {\n const input = stableJson(value);\n let hash = 0x811c9dc5;\n for (let i = 0; i < input.length; i++) {\n hash ^= input.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return (hash >>> 0).toString(16).padStart(8, \"0\");\n};\n\nconst connectionCacheKey = (input: {\n readonly sourceData: McpStoredSourceData;\n readonly invokerScope: string;\n readonly sourceId: string;\n readonly sourceScope: string;\n}): string => {\n const sd = input.sourceData;\n return sd.transport === \"stdio\"\n ? `stdio:${fingerprint({\n sourceId: input.sourceId,\n sourceScope: input.sourceScope,\n command: sd.command,\n args: sd.args ?? [],\n env: sd.env ?? {},\n cwd: sd.cwd ?? null,\n })}`\n : `remote:${fingerprint({\n sourceId: input.sourceId,\n sourceScope: input.sourceScope,\n invokerScope: input.invokerScope,\n endpoint: sd.endpoint,\n remoteTransport: sd.remoteTransport ?? \"auto\",\n headers: sd.headers ?? {},\n queryParams: sd.queryParams ?? {},\n auth: sd.auth,\n })}`;\n};\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: 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 readonly toolName: string;\n readonly args: unknown;\n readonly sourceData: McpStoredSourceData;\n readonly sourceId: string;\n readonly sourceScope: string;\n /** Innermost executor scope id at invoke time. Mixed into the\n * connection cache key so per-user OAuth/secret resolution doesn't\n * collapse multiple users onto one shared connection. */\n readonly invokerScope: string;\n readonly resolveConnector: () => Effect.Effect<\n McpConnection,\n McpAuthRequiredError | McpConnectionError\n >;\n readonly connectionCache: ScopedCache.ScopedCache<\n string,\n McpConnection,\n McpAuthRequiredError | McpConnectionError\n >;\n readonly pendingConnectors: Map<\n string,\n Effect.Effect<McpConnection, McpAuthRequiredError | McpConnectionError>\n >;\n readonly elicit: Elicit;\n}\n\nexport const invokeMcpTool = (\n input: InvokeMcpToolInput,\n): Effect.Effect<unknown, McpAuthRequiredError | McpConnectionError | McpInvocationError> => {\n const transport: string =\n input.sourceData.transport === \"stdio\" ? \"stdio\" : (input.sourceData.remoteTransport ?? \"auto\");\n return Effect.gen(function* () {\n const cacheKey = connectionCacheKey(input);\n const args = argsRecord(input.args);\n\n // Register the connector for the cache lookup (side-channel pattern\n // — the ScopedCache lookup closure reads from `pendingConnectors`).\n const connector = input.resolveConnector();\n input.pendingConnectors.set(cacheKey, connector);\n\n // Check cache state BEFORE acquire so the span clearly attributes\n // tail latency to either a cold handshake (miss) or warm reuse (hit).\n // Without this every `plugin.mcp.connection.acquire` span looks the\n // same in Axiom and you have to cross-reference the\n // `plugin.mcp.connection.handshake` count to back out the hit rate.\n const cacheHit = yield* ScopedCache.has(input.connectionCache, cacheKey);\n\n const firstConnection = yield* ScopedCache.get(input.connectionCache, cacheKey).pipe(\n Effect.withSpan(\"plugin.mcp.connection.acquire\", {\n attributes: {\n \"plugin.mcp.transport\": transport,\n \"plugin.mcp.cache_key\": cacheKey,\n \"plugin.mcp.attempt\": 1,\n \"plugin.mcp.cache_hit\": cacheHit,\n },\n }),\n );\n\n return yield* useConnection(firstConnection, input.toolName, args, input.elicit).pipe(\n // On failure, invalidate the cache and retry once with a fresh\n // connection. Matches the old invoker's retry-once semantics.\n Effect.catch(() =>\n Effect.gen(function* () {\n yield* ScopedCache.invalidate(input.connectionCache, cacheKey);\n input.pendingConnectors.set(cacheKey, connector);\n const fresh = yield* ScopedCache.get(input.connectionCache, cacheKey);\n return yield* useConnection(fresh, input.toolName, args, input.elicit);\n }).pipe(\n Effect.withSpan(\"plugin.mcp.invoke.retry\", {\n attributes: {\n \"plugin.mcp.transport\": transport,\n \"plugin.mcp.cache_key\": cacheKey,\n \"mcp.tool.name\": input.toolName,\n },\n }),\n ),\n ),\n );\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\": transport,\n },\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,QAAQ,WAAW,cAAc;AAW3C,IAAM,YAAY,CAAC;AAG1B,IAAM,oBAAoB;AAC1B,IAAM,qBAAqB;AAE3B,IAAM,mBAAmB,OAAO,kBAAkB,mBAAmB;AACrE,IAAM,mBAAmB,OAAO,WAAW,mBAAmB;AAC9D,IAAM,gBAAgB,OAAO,kBAAkB,cAAc;AAC7D,IAAM,gBAAgB,OAAO,WAAW,cAAc;AACtD,IAAM,aAAa,OAAO,oBAAoB,OAAO,eAAe,OAAO,OAAO,CAAC;AAEnF,IAAM,aAAa,CAAC,UAA4B;AAC9C,MAAI,OAAO,UAAU,SAAU,QAAO;AACtC,SAAO,OAAO,UAAU,WAAW,KAAK,GAAG,MAAM,KAAK;AACxD;AAmDA,IAAM,aAAa,CAAC,YAA6B;AAAA,EAC/C,W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;AAAA,YACZ,kBAAkB;AAAA,YAClB,qBAAqB,IAAI,SAAS,SAAS,YAAY,IAAI;AAAA,UAC7D;AAAA,QACF,OAAO;AACL,cAAI,IAAI,EAAE,IAAI,EAAE,kBAAkB,MAAM;AAAA,QAC1C;AAAA,MACF;AACA,aAAO;AAAA,IACT,CAAC;AAAA,IAEH,cAAc,CAAC,EAAE,KAAK,UAAU,MAAM,MACpCA,QAAO,IAAI,aAAa;AACtB,aAAO,IAAI;AAAA,QACTA,QAAO,IAAI,aAAa;AACtB,iBAAO,IAAI,mBAAmB,gBAAgB;AAAA,YAC5C,UAAU;AAAA,YACV;AAAA,YACA,aAAa,QAAQ,KAAK,KAAK;AAAA,UACjC,CAAC;AACD,iBAAO,IAAI,QAAQ,0BAA0B,UAAU,KAAK;AAC5D,iBAAO,IAAI,QAAQ,aAAa,UAAU,KAAK;AAAA,QACjD,CAAC;AAAA,MACH;AACA,UAAI,SAAS,YAAY;AACvB,eAAO,QAAQ,WAAW,aAAa,QAAQ;AAAA,MACjD;AAAA,IACF,CAAC;AAAA,IAEH,iBAAiB,MAAMA,QAAO,QAAQ,CAAC,CAAC;AAAA,IAExC,qBAAqB,MAAMA,QAAO,QAAQ,CAAC,CAAC;AAAA,IAE5C,eAAe,MAAMA,QAAO;AAAA;AAAA;AAAA;AAAA,IAM5B,OAAO,MACLA,QAAO,IAAI,aAAa;AACtB,YAAM,UAAU,WAAW;AAC3B,UAAI,SAAS;AACX,gBAAQ,kBAAkB,MAAM;AAChC,eAAOE,aAAY,cAAc,QAAQ,eAAe;AACxD,eAAO,MAAM,MAAM,QAAQ,YAAYG,MAAK,IAAI;AAChD,mBAAW,UAAU;AAAA,MACvB;AAAA,IACF,CAAC,EAAE,KAAKL,QAAO,SAAS,kBAAkB,CAAC;AAAA,EAC/C;AAKF,CAAC;","names":["Duration","Effect","Exit","Option","Predicate","Schema","ScopedCache","Effect","Effect","Effect","Option","Schema","Schema","Option","Option","tool","Effect","Effect","Option","Predicate","Schema","Schema","Option","Effect","Predicate","Effect","Option","Schema","Schema","Option","Effect","Predicate","ScopedCache","Duration","entry","Exit"]}
|
package/dist/client.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
mcpPresets
|
|
3
3
|
} from "./chunk-TW44CBXJ.js";
|
|
4
|
-
import "./chunk-PZ5AY32C.js";
|
|
5
4
|
|
|
6
5
|
// src/react/plugin-client.tsx
|
|
7
6
|
import { defineClientPlugin } from "@executor-js/sdk/client";
|
|
@@ -9,9 +8,9 @@ import { defineClientPlugin } from "@executor-js/sdk/client";
|
|
|
9
8
|
// src/react/source-plugin.tsx
|
|
10
9
|
import { lazy } from "react";
|
|
11
10
|
import { jsx } from "react/jsx-runtime";
|
|
12
|
-
var importAdd = () => import("./AddMcpSource-
|
|
13
|
-
var importEdit = () => import("./EditMcpSource-
|
|
14
|
-
var importSummary = () => import("./McpSourceSummary-
|
|
11
|
+
var importAdd = () => import("./AddMcpSource-PADMBVX2.js");
|
|
12
|
+
var importEdit = () => import("./EditMcpSource-L5GC2B4J.js");
|
|
13
|
+
var importSummary = () => import("./McpSourceSummary-LE3WXFUE.js");
|
|
15
14
|
var LazyAddMcpSource = lazy(importAdd);
|
|
16
15
|
var LazyEditMcpSource = lazy(importEdit);
|
|
17
16
|
var LazyMcpSourceSummary = lazy(importSummary);
|
package/dist/client.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/plugin-client.tsx","../src/react/source-plugin.tsx"],"sourcesContent":["// ---------------------------------------------------------------------------\n// @executor-js/plugin-mcp/client — `defineClientPlugin` factory entry.\n//\n// Default-exports a factory rather than a value: at build time the\n// `@executor-js/vite-plugin` reads each plugin spec's `clientConfig`\n// from `executor.config.ts` and emits `__p(<JSON.stringify(clientConfig)>)`\n// into the virtual `plugins-client` module. So `allowStdio` flows from\n// the server-side `mcpPlugin({ dangerouslyAllowStdioMCP })` straight\n// into the bundle — no parallel client-side flag, no per-host shim,\n// no runtime fetch.\n// ---------------------------------------------------------------------------\n\nimport { defineClientPlugin } from \"@executor-js/sdk/client\";\n\nimport { createMcpSourcePlugin } from \"./source-plugin\";\n\nexport interface McpClientConfig {\n /**\n * Mirrors `dangerouslyAllowStdioMCP` on the server-side plugin. When\n * false, the AddMcpSource UI hides the stdio tab and stdio presets.\n * Defaults to false — same default as the server flag.\n */\n readonly allowStdio?: boolean;\n}\n\nexport default function createMcpClientPlugin(config?: McpClientConfig) {\n return defineClientPlugin({\n id: \"mcp\" as const,\n sourcePlugin: createMcpSourcePlugin({\n allowStdio: config?.allowStdio ?? false,\n }),\n });\n}\n","import { lazy, type ComponentProps, type ComponentType } from \"react\";\nimport type { SourcePlugin } from \"@executor-js/sdk/client\";\nimport { mcpPresets } from \"../sdk/presets\";\n\nconst importAdd = () => import(\"./AddMcpSource\");\nconst importEdit = () => import(\"./EditMcpSource\");\nconst importSummary = () => import(\"./McpSourceSummary\");\n\nconst LazyAddMcpSource = lazy(importAdd);\nconst LazyEditMcpSource = lazy(importEdit);\nconst LazyMcpSourceSummary = lazy(importSummary);\n\ntype AddProps = ComponentProps<SourcePlugin[\"add\"]>;\n\nexport interface McpSourcePluginOptions {\n /**\n * Enable the stdio transport in the add-source UI (tab + presets).\n *\n * Off by default — stdio is a high-risk transport on any server deployment\n * (see `dangerouslyAllowStdioMCP` on the server-side plugin). Only enable in\n * trusted local contexts where the server has the matching flag set.\n */\n readonly allowStdio?: boolean;\n}\n\nexport const createMcpSourcePlugin = (options?: McpSourcePluginOptions): SourcePlugin => {\n const allowStdio = options?.allowStdio ?? false;\n\n const AddWithFlag: ComponentType<AddProps> = (props) => (\n <LazyAddMcpSource {...props} allowStdio={allowStdio} />\n );\n\n const presets = allowStdio\n ? mcpPresets\n : mcpPresets.filter(\n (p) => !(\"transport\" in p && (p as { transport?: string }).transport === \"stdio\"),\n );\n\n return {\n key: \"mcp\",\n label: \"MCP\",\n add: AddWithFlag,\n edit: LazyEditMcpSource,\n summary: LazyMcpSourceSummary,\n presets,\n preload: () => {\n void importAdd();\n void importEdit();\n void importSummary();\n },\n };\n};\n\n/** @deprecated Use `createMcpSourcePlugin({ allowStdio })` instead. */\nexport const mcpSourcePlugin: SourcePlugin = createMcpSourcePlugin();\n"],"mappings":"
|
|
1
|
+
{"version":3,"sources":["../src/react/plugin-client.tsx","../src/react/source-plugin.tsx"],"sourcesContent":["// ---------------------------------------------------------------------------\n// @executor-js/plugin-mcp/client — `defineClientPlugin` factory entry.\n//\n// Default-exports a factory rather than a value: at build time the\n// `@executor-js/vite-plugin` reads each plugin spec's `clientConfig`\n// from `executor.config.ts` and emits `__p(<JSON.stringify(clientConfig)>)`\n// into the virtual `plugins-client` module. So `allowStdio` flows from\n// the server-side `mcpPlugin({ dangerouslyAllowStdioMCP })` straight\n// into the bundle — no parallel client-side flag, no per-host shim,\n// no runtime fetch.\n// ---------------------------------------------------------------------------\n\nimport { defineClientPlugin } from \"@executor-js/sdk/client\";\n\nimport { createMcpSourcePlugin } from \"./source-plugin\";\n\nexport interface McpClientConfig {\n /**\n * Mirrors `dangerouslyAllowStdioMCP` on the server-side plugin. When\n * false, the AddMcpSource UI hides the stdio tab and stdio presets.\n * Defaults to false — same default as the server flag.\n */\n readonly allowStdio?: boolean;\n}\n\nexport default function createMcpClientPlugin(config?: McpClientConfig) {\n return defineClientPlugin({\n id: \"mcp\" as const,\n sourcePlugin: createMcpSourcePlugin({\n allowStdio: config?.allowStdio ?? false,\n }),\n });\n}\n","import { lazy, type ComponentProps, type ComponentType } from \"react\";\nimport type { SourcePlugin } from \"@executor-js/sdk/client\";\nimport { mcpPresets } from \"../sdk/presets\";\n\nconst importAdd = () => import(\"./AddMcpSource\");\nconst importEdit = () => import(\"./EditMcpSource\");\nconst importSummary = () => import(\"./McpSourceSummary\");\n\nconst LazyAddMcpSource = lazy(importAdd);\nconst LazyEditMcpSource = lazy(importEdit);\nconst LazyMcpSourceSummary = lazy(importSummary);\n\ntype AddProps = ComponentProps<SourcePlugin[\"add\"]>;\n\nexport interface McpSourcePluginOptions {\n /**\n * Enable the stdio transport in the add-source UI (tab + presets).\n *\n * Off by default — stdio is a high-risk transport on any server deployment\n * (see `dangerouslyAllowStdioMCP` on the server-side plugin). Only enable in\n * trusted local contexts where the server has the matching flag set.\n */\n readonly allowStdio?: boolean;\n}\n\nexport const createMcpSourcePlugin = (options?: McpSourcePluginOptions): SourcePlugin => {\n const allowStdio = options?.allowStdio ?? false;\n\n const AddWithFlag: ComponentType<AddProps> = (props) => (\n <LazyAddMcpSource {...props} allowStdio={allowStdio} />\n );\n\n const presets = allowStdio\n ? mcpPresets\n : mcpPresets.filter(\n (p) => !(\"transport\" in p && (p as { transport?: string }).transport === \"stdio\"),\n );\n\n return {\n key: \"mcp\",\n label: \"MCP\",\n add: AddWithFlag,\n edit: LazyEditMcpSource,\n summary: LazyMcpSourceSummary,\n presets,\n preload: () => {\n void importAdd();\n void importEdit();\n void importSummary();\n },\n };\n};\n\n/** @deprecated Use `createMcpSourcePlugin({ allowStdio })` instead. */\nexport const mcpSourcePlugin: SourcePlugin = createMcpSourcePlugin();\n"],"mappings":";;;;;AAYA,SAAS,0BAA0B;;;ACZnC,SAAS,YAAqD;AA6B1D;AAzBJ,IAAM,YAAY,MAAM,OAAO,4BAAgB;AAC/C,IAAM,aAAa,MAAM,OAAO,6BAAiB;AACjD,IAAM,gBAAgB,MAAM,OAAO,gCAAoB;AAEvD,IAAM,mBAAmB,KAAK,SAAS;AACvC,IAAM,oBAAoB,KAAK,UAAU;AACzC,IAAM,uBAAuB,KAAK,aAAa;AAexC,IAAM,wBAAwB,CAAC,YAAmD;AACvF,QAAM,aAAa,SAAS,cAAc;AAE1C,QAAM,cAAuC,CAAC,UAC5C,oBAAC,oBAAkB,GAAG,OAAO,YAAwB;AAGvD,QAAM,UAAU,aACZ,aACA,WAAW;AAAA,IACT,CAAC,MAAM,EAAE,eAAe,KAAM,EAA6B,cAAc;AAAA,EAC3E;AAEJ,SAAO;AAAA,IACL,KAAK;AAAA,IACL,OAAO;AAAA,IACP,KAAK;AAAA,IACL,MAAM;AAAA,IACN,SAAS;AAAA,IACT;AAAA,IACA,SAAS,MAAM;AACb,WAAK,UAAU;AACf,WAAK,WAAW;AAChB,WAAK,cAAc;AAAA,IACrB;AAAA,EACF;AACF;AAGO,IAAM,kBAAgC,sBAAsB;;;AD7BpD,SAAR,sBAAuC,QAA0B;AACtE,SAAO,mBAAmB;AAAA,IACxB,IAAI;AAAA,IACJ,cAAc,sBAAsB;AAAA,MAClC,YAAY,QAAQ,cAAc;AAAA,IACpC,CAAC;AAAA,EACH,CAAC;AACH;","names":[]}
|
package/dist/core.js
CHANGED
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
makeMcpStore,
|
|
3
3
|
mcpPlugin,
|
|
4
4
|
mcpSchema
|
|
5
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-LEGVPKYH.js";
|
|
6
6
|
import "./chunk-TW44CBXJ.js";
|
|
7
7
|
import {
|
|
8
8
|
ConfiguredMcpCredentialValue,
|
|
@@ -15,8 +15,7 @@ import {
|
|
|
15
15
|
McpCredentialInput,
|
|
16
16
|
mcpHeaderSlot,
|
|
17
17
|
mcpQueryParamSlot
|
|
18
|
-
} from "./chunk-
|
|
19
|
-
import "./chunk-PZ5AY32C.js";
|
|
18
|
+
} from "./chunk-6OYEXHU3.js";
|
|
20
19
|
export {
|
|
21
20
|
ConfiguredMcpCredentialValue,
|
|
22
21
|
MCP_HEADER_AUTH_SLOT,
|
package/dist/index.js
CHANGED
package/dist/sdk/errors.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { Schema } from "effect";
|
|
2
|
+
import type { AuthToolFailureCode } from "@executor-js/sdk/core";
|
|
2
3
|
declare const McpConnectionError_base: Schema.Class<McpConnectionError, Schema.TaggedStruct<"McpConnectionError", {
|
|
3
4
|
readonly transport: Schema.String;
|
|
4
5
|
readonly message: Schema.String;
|
|
@@ -22,4 +23,22 @@ declare const McpOAuthError_base: Schema.Class<McpOAuthError, Schema.TaggedStruc
|
|
|
22
23
|
}>, import("effect/Cause").YieldableError>;
|
|
23
24
|
export declare class McpOAuthError extends McpOAuthError_base {
|
|
24
25
|
}
|
|
26
|
+
declare const McpAuthRequiredError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
27
|
+
readonly _tag: "McpAuthRequiredError";
|
|
28
|
+
} & Readonly<A>;
|
|
29
|
+
export declare class McpAuthRequiredError extends McpAuthRequiredError_base<{
|
|
30
|
+
readonly code: AuthToolFailureCode;
|
|
31
|
+
readonly message: string;
|
|
32
|
+
readonly sourceId: string;
|
|
33
|
+
readonly sourceScope: string;
|
|
34
|
+
readonly credentialKind: "secret" | "connection" | "oauth" | "upstream";
|
|
35
|
+
readonly credentialLabel?: string;
|
|
36
|
+
readonly slotKey?: string;
|
|
37
|
+
readonly secretId?: string;
|
|
38
|
+
readonly connectionId?: string;
|
|
39
|
+
readonly status?: number;
|
|
40
|
+
readonly details?: unknown;
|
|
41
|
+
readonly cause?: unknown;
|
|
42
|
+
}> {
|
|
43
|
+
}
|
|
25
44
|
export {};
|