@executor-js/plugin-mcp 0.1.0 → 0.2.1
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-VM3HY26S.js +762 -0
- package/dist/AddMcpSource-VM3HY26S.js.map +1 -0
- package/dist/EditMcpSource-WELWGRJG.js +259 -0
- package/dist/EditMcpSource-WELWGRJG.js.map +1 -0
- package/dist/McpSourceSummary-7TDQXLT5.js +85 -0
- package/dist/McpSourceSummary-7TDQXLT5.js.map +1 -0
- package/dist/api/group.d.ts +109 -17
- package/dist/api/index.d.ts +391 -0
- package/dist/chunk-2ETJ6LQH.js +239 -0
- package/dist/chunk-2ETJ6LQH.js.map +1 -0
- package/dist/chunk-OOOH3IO4.js +2194 -0
- package/dist/chunk-OOOH3IO4.js.map +1 -0
- package/dist/chunk-SKSXXFOA.js +104 -0
- package/dist/chunk-SKSXXFOA.js.map +1 -0
- package/dist/chunk-Z4CRPOLI.js +186 -0
- package/dist/chunk-Z4CRPOLI.js.map +1 -0
- package/dist/chunk-ZIRGIRGP.js +115 -0
- package/dist/chunk-ZIRGIRGP.js.map +1 -0
- package/dist/client.js +51 -0
- package/dist/client.js.map +1 -0
- package/dist/core.js +26 -2
- package/dist/index.js +2 -1
- package/dist/react/McpRemoteSourceFields.d.ts +18 -0
- package/dist/react/McpSourceSummary.d.ts +5 -0
- package/dist/react/atoms.d.ts +206 -6
- package/dist/react/client.d.ts +113 -16
- package/dist/react/index.d.ts +1 -1
- package/dist/react/plugin-client.d.ts +9 -2
- package/dist/sdk/binding-store.d.ts +106 -1
- package/dist/sdk/index.d.ts +1 -1
- package/dist/sdk/invoke.d.ts +2 -0
- package/dist/sdk/plugin.d.ts +142 -114
- package/dist/sdk/probe-shape-real-servers.live.test.d.ts +1 -0
- package/dist/sdk/probe-shape.d.ts +17 -3
- package/dist/sdk/stored-source.d.ts +9 -6
- package/dist/sdk/types.d.ts +138 -13
- package/dist/{stdio-connector-KNHLETKM.js → stdio-connector-AA5S6UUJ.js} +1 -1
- package/dist/{stdio-connector-KNHLETKM.js.map → stdio-connector-AA5S6UUJ.js.map} +1 -1
- package/dist/testing/index.d.ts +1 -0
- package/dist/{sdk/test-utils.d.ts → testing/server.d.ts} +0 -6
- package/dist/testing.js +51 -0
- package/dist/testing.js.map +1 -0
- package/package.json +17 -4
- package/dist/chunk-C2GNZGFJ.js +0 -1622
- package/dist/chunk-C2GNZGFJ.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sdk/types.ts","../src/sdk/binding-store.ts","../src/sdk/plugin.ts","../src/api/group.ts","../src/sdk/errors.ts","../src/sdk/stored-source.ts","../src/api/handlers.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, Schema } from \"effect\";\nimport { SecretBackedMap, SecretBackedValue } from \"@executor-js/sdk/core\";\n\nexport { SecretBackedMap, SecretBackedValue };\n\n// ---------------------------------------------------------------------------\n// Remote transport type\n// ---------------------------------------------------------------------------\n\nexport const McpRemoteTransport = Schema.Literals([\"streamable-http\", \"sse\", \"auto\"]);\nexport type McpRemoteTransport = typeof McpRemoteTransport.Type;\n\n/** All transport types (used in the connector layer) */\nexport const McpTransport = Schema.Literals([\"streamable-http\", \"sse\", \"stdio\", \"auto\"]);\nexport type McpTransport = typeof McpTransport.Type;\n\n// ---------------------------------------------------------------------------\n// Connection auth (only applies to remote sources)\n//\n// `oauth2` is a thin pointer to an SDK Connection (`ctx.connections`) —\n// the access/refresh secrets, expiry, DCR client info, and authorization-\n// server discovery URLs all live on the connection row. Scope shadowing\n// means the same `connectionId` resolves per-user via the executor's\n// innermost-wins lookup.\n// ---------------------------------------------------------------------------\n\n/** JSON object loosely typed — used for opaque OAuth state we just round-trip. */\nconst JsonObject = Schema.Record(Schema.String, Schema.Unknown);\nexport { JsonObject as McpJsonObject };\n\nexport const McpConnectionAuth = Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"none\") }),\n Schema.Struct({\n kind: Schema.Literal(\"header\"),\n headerName: Schema.String,\n secretId: Schema.String,\n prefix: Schema.optional(Schema.String),\n }),\n Schema.Struct({\n kind: Schema.Literal(\"oauth2\"),\n connectionId: Schema.String,\n clientIdSecretId: Schema.optional(Schema.String),\n clientSecretSecretId: Schema.optional(Schema.NullOr(Schema.String)),\n }),\n]);\nexport type McpConnectionAuth = typeof McpConnectionAuth.Type;\n\n// ---------------------------------------------------------------------------\n// Stored source data — discriminated union on transport\n// ---------------------------------------------------------------------------\n\n/** Common fields for remote string map schemas */\nconst StringMap = Schema.Record(Schema.String, Schema.String);\n\nexport const McpRemoteSourceData = Schema.Struct({\n transport: Schema.Literal(\"remote\"),\n /** The MCP server endpoint URL */\n endpoint: Schema.String,\n /** Transport preference for this remote source */\n remoteTransport: McpRemoteTransport.pipe(\n Schema.optionalKey,\n Schema.withConstructorDefault(Effect.succeed(\"auto\" as const)),\n ),\n /** Extra query params appended to the endpoint URL */\n queryParams: Schema.optional(SecretBackedMap),\n /** Extra headers sent on every request */\n headers: Schema.optional(SecretBackedMap),\n /** Auth configuration */\n auth: McpConnectionAuth,\n});\nexport type McpRemoteSourceData = typeof McpRemoteSourceData.Type;\n\nexport const McpStdioSourceData = Schema.Struct({\n transport: Schema.Literal(\"stdio\"),\n /** The command to run */\n command: Schema.String,\n /** Arguments to the command */\n args: Schema.optional(Schema.Array(Schema.String)),\n /** Environment variables */\n env: Schema.optional(StringMap),\n /** Working directory */\n cwd: Schema.optional(Schema.String),\n});\nexport type McpStdioSourceData = typeof McpStdioSourceData.Type;\n\nexport const McpStoredSourceData = Schema.Union([McpRemoteSourceData, McpStdioSourceData]);\nexport type McpStoredSourceData = typeof McpStoredSourceData.Type;\n\n// ---------------------------------------------------------------------------\n// Tool binding — maps a registered ToolId back to the MCP tool name\n// ---------------------------------------------------------------------------\n\nexport const McpToolAnnotations = Schema.Struct({\n title: Schema.optional(Schema.String),\n readOnlyHint: Schema.optional(Schema.Boolean),\n destructiveHint: Schema.optional(Schema.Boolean),\n idempotentHint: Schema.optional(Schema.Boolean),\n openWorldHint: Schema.optional(Schema.Boolean),\n});\nexport type McpToolAnnotations = typeof McpToolAnnotations.Type;\n\nexport class McpToolBinding extends Schema.Class<McpToolBinding>(\"McpToolBinding\")({\n toolId: Schema.String,\n toolName: Schema.String,\n description: Schema.NullOr(Schema.String),\n inputSchema: Schema.optional(Schema.Unknown),\n outputSchema: Schema.optional(Schema.Unknown),\n annotations: Schema.optional(McpToolAnnotations),\n}) {}\n","// ---------------------------------------------------------------------------\n// MCP plugin storage — two tables (mcp_source, mcp_binding). OAuth\n// session storage lives at the core level in `oauth2_session` and is\n// owned by `ctx.oauth`.\n// ---------------------------------------------------------------------------\n\nimport { Effect, Schema } from \"effect\";\n\nimport {\n defineSchema,\n type StorageDeps,\n type StorageFailure,\n} from \"@executor-js/sdk/core\";\n\nimport { McpToolBinding, McpStoredSourceData } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Schema\n// ---------------------------------------------------------------------------\n\nexport const mcpSchema = defineSchema({\n mcp_source: {\n fields: {\n id: { type: \"string\", required: true },\n scope_id: { type: \"string\", required: true, index: true },\n name: { type: \"string\", required: true },\n config: { type: \"json\", required: true },\n created_at: { type: \"date\", required: true },\n },\n },\n mcp_binding: {\n fields: {\n id: { type: \"string\", required: true },\n scope_id: { type: \"string\", required: true, index: true },\n source_id: { type: \"string\", required: true, index: true },\n binding: { type: \"json\", required: true },\n created_at: { type: \"date\", required: true },\n },\n },\n});\n\nexport type McpSchema = typeof mcpSchema;\n\n// ---------------------------------------------------------------------------\n// Serialization helpers — JSON columns round-trip through the adapter as\n// either plain objects or serialized strings depending on the backend.\n// ---------------------------------------------------------------------------\n\nconst decodeSourceData = Schema.decodeUnknownSync(McpStoredSourceData);\nconst encodeSourceData = Schema.encodeSync(McpStoredSourceData);\n\nconst decodeBinding = Schema.decodeUnknownSync(McpToolBinding);\nconst encodeBinding = Schema.encodeSync(McpToolBinding);\n\nconst coerceJson = (value: unknown): unknown => {\n if (typeof value !== \"string\") return value;\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n};\n\n// ---------------------------------------------------------------------------\n// Stored source (decoded) — what callers see\n// ---------------------------------------------------------------------------\n\nexport interface McpStoredSource {\n readonly namespace: string;\n /** Executor scope id this source row lives in. Writes stamp this on\n * `scope_id`; reads return whichever scope's row the adapter's\n * fall-through walk surfaced first. */\n readonly scope: string;\n readonly name: string;\n readonly config: McpStoredSourceData;\n}\n\n// ---------------------------------------------------------------------------\n// Store interface\n// ---------------------------------------------------------------------------\n\n// Every method routes through the typed adapter (`ctx.storage.adapter`)\n// so the typed error channel is `StorageFailure`. Schema-decode failures\n// inside `Effect.gen` land as defects, not typed errors, and are caught\n// by the HTTP edge's observability middleware.\n//\n// Every read/write that targets a single row pins BOTH the natural id\n// (namespace, toolId, sessionId) AND the owning `scope_id`. The store\n// runs behind the scoped adapter (which auto-injects `scope_id IN\n// (stack)`), so a bare `{id}` filter resolves to any matching row in\n// the stack in adapter-iteration order. For shadowed rows (same id at\n// multiple scopes — e.g. an org-level MCP source with a per-user\n// override), that's a scope-isolation bug: updates and deletes can\n// land on the wrong scope's row. Callers thread the resolved scope in\n// (typically `path.scopeId` for HTTP, `toolRow.scope_id` /\n// `input.scope` for invokeTool/lifecycle) so every keyed mutation\n// targets exactly one row.\nexport interface McpBindingStore {\n readonly listBindingsBySource: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<\n ReadonlyArray<{ readonly toolId: string; readonly binding: McpToolBinding }>,\n StorageFailure\n >;\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\n readonly putBindings: (\n namespace: string,\n scope: string,\n entries: ReadonlyArray<{ readonly toolId: string; readonly binding: McpToolBinding }>,\n ) => Effect.Effect<void, StorageFailure>;\n\n readonly removeBindingsByNamespace: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<void, StorageFailure>;\n\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: (\n namespace: string,\n scope: string,\n ) => Effect.Effect<void, StorageFailure>;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nexport const makeMcpStore = ({\n adapter: db,\n}: StorageDeps<McpSchema>): McpBindingStore => {\n return {\n listBindingsBySource: (namespace, scope) =>\n Effect.gen(function* () {\n const rows = yield* db.findMany({\n model: \"mcp_binding\",\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n return rows.map((row) => ({\n toolId: row.id,\n binding: decodeBinding(coerceJson(row.binding)),\n }));\n }),\n\n getBinding: (toolId, scope) =>\n Effect.gen(function* () {\n const row = yield* db.findOne({\n model: \"mcp_binding\",\n where: [\n { field: \"id\", value: toolId },\n { field: \"scope_id\", value: scope },\n ],\n });\n if (!row) return null;\n const binding = decodeBinding(coerceJson(row.binding));\n return { binding, namespace: row.source_id };\n }),\n\n putBindings: (namespace, scope, entries) =>\n Effect.gen(function* () {\n if (entries.length === 0) return;\n const now = new Date();\n yield* db.createMany({\n model: \"mcp_binding\",\n data: entries.map((e) => ({\n id: e.toolId,\n scope_id: scope,\n source_id: namespace,\n binding: encodeBinding(e.binding),\n created_at: now,\n })),\n forceAllowId: true,\n });\n }),\n\n removeBindingsByNamespace: (namespace, scope) =>\n db\n .deleteMany({\n model: \"mcp_binding\",\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n })\n .pipe(Effect.asVoid),\n\n getSource: (namespace, scope) =>\n Effect.gen(function* () {\n const row = yield* db.findOne({\n model: \"mcp_source\",\n where: [\n { field: \"id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n if (!row) return null;\n return {\n namespace: row.id,\n scope: row.scope_id,\n name: row.name,\n config: decodeSourceData(coerceJson(row.config)),\n };\n }),\n\n getSourceConfig: (namespace, scope) =>\n Effect.gen(function* () {\n const row = yield* db.findOne({\n model: \"mcp_source\",\n where: [\n { field: \"id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n if (!row) return null;\n return decodeSourceData(coerceJson(row.config));\n }),\n\n putSource: (source) =>\n Effect.gen(function* () {\n const now = new Date();\n yield* db.delete({\n model: \"mcp_source\",\n where: [\n { field: \"id\", value: source.namespace },\n { field: \"scope_id\", value: source.scope },\n ],\n });\n yield* db.create({\n model: \"mcp_source\",\n data: {\n id: source.namespace,\n scope_id: source.scope,\n name: source.name,\n config: encodeSourceData(source.config),\n created_at: now,\n },\n forceAllowId: true,\n });\n }),\n\n removeSource: (namespace, scope) =>\n Effect.gen(function* () {\n yield* db.deleteMany({\n model: \"mcp_binding\",\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n yield* db.delete({\n model: \"mcp_source\",\n where: [\n { field: \"id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n }),\n };\n};\n","import { Duration, Effect, Exit, Result, Scope, ScopedCache } from \"effect\";\n\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\n\nimport { McpGroup } from \"../api/group\";\nimport { McpExtensionService, McpHandlers } from \"../api/handlers\";\n\nimport {\n SourceDetectionResult,\n definePlugin,\n resolveSecretBackedMap as resolveSharedSecretBackedMap,\n type PluginCtx,\n type StorageFailure,\n type ToolAnnotations,\n} from \"@executor-js/sdk/core\";\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 { McpConnectionError, McpToolDiscoveryError } from \"./errors\";\nimport { invokeMcpTool } from \"./invoke\";\nimport { deriveMcpNamespace, type McpToolManifest, type McpToolManifestEntry } from \"./manifest\";\nimport { probeMcpEndpointShape } from \"./probe-shape\";\nimport {\n McpToolBinding,\n type McpConnectionAuth,\n type SecretBackedValue,\n type McpStoredSourceData,\n} from \"./types\";\n\nimport {\n SECRET_REF_PREFIX,\n type ConfigFileSink,\n type McpAuthConfig,\n type McpRemoteSourceConfig as McpRemoteConfigEntry,\n type McpStdioSourceConfig as McpStdioConfigEntry,\n type SourceConfig,\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, SecretBackedValue>;\n readonly headers?: Record<string, SecretBackedValue>;\n readonly namespace?: string;\n readonly auth?: McpConnectionAuth;\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;\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 name: string;\n readonly namespace: string;\n readonly toolCount: number | null;\n readonly serverName: string | null;\n}\n\nexport interface McpUpdateSourceInput {\n readonly name?: string;\n readonly endpoint?: string;\n readonly headers?: Record<string, SecretBackedValue>;\n readonly queryParams?: Record<string, SecretBackedValue>;\n readonly auth?: McpConnectionAuth;\n}\n\nexport interface McpProbeEndpointInput {\n readonly endpoint: string;\n readonly headers?: Record<string, SecretBackedValue>;\n readonly queryParams?: Record<string, SecretBackedValue>;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst toStoredSourceData = (config: McpSourceConfig): 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: config.queryParams,\n headers: config.headers,\n auth: config.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\nconst toBinding = (entry: McpToolManifestEntry): McpToolBinding =>\n new McpToolBinding({\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\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 throw new Error(\"MCP OAuth re-authorization required\");\n },\n saveCodeVerifier: () => undefined,\n codeVerifier: () => {\n throw new Error(\"No active PKCE verifier\");\n },\n saveDiscoveryState: () => undefined,\n discoveryState: () => undefined,\n});\n\nconst remoteConnectionError = (message: string) =>\n new McpConnectionError({ transport: \"remote\", message });\n\nconst mcpDiscoveryError = (message: string) =>\n new McpToolDiscoveryError({ stage: \"list_tools\", message });\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 remoteConnectionError(`Failed to resolve secret \"${value.secretId}\"`),\n onError: (err, _name, value) =>\n \"_tag\" in err && err._tag === \"SecretOwnedByConnectionError\"\n ? remoteConnectionError(`Failed to resolve secret \"${value.secretId}\"`)\n : err,\n }).pipe(\n Effect.mapError((err) =>\n \"_tag\" in err && err._tag === \"SecretOwnedByConnectionError\"\n ? remoteConnectionError(\"Failed to resolve secret\")\n : err,\n ),\n );\n\nconst plainStringMap = (\n values: Record<string, SecretBackedValue> | undefined,\n): Record<string, string> | undefined => {\n if (!values) return undefined;\n const entries = Object.entries(values).filter(\n (entry): entry is [string, string] => typeof entry[1] === \"string\",\n );\n return entries.length > 0 ? Object.fromEntries(entries) : undefined;\n};\n\n// ---------------------------------------------------------------------------\n// Shared connector resolution — reads secrets, builds stdio/remote input\n// ---------------------------------------------------------------------------\n\nconst resolveConnectorInput = (\n sd: McpStoredSourceData,\n ctx: PluginCtx<McpBindingStore>,\n allowStdio: boolean,\n): Effect.Effect<ConnectorInput, 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* resolveSecretBackedMap(sd.headers, ctx);\n const resolvedQueryParams = yield* resolveSecretBackedMap(sd.queryParams, ctx);\n const headers: Record<string, string> = { ...(resolvedHeaders ?? {}) };\n let authProvider: OAuthClientProvider | undefined;\n\n const auth = sd.auth;\n if (auth.kind === \"header\") {\n const val = yield* ctx.secrets\n .get(auth.secretId)\n .pipe(\n Effect.mapError((err) =>\n \"_tag\" in err && err._tag === \"SecretOwnedByConnectionError\"\n ? remoteConnectionError(`Failed to resolve secret \"${auth.secretId}\"`)\n : err,\n ),\n );\n if (val === null) {\n return yield* Effect.fail(\n remoteConnectionError(`Failed to resolve secret \"${auth.secretId}\"`),\n );\n }\n headers[auth.headerName] = auth.prefix ? `${auth.prefix}${val}` : val;\n } else if (auth.kind === \"oauth2\") {\n // `accessToken(id)` handles refresh internally — by the time we\n // hand the value to the MCP transport it's guaranteed fresh.\n // The canonical `\"oauth2\"` ConnectionProvider registered by\n // core owns the refresh lifecycle; we just wrap the current\n // token for the SDK's transport.\n const accessToken = yield* ctx.connections\n .accessToken(auth.connectionId)\n .pipe(\n Effect.mapError((err) =>\n remoteConnectionError(\n `Failed to resolve OAuth connection \"${auth.connectionId}\": ${\n \"message\" in err ? (err as { message: string }).message : String(err)\n }`,\n ),\n ),\n );\n authProvider = makeOAuthProvider(accessToken);\n }\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<string, McpConnection, McpConnectionError>;\n readonly pendingConnectors: Map<string, Effect.Effect<McpConnection, McpConnectionError>>;\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<string, Effect.Effect<McpConnection, McpConnectionError>>();\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) => Effect.promise(() => connection.close().catch(() => {})),\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 /** 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 secretRef = (id: string): string => `${SECRET_REF_PREFIX}${id}`;\n\nconst authToConfig = (auth: McpConnectionAuth | undefined): McpAuthConfig | undefined => {\n if (!auth) return undefined;\n if (auth.kind === \"none\") return { kind: \"none\" };\n if (auth.kind === \"header\") {\n return {\n kind: \"header\",\n headerName: auth.headerName,\n secret: secretRef(auth.secretId),\n prefix: auth.prefix,\n };\n }\n return {\n kind: \"oauth2\",\n connectionId: auth.connectionId,\n };\n};\n\nconst toMcpConfigEntry = (\n namespace: string,\n sourceName: string,\n config: McpSourceConfig,\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: plainStringMap(config.queryParams),\n headers: plainStringMap(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 schema: mcpSchema,\n storage: (deps): McpBindingStore => makeMcpStore(deps),\n\n extension: (ctx) => {\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* Effect.fail(remoteConnectionError(\"Endpoint URL is required\"));\n }\n\n const name = yield* Effect.try({\n try: () => new URL(trimmed).hostname,\n catch: () => \"mcp\",\n }).pipe(\n Effect.orElseSucceed(() => \"mcp\"),\n );\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 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 headers: probeHeaders,\n queryParams: probeQueryParams,\n });\n if (shape.kind !== \"mcp\") {\n return yield* Effect.fail(\n remoteConnectionError(\n shape.kind === \"not-mcp\"\n ? `Endpoint does not look like an MCP server: ${shape.reason}`\n : `Could not reach endpoint: ${shape.reason}`,\n ),\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(() => true),\n Effect.catch(() => Effect.succeed(false)),\n Effect.withSpan(\"mcp.plugin.probe_oauth\"),\n );\n\n if (probeResult) {\n return {\n connected: false,\n requiresOAuth: true,\n name,\n namespace,\n toolCount: null,\n serverName: null,\n } satisfies McpProbeResult;\n }\n\n return yield* Effect.fail(\n remoteConnectionError(\"MCP server requires authentication but OAuth discovery failed\"),\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 sd = toStoredSourceData(config);\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 resolved = yield* resolveConnectorInput(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 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 McpToolDiscoveryError | McpConnectionError | StorageFailure\n > =\n Result.isSuccess(resolved)\n ? yield* discoverTools(createMcpConnector(resolved.success)).pipe(\n Effect.mapError((err) =>\n mcpDiscoveryError(`MCP discovery failed: ${err.message}`),\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 =\n 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\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: 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 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 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.storage.removeBindingsByNamespace(namespace, scope);\n yield* ctx.storage.removeSource(namespace, scope);\n yield* ctx.core.sources.unregister(namespace);\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* Effect.fail(\n remoteConnectionError(`No stored config for MCP source \"${namespace}\"`),\n );\n }\n\n const ci = yield* resolveConnectorInput(sd, ctx, allowStdio).pipe(\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((err) => mcpDiscoveryError(`MCP refresh failed: ${err.message}`)),\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(namespace);\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: 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 updateSource = (namespace: string, scope: string, input: McpUpdateSourceInput) =>\n Effect.gen(function* () {\n const existing = yield* ctx.storage.getSource(namespace, scope);\n if (!existing || existing.config.transport !== \"remote\") return;\n\n const remote = existing.config;\n const updatedConfig: McpStoredSourceData = {\n ...remote,\n ...(input.endpoint !== undefined ? { endpoint: input.endpoint } : {}),\n ...(input.headers !== undefined ? { headers: input.headers } : {}),\n ...(input.auth !== undefined ? { auth: input.auth } : {}),\n ...(input.queryParams !== undefined ? { queryParams: input.queryParams } : {}),\n };\n\n yield* ctx.storage.putSource({\n namespace,\n scope,\n name: input.name?.trim() || existing.name,\n config: updatedConfig,\n });\n }).pipe(\n Effect.withSpan(\"mcp.plugin.update_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 updateSource,\n } satisfies McpPluginExtension;\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 + mcp_source rows live at the same scope, so\n // pin every store lookup to it instead of relying on the\n // scoped adapter's stack-wide fall-through.\n const toolScope = toolRow.scope_id as string;\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* Effect.fail(new Error(`No MCP binding found for tool \"${toolRow.id}\"`));\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* Effect.fail(\n new Error(`No MCP source config for namespace \"${entry.namespace}\"`),\n );\n }\n\n return yield* invokeMcpTool({\n toolId: toolRow.id,\n toolName: entry.binding.toolName,\n args,\n sourceData: sd,\n invokerScope: ctx.scopes[0]!.id as string,\n resolveConnector: () =>\n resolveConnectorInput(sd, ctx, allowStdio).pipe(\n Effect.flatMap((ci) => createMcpConnector(ci)),\n Effect.mapError((err) =>\n err instanceof McpConnectionError\n ? err\n : new McpConnectionError({\n transport: \"auto\",\n message: err instanceof Error ? err.message : String(err),\n }),\n ),\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 }).pipe(\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 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 (parsed._tag === \"None\") 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 new SourceDetectionResult({\n kind: \"mcp\",\n confidence: \"high\",\n endpoint: trimmed,\n name,\n namespace,\n });\n }\n\n // host publishes RFC 9728 + 8414 metadata) would be classified\n // as MCP whenever the cross-plugin detector fans out to us.\n const shape = yield* probeMcpEndpointShape(trimmed);\n if (shape.kind !== \"mcp\") return null;\n\n // Confirm OAuth metadata is actually reachable. The shape\n // probe already found a Bearer challenge; the core OAuth\n // service's probe verifies the AS metadata resolves so we\n // don't classify endpoints that challenge but have no\n // discovery.\n const probeOk = yield* ctx.oauth.probe({ endpoint: trimmed }).pipe(\n Effect.map(() => true),\n Effect.catch(() => Effect.succeed(false)),\n Effect.withSpan(\"mcp.plugin.probe_oauth\"),\n );\n if (!probeOk) return null;\n\n return new SourceDetectionResult({\n kind: \"mcp\",\n confidence: \"high\",\n endpoint: trimmed,\n name,\n namespace,\n });\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 row the scoped adapter\n // sees 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.storage.removeBindingsByNamespace(sourceId, scope);\n yield* ctx.storage.removeSource(sourceId, scope);\n }),\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. `McpHandlers` requires `McpExtensionService`; the\n // host satisfies it via the `extensionService` Tag — at boot for\n // local, per request for cloud.\n routes: () => McpGroup,\n handlers: () => McpHandlers,\n extensionService: McpExtensionService,\n };\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 readonly updateSource: (\n namespace: string,\n scope: string,\n input: McpUpdateSourceInput,\n ) => Effect.Effect<void, McpExtensionFailure>;\n}\n","import { HttpApiEndpoint, HttpApiGroup } from \"effect/unstable/httpapi\";\nimport { Schema } from \"effect\";\nimport { ScopeId, SecretBackedMap } from \"@executor-js/sdk/core\";\nimport { InternalError } from \"@executor-js/api\";\n\nimport { McpConnectionError, McpToolDiscoveryError } from \"../sdk/errors\";\nimport { McpStoredSourceSchema } from \"../sdk/stored-source\";\n\n// ---------------------------------------------------------------------------\n// Params\n// ---------------------------------------------------------------------------\n\nconst ScopeParams = { scopeId: ScopeId };\nconst SourceParams = { scopeId: ScopeId, namespace: Schema.String };\n\n// ---------------------------------------------------------------------------\n// Auth payload (only for remote)\n// ---------------------------------------------------------------------------\n\nconst AuthPayload = Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"none\") }),\n Schema.Struct({\n kind: Schema.Literal(\"header\"),\n headerName: Schema.String,\n secretId: Schema.String,\n prefix: Schema.optional(Schema.String),\n }),\n Schema.Struct({\n kind: Schema.Literal(\"oauth2\"),\n /** Stable id of the SDK Connection minted by `completeOAuth`. The\n * backing access/refresh secrets live on the connection row; the\n * source only needs this pointer. */\n connectionId: Schema.String,\n clientIdSecretId: Schema.optional(Schema.String),\n clientSecretSecretId: Schema.optional(Schema.NullOr(Schema.String)),\n }),\n]);\n\nconst StringMap = Schema.Record(Schema.String, Schema.String);\n// ---------------------------------------------------------------------------\n// Add source — discriminated union on transport\n// ---------------------------------------------------------------------------\n\nconst AddRemoteSourcePayload = Schema.Struct({\n transport: Schema.Literal(\"remote\"),\n name: Schema.String,\n endpoint: Schema.String,\n remoteTransport: Schema.optional(Schema.Literals([\"streamable-http\", \"sse\", \"auto\"])),\n namespace: Schema.optional(Schema.String),\n queryParams: Schema.optional(SecretBackedMap),\n headers: Schema.optional(SecretBackedMap),\n auth: Schema.optional(AuthPayload),\n});\n\nconst AddStdioSourcePayload = 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(StringMap),\n cwd: Schema.optional(Schema.String),\n namespace: Schema.optional(Schema.String),\n});\n\nconst AddSourcePayload = Schema.Union([AddRemoteSourcePayload, AddStdioSourcePayload]);\n\n// ---------------------------------------------------------------------------\n// Other payloads\n// ---------------------------------------------------------------------------\n\nconst UpdateSourcePayload = Schema.Struct({\n name: Schema.optional(Schema.String),\n endpoint: Schema.optional(Schema.String),\n headers: Schema.optional(SecretBackedMap),\n queryParams: Schema.optional(SecretBackedMap),\n auth: Schema.optional(AuthPayload),\n});\n\nconst UpdateSourceResponse = Schema.Struct({\n updated: Schema.Boolean,\n});\n\nconst ProbeEndpointPayload = Schema.Struct({\n endpoint: Schema.String,\n headers: Schema.optional(SecretBackedMap),\n queryParams: Schema.optional(SecretBackedMap),\n});\n\nconst ProbeEndpointResponse = Schema.Struct({\n connected: Schema.Boolean,\n requiresOAuth: 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 NamespacePayload = Schema.Struct({\n namespace: Schema.String,\n});\n\n// ---------------------------------------------------------------------------\n// Responses\n// ---------------------------------------------------------------------------\n\nconst AddSourceResponse = Schema.Struct({\n toolCount: Schema.Number,\n namespace: Schema.String,\n});\n\nconst RefreshSourceResponse = Schema.Struct({\n toolCount: Schema.Number,\n});\n\nconst RemoveSourceResponse = Schema.Struct({\n removed: Schema.Boolean,\n});\n\n// ---------------------------------------------------------------------------\n// Group\n//\n// Plugin SDK errors (McpOAuthError etc.) are declared once at the group\n// level via `.addError(...)` — every endpoint inherits them. The errors\n// themselves carry their HTTP status via `HttpApiSchema.annotations`\n// in errors.ts, so handlers just `return yield* ext.foo(...)` and the\n// schema encodes whatever it gets.\n//\n// 5xx is handled at the API level: `CoreExecutorApi.addError(InternalError)`\n// adds a single shared opaque-by-schema 500 surface to every endpoint in\n// the entire API. Defects are captured + downgraded to it by an\n// HttpApiBuilder middleware (see apps/cloud/src/observability.ts).\n// No per-handler wrapping, no per-plugin InternalError.\n// ---------------------------------------------------------------------------\n\nexport const McpGroup = HttpApiGroup.make(\"mcp\")\n .add(\n HttpApiEndpoint.post(\"probeEndpoint\", \"/scopes/:scopeId/mcp/probe\", {\n params: ScopeParams,\n payload: ProbeEndpointPayload,\n success: ProbeEndpointResponse,\n error: [InternalError, McpConnectionError, McpToolDiscoveryError],\n }),\n )\n .add(\n HttpApiEndpoint.post(\"addSource\", \"/scopes/:scopeId/mcp/sources\", {\n params: ScopeParams,\n payload: AddSourcePayload,\n success: AddSourceResponse,\n error: [InternalError, McpConnectionError, McpToolDiscoveryError],\n }),\n )\n .add(\n HttpApiEndpoint.post(\"removeSource\", \"/scopes/:scopeId/mcp/sources/remove\", {\n params: ScopeParams,\n payload: NamespacePayload,\n success: RemoveSourceResponse,\n error: [InternalError, McpConnectionError, McpToolDiscoveryError],\n }),\n )\n .add(\n HttpApiEndpoint.post(\"refreshSource\", \"/scopes/:scopeId/mcp/sources/refresh\", {\n params: ScopeParams,\n payload: NamespacePayload,\n success: RefreshSourceResponse,\n error: [InternalError, McpConnectionError, McpToolDiscoveryError],\n }),\n )\n .add(\n HttpApiEndpoint.get(\"getSource\", \"/scopes/:scopeId/mcp/sources/:namespace\", {\n params: SourceParams,\n success: Schema.NullOr(McpStoredSourceSchema),\n error: [InternalError, McpConnectionError, McpToolDiscoveryError],\n }),\n )\n .add(\n HttpApiEndpoint.patch(\"updateSource\", \"/scopes/:scopeId/mcp/sources/:namespace\", {\n params: SourceParams,\n payload: UpdateSourcePayload,\n success: UpdateSourceResponse,\n error: [InternalError, McpConnectionError, McpToolDiscoveryError],\n }),\n )\n // Errors declared once at the group level — every endpoint inherits.\n // Plugin domain errors carry their own HttpApiSchema status (4xx);\n // `InternalError` is the shared opaque 500 translated at the HTTP\n // edge by `withCapture`. We only list errors an MCP *group*\n // endpoint can surface: `McpInvocationError` is thrown inside\n // `invokeTool` which is reached via the core `tools.invoke`\n // endpoint, not any MCP-group endpoint, so it doesn't belong here.\n // OAuth errors live on the shared `/oauth/*` group in `@executor-js/api`\n // now — the MCP group only declares its own plugin-domain errors.\n;\n","// MCP plugin tagged errors. Each carries an `HttpApiSchema` annotation so\n// it can be `.addError(...)` directly on the API group — handlers return\n// these and HttpApi encodes them as 4xx responses with a typed body. No\n// per-handler sanitisation step.\n\nimport { Schema } from \"effect\";\n\nexport class McpConnectionError extends Schema.TaggedErrorClass<McpConnectionError>()(\n \"McpConnectionError\",\n {\n transport: Schema.String,\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class McpToolDiscoveryError extends Schema.TaggedErrorClass<McpToolDiscoveryError>()(\n \"McpToolDiscoveryError\",\n {\n stage: Schema.Literals([\"connect\", \"list_tools\"]),\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class McpInvocationError extends Schema.TaggedErrorClass<McpInvocationError>()(\n \"McpInvocationError\",\n {\n toolName: Schema.String,\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class McpOAuthError extends Schema.TaggedErrorClass<McpOAuthError>()(\n \"McpOAuthError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n","import { Schema } from \"effect\";\n\nimport { McpStoredSourceData } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Stored source — the shape persisted by the binding store and exposed\n// via the getSource HTTP endpoint.\n// ---------------------------------------------------------------------------\n\nexport class McpStoredSourceSchema extends Schema.Class<McpStoredSourceSchema>(\"McpStoredSource\")({\n namespace: Schema.String,\n name: Schema.String,\n config: McpStoredSourceData,\n}) {}\n\nexport type McpStoredSourceSchemaType = typeof McpStoredSourceSchema.Type;\n","import { HttpApiBuilder } from \"effect/unstable/httpapi\";\nimport { Context, Effect } from \"effect\";\n\nimport { addGroup, capture } from \"@executor-js/api\";\nimport type {\n McpPluginExtension,\n McpProbeEndpointInput,\n McpSourceConfig,\n McpUpdateSourceInput,\n} from \"../sdk/plugin\";\nimport type { SecretBackedValue } from \"../sdk/types\";\nimport { McpStoredSourceSchema } from \"../sdk/stored-source\";\nimport { McpGroup } from \"./group\";\n\n// ---------------------------------------------------------------------------\n// Service tag — holds the raw extension shape the executor produces.\n// Handlers wrap their generator bodies with `capture(...)` from\n// `@executor-js/api`, which translates `StorageError` to `InternalError`\n// at the edge; that's why the tag type matches the SDK shape directly\n// (no `Captured<>` inversion).\n// ---------------------------------------------------------------------------\n\nexport class McpExtensionService extends Context.Service<McpExtensionService, McpPluginExtension\n>()(\"McpExtensionService\") {}\n\n// ---------------------------------------------------------------------------\n// Composed API\n// ---------------------------------------------------------------------------\n\nconst ExecutorApiWithMcp = addGroup(McpGroup);\n\n// ---------------------------------------------------------------------------\n// Convert API payload → McpSourceConfig\n// ---------------------------------------------------------------------------\n\nconst toSourceConfig = (\n payload: { transport: \"remote\" | \"stdio\" } & Record<string, unknown>,\n scope: string,\n): McpSourceConfig => {\n if (payload.transport === \"stdio\") {\n const p = payload as {\n transport: \"stdio\";\n name: string;\n command: string;\n args?: readonly string[];\n env?: Record<string, string>;\n cwd?: string;\n namespace?: string;\n };\n return {\n transport: \"stdio\",\n scope,\n name: p.name,\n command: p.command,\n args: p.args ? [...p.args] : undefined,\n env: p.env,\n cwd: p.cwd,\n namespace: p.namespace,\n };\n }\n\n const p = payload as {\n transport: \"remote\";\n name: string;\n endpoint: string;\n remoteTransport?: \"streamable-http\" | \"sse\" | \"auto\";\n queryParams?: Record<string, SecretBackedValue>;\n headers?: Record<string, SecretBackedValue>;\n namespace?: string;\n auth?: { kind: string } & Record<string, unknown>;\n };\n\n return {\n transport: \"remote\",\n scope,\n name: p.name,\n endpoint: p.endpoint,\n remoteTransport: p.remoteTransport,\n queryParams: p.queryParams,\n headers: p.headers,\n namespace: p.namespace,\n auth: p.auth as McpSourceConfig extends { auth?: infer A } ? A : never,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Handlers\n//\n// Each handler is exactly: yield the extension service, call the method,\n// return. Plugin SDK errors flow through the typed channel and are\n// schema-encoded to 4xx by HttpApi (see group.ts `.addError(...)` calls).\n// Defects bubble up and are captured + downgraded to `InternalError(traceId)`\n// by the API-level observability middleware (see apps/cloud/src/observability.ts).\n//\n// No `sanitize*`, no `liftDomainErrors`, no `withObservability` per handler.\n// If you find yourself adding error-handling here you're in the wrong layer.\n// ---------------------------------------------------------------------------\n\nexport const McpHandlers = HttpApiBuilder.group(ExecutorApiWithMcp, \"mcp\", (handlers) =>\n handlers\n .handle(\"probeEndpoint\", ({ payload }) =>\n capture(\n Effect.gen(function* () {\n const ext = yield* McpExtensionService;\n return yield* ext.probeEndpoint(payload as McpProbeEndpointInput);\n }),\n ),\n )\n .handle(\"addSource\", ({ params: path, payload }) =>\n capture(\n Effect.gen(function* () {\n const ext = yield* McpExtensionService;\n return yield* ext.addSource(\n toSourceConfig(payload as Parameters<typeof toSourceConfig>[0], path.scopeId),\n );\n }),\n ),\n )\n .handle(\"removeSource\", ({ params: path, payload }) =>\n capture(\n Effect.gen(function* () {\n const ext = yield* McpExtensionService;\n yield* ext.removeSource(payload.namespace, path.scopeId);\n return { removed: true };\n }),\n ),\n )\n .handle(\"refreshSource\", ({ params: path, payload }) =>\n capture(\n Effect.gen(function* () {\n const ext = yield* McpExtensionService;\n return yield* ext.refreshSource(payload.namespace, path.scopeId);\n }),\n ),\n )\n .handle(\"getSource\", ({ params: path }) =>\n capture(\n Effect.gen(function* () {\n const ext = yield* McpExtensionService;\n const source = yield* ext.getSource(path.namespace, path.scopeId);\n return source\n ? new McpStoredSourceSchema({\n namespace: source.namespace,\n name: source.name,\n config: source.config,\n })\n : null;\n }),\n ),\n )\n .handle(\"updateSource\", ({ params: path, payload }) =>\n capture(\n Effect.gen(function* () {\n const ext = yield* McpExtensionService;\n yield* ext.updateSource(path.namespace, path.scopeId, {\n name: payload.name,\n endpoint: payload.endpoint,\n headers: payload.headers,\n queryParams: payload.queryParams,\n auth: payload.auth as McpUpdateSourceInput[\"auth\"],\n });\n return { updated: true };\n }),\n ),\n ),\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: (cause) =>\n new McpConnectionError({\n transport: input.transport,\n message: `Failed connecting via ${input.transport}: ${\n cause instanceof Error ? cause.message : String(cause)\n }`,\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: (cause) =>\n new McpConnectionError({\n transport: \"stdio\",\n message: `Failed to load stdio transport module: ${\n cause instanceof Error ? cause.message : String(cause)\n }`,\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 (err) =>\n new McpToolDiscoveryError({\n stage: \"connect\",\n message: `Failed connecting to MCP server: ${err.message}`,\n }),\n ),\n );\n\n // List tools\n const listResult = yield* Effect.tryPromise({\n try: () => connection.client.listTools(),\n catch: (cause) =>\n new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: `Failed listing MCP tools: ${\n cause instanceof Error ? cause.message : String(cause)\n }`,\n }),\n });\n\n if (!isListToolsResult(listResult)) {\n yield* Effect.promise(() => connection.close().catch(() => {}));\n return yield* Effect.fail(\n new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: \"MCP listTools response did not match the expected schema\",\n }),\n );\n }\n\n const manifest = extractManifestFromListToolsResult(listResult, {\n serverInfo: connection.client.getServerVersion?.(),\n });\n\n // Close the connection after discovery\n yield* Effect.promise(() => connection.close().catch(() => {}));\n\n return manifest;\n });\n","import { 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 decodeListToolsResult(value)._tag === \"Some\";\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((opt) =>\n opt._tag === \"Some\" ? opt.value.tools : [],\n );\n\n const server = decodeServerInfo(metadata?.serverInfo).pipe((opt): McpServerMetadata | null =>\n opt._tag === \"Some\"\n ? { name: opt.value.name ?? null, version: opt.value.version ?? null }\n : null,\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 try {\n return new URL(url).hostname;\n } catch {\n return null;\n }\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, 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 { McpConnectionError, McpInvocationError } from \"./errors\";\nimport type { McpConnection } from \"./connection\";\nimport type { McpStoredSourceData } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst asRecord = (value: unknown): Record<string, unknown> =>\n typeof value === \"object\" && value !== null && !Array.isArray(value)\n ? (value as Record<string, unknown>)\n : {};\n\nconst connectionCacheKey = (\n sd: McpStoredSourceData,\n invokerScope: string,\n): string =>\n sd.transport === \"stdio\"\n ? `stdio:${sd.command}`\n : // Remote sources may resolve per-user secrets (OAuth tokens, header\n // auth) via scope shadowing, so two users invoking the same source\n // get different Authorization headers. The connection caches that\n // header in transport state, so the cache key must include the\n // invoking scope — otherwise user B re-uses user A's connection\n // (and user A's tokens).\n `remote:${invokerScope}:${sd.endpoint}`;\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 ? new UrlElicitation({\n message: params.message,\n url: params.url,\n elicitationId: params.elicitationId ?? params.id ?? \"\",\n })\n : new FormElicitation({\n message: params.message,\n requestedSchema: params.requestedSchema,\n });\n\nconst installElicitationHandler = (\n client: McpConnection[\"client\"],\n elicit: Elicit,\n): void => {\n client.setRequestHandler(\n ElicitRequestSchema,\n 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\n ? { content: response.content }\n : {}),\n };\n }\n const failure = exit.cause.reasons.find(Cause.isFailReason);\n if (failure) {\n const err = failure.error as {\n readonly _tag?: string;\n readonly action?: \"decline\" | \"cancel\";\n };\n if (err._tag === \"ElicitationDeclinedError\") {\n return { action: err.action ?? \"decline\" };\n }\n }\n throw Cause.squash(exit.cause);\n },\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: (cause) =>\n new McpInvocationError({\n toolName,\n message: `MCP tool call failed for ${toolName}: ${\n cause instanceof Error ? cause.message : String(cause)\n }`,\n }),\n }).pipe(\n Effect.withSpan(\"plugin.mcp.client.call_tool\", {\n attributes: { \"mcp.tool.name\": toolName },\n }),\n );\n });\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface InvokeMcpToolInput {\n readonly toolId: string;\n readonly toolName: string;\n readonly args: unknown;\n readonly sourceData: McpStoredSourceData;\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<McpConnection, McpConnectionError>;\n readonly connectionCache: ScopedCache.ScopedCache<\n string,\n McpConnection,\n McpConnectionError\n >;\n readonly pendingConnectors: Map<\n string,\n Effect.Effect<McpConnection, McpConnectionError>\n >;\n readonly elicit: Elicit;\n}\n\nexport const invokeMcpTool = (\n input: InvokeMcpToolInput,\n): Effect.Effect<unknown, McpConnectionError | McpInvocationError> => {\n const transport: string =\n input.sourceData.transport === \"stdio\"\n ? \"stdio\"\n : (input.sourceData.remoteTransport ?? \"auto\");\n return Effect.gen(function* () {\n const cacheKey = connectionCacheKey(input.sourceData, input.invokerScope);\n const args = asRecord(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(\n firstConnection,\n input.toolName,\n args,\n input.elicit,\n ).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(\n fresh,\n input.toolName,\n args,\n input.elicit,\n );\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. When\n// `discoverTools` fails, plugin.ts falls through to\n// `startMcpOAuthAuthorization`, which succeeds against *any* URL whose\n// origin publishes OAuth 2.0 Protected Resource + Authorization Server\n// Metadata (RFC 9728 + RFC 8414) — that's what the MCP SDK's `auth()`\n// consumes. Plenty of non-MCP APIs (Railway's `backboard.railway.com/\n// graphql/v2`, anything backed by a standards-compliant OAuth AS)\n// publish that metadata, so the fall-through misclassifies them.\n//\n// The MCP authorization spec (`modelcontextprotocol.io/specification/\n// draft/basic/authorization`) mandates the handshake that distinguishes\n// a real MCP-requires-OAuth endpoint from the general case:\n//\n// - On an unauthenticated request the server MUST respond `401` and\n// include `WWW-Authenticate: Bearer` with a `resource_metadata=`\n// attribute pointing at its RFC 9728 document.\n//\n// This module issues an unauth JSON-RPC `initialize` POST and checks\n// exactly that shape. That's enough to separate \"MCP server that needs\n// OAuth\" from \"non-MCP service whose host happens to publish OAuth\n// metadata\". It's a single `fetch`, no MCP-SDK session state, no OAuth\n// round-trip, no DCR — every non-MCP endpoint exits here.\n// ---------------------------------------------------------------------------\n\nimport { Effect } from \"effect\";\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: Headers, name: string): string | null => {\n const direct = headers.get(name);\n if (direct !== null) return direct;\n const lower = name.toLowerCase();\n for (const [k, v] of headers) {\n if (k.toLowerCase() === lower) return v;\n }\n return null;\n};\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 | { readonly kind: \"not-mcp\"; readonly reason: string }\n /** Transport-level failure (DNS, TLS, timeout, abort, ...). */\n | { readonly kind: \"unreachable\"; readonly reason: string };\n\nexport interface ProbeOptions {\n /** Injected for tests. Defaults to the global `fetch`. */\n readonly fetch?: typeof fetch;\n /** Abort the request after this many ms. Default 8000. */\n readonly timeoutMs?: number;\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 fetchImpl = options.fetch ?? globalThis.fetch;\n const timeoutMs = options.timeoutMs ?? 8_000;\n\n const outcome = yield* Effect.tryPromise({\n try: async (): Promise<McpShapeProbeResult> => {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n try {\n const classify = (response: Response, method: \"GET\" | \"POST\") => {\n if (response.status === 401) {\n const wwwAuth = readHeader(response.headers, \"www-authenticate\");\n if (wwwAuth && /^\\s*bearer\\b/i.test(wwwAuth)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n return {\n kind: \"not-mcp\",\n reason:\n \"401 without Bearer WWW-Authenticate — not an MCP auth challenge\",\n } as const;\n }\n\n if (response.status >= 200 && response.status < 300) {\n if (method === \"GET\") {\n const contentType = readHeader(response.headers, \"content-type\") ?? \"\";\n if (!/^\\s*text\\/event-stream\\b/i.test(contentType)) {\n return {\n kind: \"not-mcp\",\n reason: \"GET response is not an SSE stream\",\n } as const;\n }\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 const authHeaders = options.headers ?? {};\n\n const postResponse = await fetchImpl(url, {\n method: \"POST\",\n headers: {\n ...authHeaders,\n \"content-type\": \"application/json\",\n accept: \"application/json, text/event-stream\",\n },\n body: INITIALIZE_BODY,\n signal: controller.signal,\n });\n\n const postResult = classify(postResponse, \"POST\");\n if (postResult) return postResult;\n\n if ([404, 405, 406, 415].includes(postResponse.status)) {\n const getResponse = await fetchImpl(url, {\n method: \"GET\",\n headers: { ...authHeaders, accept: \"text/event-stream\" },\n signal: controller.signal,\n });\n const getResult = classify(getResponse, \"GET\");\n if (getResult) return getResult;\n }\n\n return {\n kind: \"not-mcp\",\n reason: `unexpected status ${postResponse.status} for initialize`,\n };\n } finally {\n clearTimeout(timer);\n }\n },\n catch: (cause) => cause,\n }).pipe(\n Effect.catch((cause) =>\n Effect.succeed<McpShapeProbeResult>({\n kind: \"unreachable\",\n reason: cause instanceof Error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;AAAA,MACvB;AAAA,IACF,CAAC,EAAE,KAAKH,QAAO,SAAS,kBAAkB,CAAC;AAAA;AAAA;AAAA;AAAA,IAK7C,QAAQ,MAAM;AAAA,IACd,UAAU,MAAM;AAAA,IAChB,kBAAkB;AAAA,EACpB;AACF,CAAC;","names":["Effect","Schema","Schema","Effect","Effect","Exit","ScopedCache","Schema","SecretBackedMap","Schema","Schema","Schema","Schema","StringMap","SecretBackedMap","Effect","p","Effect","Effect","Effect","Effect","Schema","Schema","Effect","Effect","Schema","Schema","Effect","Effect","Effect","ScopedCache","entry","Exit"]}
|