@executor-js/plugin-mcp 1.4.27 → 1.4.29

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.
@@ -202,7 +202,7 @@ function StdioReadOnly(props) {
202
202
  return /* @__PURE__ */ jsxs("div", { className: "space-y-6", children: [
203
203
  /* @__PURE__ */ jsxs("div", { children: [
204
204
  /* @__PURE__ */ jsx("h1", { className: "text-xl font-semibold text-foreground", children: "Edit MCP Source" }),
205
- /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-muted-foreground", children: "Stdio MCP sources cannot be edited in the UI. Modify the executor.jsonc config file directly." })
205
+ /* @__PURE__ */ jsx("p", { className: "mt-1 text-sm text-muted-foreground", children: "Stdio MCP sources cannot be edited in the UI. Remove and recreate the source with the updated command." })
206
206
  ] }),
207
207
  /* @__PURE__ */ jsxs("div", { className: "flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3", children: [
208
208
  /* @__PURE__ */ jsxs("div", { className: "min-w-0 flex-1", children: [
@@ -256,4 +256,4 @@ function EditMcpSource({
256
256
  export {
257
257
  EditMcpSource as default
258
258
  };
259
- //# sourceMappingURL=EditMcpSource-CWN6HIC4.js.map
259
+ //# sourceMappingURL=EditMcpSource-FAWEECNU.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/react/EditMcpSource.tsx"],"sourcesContent":["import { useState } from \"react\";\nimport { useAtomValue, useAtomSet } from \"@effect/atom-react\";\nimport * as AsyncResult from \"effect/unstable/reactivity/AsyncResult\";\nimport * as Exit from \"effect/Exit\";\nimport {\n mcpSourceAtom,\n mcpSourceBindingsAtom,\n setMcpSourceBinding,\n updateMcpSource,\n} from \"./atoms\";\nimport { connectionsAtom } from \"@executor-js/react/api/atoms\";\nimport { useScope, useScopeStack } from \"@executor-js/react/api/scope-context\";\nimport { connectionWriteKeys, sourceWriteKeys } from \"@executor-js/react/api/reactivity-keys\";\nimport { slugifyNamespace, useSourceIdentity } from \"@executor-js/react/plugins/source-identity\";\nimport { useCredentialTargetScope } from \"@executor-js/react/plugins/credential-target-scope\";\nimport { useSecretPickerSecrets } from \"@executor-js/react/plugins/use-secret-picker-secrets\";\nimport {\n HttpCredentialsEditor,\n serializeHttpCredentials,\n serializeScopedHttpCredentials,\n type HttpCredentialsState,\n} from \"@executor-js/react/plugins/http-credentials\";\nimport {\n effectiveCredentialBindingForScope,\n httpCredentialsFromConfiguredCredentialBindings,\n initialCredentialTargetScope,\n} from \"@executor-js/react/plugins/credential-bindings\";\nimport { SourceOAuthConnectionControl } from \"@executor-js/react/plugins/source-oauth-connection\";\nimport { Button } from \"@executor-js/react/components/button\";\nimport { Badge } from \"@executor-js/react/components/badge\";\nimport { ScopeId } from \"@executor-js/sdk/core\";\nimport { McpRemoteSourceFields } from \"./McpRemoteSourceFields\";\nimport {\n McpSourceBindingInput,\n type McpCredentialInput,\n type McpSourceBindingRef,\n} from \"../sdk/types\";\nimport type { McpStoredSourceSchemaType } from \"../sdk/stored-source\";\n\n// ---------------------------------------------------------------------------\n// Remote edit form\n// ---------------------------------------------------------------------------\n\nfunction RemoteEditForm(props: {\n sourceId: string;\n initial: McpStoredSourceSchemaType & { config: { transport: \"remote\" } };\n bindings: readonly McpSourceBindingRef[];\n onSave: () => void;\n}) {\n const displayScope = useScope();\n const scopeStack = useScopeStack();\n const sourceScope = ScopeId.make(props.initial.scope);\n const { credentialTargetScope, credentialScopeOptions } = useCredentialTargetScope({\n sourceScope,\n initialTargetScope: initialCredentialTargetScope(sourceScope, props.bindings),\n });\n const {\n credentialTargetScope: oauthCredentialTargetScope,\n setCredentialTargetScope: setOAuthCredentialTargetScope,\n } = useCredentialTargetScope({\n sourceScope,\n initialTargetScope: initialCredentialTargetScope(sourceScope, props.bindings),\n });\n const doUpdate = useAtomSet(updateMcpSource, { mode: \"promiseExit\" });\n const setBinding = useAtomSet(setMcpSourceBinding, { mode: \"promise\" });\n const secretList = useSecretPickerSecrets();\n const connectionsResult = useAtomValue(connectionsAtom(displayScope));\n\n const identity = useSourceIdentity({\n fallbackName: props.initial.name,\n fallbackNamespace: props.initial.namespace,\n });\n const [endpoint, setEndpoint] = useState(props.initial.config.endpoint);\n const [credentials, setCredentials] = useState<HttpCredentialsState>(() =>\n httpCredentialsFromConfiguredCredentialBindings({\n headers: props.initial.config.headers,\n queryParams: props.initial.config.queryParams,\n bindings: props.bindings,\n }),\n );\n const [saving, setSaving] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [credentialsDirty, setCredentialsDirty] = useState(false);\n\n const identityDirty = identity.name.trim() !== props.initial.name.trim();\n const metadataDirty = identityDirty || endpoint.trim() !== props.initial.config.endpoint.trim();\n const dirty = metadataDirty || credentialsDirty;\n const oauth2 = props.initial.config.auth.kind === \"oauth2\" ? props.initial.config.auth : null;\n const connections = AsyncResult.isSuccess(connectionsResult) ? connectionsResult.value : [];\n const scopeRanks = new Map(scopeStack.map((scope, index) => [scope.id, index] as const));\n const connectionBinding = oauth2\n ? effectiveCredentialBindingForScope(\n props.bindings,\n oauth2.connectionSlot,\n oauthCredentialTargetScope,\n scopeRanks,\n )\n : null;\n const boundConnectionId =\n connectionBinding?.value.kind === \"connection\" ? connectionBinding.value.connectionId : null;\n const isConnected =\n boundConnectionId !== null &&\n connections.some((connection) => connection.id === boundConnectionId);\n const oauthRequestCredentials = serializeHttpCredentials(credentials);\n\n const handleCredentialsChange = (next: HttpCredentialsState) => {\n setCredentials(next);\n setCredentialsDirty(true);\n };\n\n const handleSave = async () => {\n setSaving(true);\n setError(null);\n const { headers, queryParams } = serializeScopedHttpCredentials(\n credentials,\n credentialTargetScope,\n );\n const payload: {\n sourceScope: ScopeId;\n name?: string;\n endpoint?: string;\n headers?: Record<string, McpCredentialInput>;\n queryParams?: Record<string, McpCredentialInput>;\n credentialTargetScope?: ScopeId;\n } = {\n sourceScope,\n name: metadataDirty ? identity.name.trim() || undefined : undefined,\n endpoint: metadataDirty ? endpoint.trim() || undefined : undefined,\n };\n if (credentialsDirty) {\n payload.headers = headers;\n payload.queryParams = queryParams as Record<string, McpCredentialInput>;\n payload.credentialTargetScope = credentialTargetScope;\n }\n const exit = await doUpdate({\n params: { scopeId: displayScope, namespace: props.sourceId },\n payload,\n reactivityKeys: sourceWriteKeys,\n });\n if (Exit.isFailure(exit)) {\n setError(\"Failed to update source\");\n setSaving(false);\n return;\n }\n setCredentialsDirty(false);\n setSaving(false);\n props.onSave();\n };\n\n return (\n <div className=\"space-y-6\">\n <div>\n <h1 className=\"text-xl font-semibold text-foreground\">Edit MCP Source</h1>\n <p className=\"mt-1 text-sm text-muted-foreground\">\n Update the endpoint and headers for this MCP connection.\n </p>\n </div>\n\n <div className=\"flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3\">\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate text-sm font-semibold text-card-foreground\">{props.sourceId}</p>\n </div>\n <Badge variant=\"secondary\" className=\"text-xs\">\n remote\n </Badge>\n </div>\n\n <McpRemoteSourceFields\n url={endpoint}\n onUrlChange={setEndpoint}\n identity={identity}\n preview={{\n name: props.initial.name,\n serverName: props.initial.name,\n connected: true,\n toolCount: null,\n }}\n namespaceReadOnly\n />\n\n <HttpCredentialsEditor\n credentials={credentials}\n onChange={handleCredentialsChange}\n existingSecrets={secretList}\n sourceName={identity.name}\n targetScope={credentialTargetScope}\n credentialScopeOptions={credentialScopeOptions}\n bindingScopeOptions={credentialScopeOptions}\n />\n\n {oauth2 && (\n <SourceOAuthConnectionControl\n popupName=\"mcp-oauth\"\n pluginId=\"mcp\"\n namespace={slugifyNamespace(props.initial.namespace) || \"mcp\"}\n fallbackNamespace=\"mcp\"\n endpoint={endpoint.trim()}\n tokenScope={oauthCredentialTargetScope}\n onTokenScopeChange={setOAuthCredentialTargetScope}\n credentialScopeOptions={credentialScopeOptions}\n connectionId={boundConnectionId}\n sourceLabel={`${identity.name.trim() || props.initial.namespace || \"MCP\"} OAuth`}\n headers={oauthRequestCredentials.headers}\n queryParams={oauthRequestCredentials.queryParams}\n isConnected={isConnected}\n onConnected={async (connectionId) => {\n await setBinding({\n params: { scopeId: oauthCredentialTargetScope },\n payload: McpSourceBindingInput.make({\n sourceId: props.sourceId,\n sourceScope,\n scope: oauthCredentialTargetScope,\n slot: oauth2.connectionSlot,\n value: { kind: \"connection\", connectionId },\n }),\n reactivityKeys: [...sourceWriteKeys, ...connectionWriteKeys],\n });\n }}\n reconnectingLabel=\"Reconnecting…\"\n signingInLabel=\"Signing in…\"\n />\n )}\n\n {error && (\n <div className=\"rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2\">\n <p className=\"text-sm text-destructive\">{error}</p>\n </div>\n )}\n\n <div className=\"flex items-center justify-between border-t border-border pt-4\">\n <Button variant=\"ghost\" onClick={props.onSave}>\n Cancel\n </Button>\n <Button onClick={handleSave} disabled={!dirty || saving}>\n {saving ? \"Saving…\" : \"Save changes\"}\n </Button>\n </div>\n </div>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Stdio read-only view\n// ---------------------------------------------------------------------------\n\nfunction StdioReadOnly(props: {\n sourceId: string;\n initial: McpStoredSourceSchemaType & { config: { transport: \"stdio\" } };\n onSave: () => void;\n}) {\n const { command, args } = props.initial.config;\n return (\n <div className=\"space-y-6\">\n <div>\n <h1 className=\"text-xl font-semibold text-foreground\">Edit MCP Source</h1>\n <p className=\"mt-1 text-sm text-muted-foreground\">\n Stdio MCP sources cannot be edited in the UI. Modify the executor.jsonc config file\n directly.\n </p>\n </div>\n\n <div className=\"flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3\">\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate text-sm font-semibold text-card-foreground\">{props.sourceId}</p>\n <p className=\"mt-0.5 text-xs text-muted-foreground font-mono\">\n {command} {(args ?? []).join(\" \")}\n </p>\n </div>\n <Badge variant=\"secondary\" className=\"text-xs\">\n stdio\n </Badge>\n </div>\n\n <div className=\"flex items-center justify-end border-t border-border pt-4\">\n <Button onClick={props.onSave}>Done</Button>\n </div>\n </div>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Main component\n// ---------------------------------------------------------------------------\n\nexport default function EditMcpSource({\n sourceId,\n onSave,\n}: {\n readonly sourceId: string;\n readonly onSave: () => void;\n}) {\n const scopeId = useScope();\n const sourceResult = useAtomValue(mcpSourceAtom(scopeId, sourceId)) as AsyncResult.AsyncResult<\n McpStoredSourceSchemaType | null,\n unknown\n >;\n const source =\n AsyncResult.isSuccess(sourceResult) && sourceResult.value ? sourceResult.value : null;\n const sourceScope = source ? ScopeId.make(source.scope) : scopeId;\n const bindingsResult = useAtomValue(mcpSourceBindingsAtom(scopeId, sourceId, sourceScope));\n\n if (!AsyncResult.isSuccess(sourceResult) || !source || !AsyncResult.isSuccess(bindingsResult)) {\n return (\n <div className=\"space-y-6\">\n <div>\n <h1 className=\"text-xl font-semibold text-foreground\">Edit MCP Source</h1>\n <p className=\"mt-1 text-sm text-muted-foreground\">Loading configuration…</p>\n </div>\n </div>\n );\n }\n\n if (source.config.transport === \"stdio\") {\n return (\n <StdioReadOnly\n sourceId={sourceId}\n initial={source as McpStoredSourceSchemaType & { config: { transport: \"stdio\" } }}\n onSave={onSave}\n />\n );\n }\n\n return (\n <RemoteEditForm\n sourceId={sourceId}\n initial={source as McpStoredSourceSchemaType & { config: { transport: \"remote\" } }}\n bindings={bindingsResult.value}\n onSave={onSave}\n />\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,cAAc,kBAAkB;AACzC,YAAY,iBAAiB;AAC7B,YAAY,UAAU;AAOtB,SAAS,uBAAuB;AAChC,SAAS,UAAU,qBAAqB;AACxC,SAAS,qBAAqB,uBAAuB;AACrD,SAAS,kBAAkB,yBAAyB;AACpD,SAAS,gCAAgC;AACzC,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,oCAAoC;AAC7C,SAAS,c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AY,WAAU,WAAU,mBAE/C;AAAA,OACF;AAAA,IAEA,oBAAC,SAAI,WAAU,6DACb,8BAAC,UAAO,SAAS,MAAM,QAAQ,kBAAI,GACrC;AAAA,KACF;AAEJ;AAMe,SAAR,cAA+B;AAAA,EACpC;AAAA,EACA;AACF,GAGG;AACD,QAAM,UAAU,SAAS;AACzB,QAAM,eAAe,aAAa,cAAc,SAAS,QAAQ,CAAC;AAIlE,QAAM,SACQ,sBAAU,YAAY,KAAK,aAAa,QAAQ,aAAa,QAAQ;AACnF,QAAM,cAAc,SAAS,QAAQ,KAAK,OAAO,KAAK,IAAI;AAC1D,QAAM,iBAAiB,aAAa,sBAAsB,SAAS,UAAU,WAAW,CAAC;AAEzF,MAAI,CAAa,sBAAU,YAAY,KAAK,CAAC,UAAU,CAAa,sBAAU,cAAc,GAAG;AAC7F,WACE,oBAAC,SAAI,WAAU,aACb,+BAAC,SACC;AAAA,0BAAC,QAAG,WAAU,yCAAwC,6BAAe;AAAA,MACrE,oBAAC,OAAE,WAAU,sCAAqC,yCAAsB;AAAA,OAC1E,GACF;AAAA,EAEJ;AAEA,MAAI,OAAO,OAAO,cAAc,SAAS;AACvC,WACE;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA,SAAS;AAAA,QACT;AAAA;AAAA,IACF;AAAA,EAEJ;AAEA,SACE;AAAA,IAAC;AAAA;AAAA,MACC;AAAA,MACA,SAAS;AAAA,MACT,UAAU,eAAe;AAAA,MACzB;AAAA;AAAA,EACF;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/react/EditMcpSource.tsx"],"sourcesContent":["import { useState } from \"react\";\nimport { useAtomValue, useAtomSet } from \"@effect/atom-react\";\nimport * as AsyncResult from \"effect/unstable/reactivity/AsyncResult\";\nimport * as Exit from \"effect/Exit\";\nimport {\n mcpSourceAtom,\n mcpSourceBindingsAtom,\n setMcpSourceBinding,\n updateMcpSource,\n} from \"./atoms\";\nimport { connectionsAtom } from \"@executor-js/react/api/atoms\";\nimport { useScope, useScopeStack } from \"@executor-js/react/api/scope-context\";\nimport { connectionWriteKeys, sourceWriteKeys } from \"@executor-js/react/api/reactivity-keys\";\nimport { slugifyNamespace, useSourceIdentity } from \"@executor-js/react/plugins/source-identity\";\nimport { useCredentialTargetScope } from \"@executor-js/react/plugins/credential-target-scope\";\nimport { useSecretPickerSecrets } from \"@executor-js/react/plugins/use-secret-picker-secrets\";\nimport {\n HttpCredentialsEditor,\n serializeHttpCredentials,\n serializeScopedHttpCredentials,\n type HttpCredentialsState,\n} from \"@executor-js/react/plugins/http-credentials\";\nimport {\n effectiveCredentialBindingForScope,\n httpCredentialsFromConfiguredCredentialBindings,\n initialCredentialTargetScope,\n} from \"@executor-js/react/plugins/credential-bindings\";\nimport { SourceOAuthConnectionControl } from \"@executor-js/react/plugins/source-oauth-connection\";\nimport { Button } from \"@executor-js/react/components/button\";\nimport { Badge } from \"@executor-js/react/components/badge\";\nimport { ScopeId } from \"@executor-js/sdk/core\";\nimport { McpRemoteSourceFields } from \"./McpRemoteSourceFields\";\nimport {\n McpSourceBindingInput,\n type McpCredentialInput,\n type McpSourceBindingRef,\n} from \"../sdk/types\";\nimport type { McpStoredSourceSchemaType } from \"../sdk/stored-source\";\n\n// ---------------------------------------------------------------------------\n// Remote edit form\n// ---------------------------------------------------------------------------\n\nfunction RemoteEditForm(props: {\n sourceId: string;\n initial: McpStoredSourceSchemaType & { config: { transport: \"remote\" } };\n bindings: readonly McpSourceBindingRef[];\n onSave: () => void;\n}) {\n const displayScope = useScope();\n const scopeStack = useScopeStack();\n const sourceScope = ScopeId.make(props.initial.scope);\n const { credentialTargetScope, credentialScopeOptions } = useCredentialTargetScope({\n sourceScope,\n initialTargetScope: initialCredentialTargetScope(sourceScope, props.bindings),\n });\n const {\n credentialTargetScope: oauthCredentialTargetScope,\n setCredentialTargetScope: setOAuthCredentialTargetScope,\n } = useCredentialTargetScope({\n sourceScope,\n initialTargetScope: initialCredentialTargetScope(sourceScope, props.bindings),\n });\n const doUpdate = useAtomSet(updateMcpSource, { mode: \"promiseExit\" });\n const setBinding = useAtomSet(setMcpSourceBinding, { mode: \"promise\" });\n const secretList = useSecretPickerSecrets();\n const connectionsResult = useAtomValue(connectionsAtom(displayScope));\n\n const identity = useSourceIdentity({\n fallbackName: props.initial.name,\n fallbackNamespace: props.initial.namespace,\n });\n const [endpoint, setEndpoint] = useState(props.initial.config.endpoint);\n const [credentials, setCredentials] = useState<HttpCredentialsState>(() =>\n httpCredentialsFromConfiguredCredentialBindings({\n headers: props.initial.config.headers,\n queryParams: props.initial.config.queryParams,\n bindings: props.bindings,\n }),\n );\n const [saving, setSaving] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [credentialsDirty, setCredentialsDirty] = useState(false);\n\n const identityDirty = identity.name.trim() !== props.initial.name.trim();\n const metadataDirty = identityDirty || endpoint.trim() !== props.initial.config.endpoint.trim();\n const dirty = metadataDirty || credentialsDirty;\n const oauth2 = props.initial.config.auth.kind === \"oauth2\" ? props.initial.config.auth : null;\n const connections = AsyncResult.isSuccess(connectionsResult) ? connectionsResult.value : [];\n const scopeRanks = new Map(scopeStack.map((scope, index) => [scope.id, index] as const));\n const connectionBinding = oauth2\n ? effectiveCredentialBindingForScope(\n props.bindings,\n oauth2.connectionSlot,\n oauthCredentialTargetScope,\n scopeRanks,\n )\n : null;\n const boundConnectionId =\n connectionBinding?.value.kind === \"connection\" ? connectionBinding.value.connectionId : null;\n const isConnected =\n boundConnectionId !== null &&\n connections.some((connection) => connection.id === boundConnectionId);\n const oauthRequestCredentials = serializeHttpCredentials(credentials);\n\n const handleCredentialsChange = (next: HttpCredentialsState) => {\n setCredentials(next);\n setCredentialsDirty(true);\n };\n\n const handleSave = async () => {\n setSaving(true);\n setError(null);\n const { headers, queryParams } = serializeScopedHttpCredentials(\n credentials,\n credentialTargetScope,\n );\n const payload: {\n sourceScope: ScopeId;\n name?: string;\n endpoint?: string;\n headers?: Record<string, McpCredentialInput>;\n queryParams?: Record<string, McpCredentialInput>;\n credentialTargetScope?: ScopeId;\n } = {\n sourceScope,\n name: metadataDirty ? identity.name.trim() || undefined : undefined,\n endpoint: metadataDirty ? endpoint.trim() || undefined : undefined,\n };\n if (credentialsDirty) {\n payload.headers = headers;\n payload.queryParams = queryParams as Record<string, McpCredentialInput>;\n payload.credentialTargetScope = credentialTargetScope;\n }\n const exit = await doUpdate({\n params: { scopeId: displayScope, namespace: props.sourceId },\n payload,\n reactivityKeys: sourceWriteKeys,\n });\n if (Exit.isFailure(exit)) {\n setError(\"Failed to update source\");\n setSaving(false);\n return;\n }\n setCredentialsDirty(false);\n setSaving(false);\n props.onSave();\n };\n\n return (\n <div className=\"space-y-6\">\n <div>\n <h1 className=\"text-xl font-semibold text-foreground\">Edit MCP Source</h1>\n <p className=\"mt-1 text-sm text-muted-foreground\">\n Update the endpoint and headers for this MCP connection.\n </p>\n </div>\n\n <div className=\"flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3\">\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate text-sm font-semibold text-card-foreground\">{props.sourceId}</p>\n </div>\n <Badge variant=\"secondary\" className=\"text-xs\">\n remote\n </Badge>\n </div>\n\n <McpRemoteSourceFields\n url={endpoint}\n onUrlChange={setEndpoint}\n identity={identity}\n preview={{\n name: props.initial.name,\n serverName: props.initial.name,\n connected: true,\n toolCount: null,\n }}\n namespaceReadOnly\n />\n\n <HttpCredentialsEditor\n credentials={credentials}\n onChange={handleCredentialsChange}\n existingSecrets={secretList}\n sourceName={identity.name}\n targetScope={credentialTargetScope}\n credentialScopeOptions={credentialScopeOptions}\n bindingScopeOptions={credentialScopeOptions}\n />\n\n {oauth2 && (\n <SourceOAuthConnectionControl\n popupName=\"mcp-oauth\"\n pluginId=\"mcp\"\n namespace={slugifyNamespace(props.initial.namespace) || \"mcp\"}\n fallbackNamespace=\"mcp\"\n endpoint={endpoint.trim()}\n tokenScope={oauthCredentialTargetScope}\n onTokenScopeChange={setOAuthCredentialTargetScope}\n credentialScopeOptions={credentialScopeOptions}\n connectionId={boundConnectionId}\n sourceLabel={`${identity.name.trim() || props.initial.namespace || \"MCP\"} OAuth`}\n headers={oauthRequestCredentials.headers}\n queryParams={oauthRequestCredentials.queryParams}\n isConnected={isConnected}\n onConnected={async (connectionId) => {\n await setBinding({\n params: { scopeId: oauthCredentialTargetScope },\n payload: McpSourceBindingInput.make({\n sourceId: props.sourceId,\n sourceScope,\n scope: oauthCredentialTargetScope,\n slot: oauth2.connectionSlot,\n value: { kind: \"connection\", connectionId },\n }),\n reactivityKeys: [...sourceWriteKeys, ...connectionWriteKeys],\n });\n }}\n reconnectingLabel=\"Reconnecting…\"\n signingInLabel=\"Signing in…\"\n />\n )}\n\n {error && (\n <div className=\"rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2\">\n <p className=\"text-sm text-destructive\">{error}</p>\n </div>\n )}\n\n <div className=\"flex items-center justify-between border-t border-border pt-4\">\n <Button variant=\"ghost\" onClick={props.onSave}>\n Cancel\n </Button>\n <Button onClick={handleSave} disabled={!dirty || saving}>\n {saving ? \"Saving…\" : \"Save changes\"}\n </Button>\n </div>\n </div>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Stdio read-only view\n// ---------------------------------------------------------------------------\n\nfunction StdioReadOnly(props: {\n sourceId: string;\n initial: McpStoredSourceSchemaType & { config: { transport: \"stdio\" } };\n onSave: () => void;\n}) {\n const { command, args } = props.initial.config;\n return (\n <div className=\"space-y-6\">\n <div>\n <h1 className=\"text-xl font-semibold text-foreground\">Edit MCP Source</h1>\n <p className=\"mt-1 text-sm text-muted-foreground\">\n Stdio MCP sources cannot be edited in the UI. Remove and recreate the source with the\n updated command.\n </p>\n </div>\n\n <div className=\"flex items-center gap-3 rounded-lg border border-border bg-card px-4 py-3\">\n <div className=\"min-w-0 flex-1\">\n <p className=\"truncate text-sm font-semibold text-card-foreground\">{props.sourceId}</p>\n <p className=\"mt-0.5 text-xs text-muted-foreground font-mono\">\n {command} {(args ?? []).join(\" \")}\n </p>\n </div>\n <Badge variant=\"secondary\" className=\"text-xs\">\n stdio\n </Badge>\n </div>\n\n <div className=\"flex items-center justify-end border-t border-border pt-4\">\n <Button onClick={props.onSave}>Done</Button>\n </div>\n </div>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Main component\n// ---------------------------------------------------------------------------\n\nexport default function EditMcpSource({\n sourceId,\n onSave,\n}: {\n readonly sourceId: string;\n readonly onSave: () => void;\n}) {\n const scopeId = useScope();\n const sourceResult = useAtomValue(mcpSourceAtom(scopeId, sourceId)) as AsyncResult.AsyncResult<\n McpStoredSourceSchemaType | null,\n unknown\n >;\n const source =\n AsyncResult.isSuccess(sourceResult) && sourceResult.value ? sourceResult.value : null;\n const sourceScope = source ? ScopeId.make(source.scope) : scopeId;\n const bindingsResult = useAtomValue(mcpSourceBindingsAtom(scopeId, sourceId, sourceScope));\n\n if (!AsyncResult.isSuccess(sourceResult) || !source || !AsyncResult.isSuccess(bindingsResult)) {\n return (\n <div className=\"space-y-6\">\n <div>\n <h1 className=\"text-xl font-semibold text-foreground\">Edit MCP Source</h1>\n <p className=\"mt-1 text-sm text-muted-foreground\">Loading configuration…</p>\n </div>\n </div>\n );\n }\n\n if (source.config.transport === \"stdio\") {\n return (\n <StdioReadOnly\n sourceId={sourceId}\n initial={source as McpStoredSourceSchemaType & { config: { transport: \"stdio\" } }}\n onSave={onSave}\n />\n );\n }\n\n return (\n <RemoteEditForm\n sourceId={sourceId}\n initial={source as McpStoredSourceSchemaType & { config: { transport: \"remote\" } }}\n bindings={bindingsResult.value}\n onSave={onSave}\n />\n );\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,gBAAgB;AACzB,SAAS,cAAc,kBAAkB;AACzC,YAAY,iBAAiB;AAC7B,YAAY,UAAU;AAOtB,SAAS,uBAAuB;AAChC,SAAS,UAAU,qBAAqB;AACxC,SAAS,qBAAqB,uBAAuB;AACrD,SAAS,kBAAkB,yBAAyB;AACpD,SAAS,gCAAgC;AACzC,SAAS,8B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,OAAE,WAAU,kDACV;AAAA;AAAA,UAAQ;AAAA,WAAG,QAAQ,CAAC,GAAG,KAAK,GAAG;AAAA,WAClC;AAAA,SACF;AAAA,MACA,oBAAC,SAAM,SAAQ,aAAY,WAAU,WAAU,mBAE/C;AAAA,OACF;AAAA,IAEA,oBAAC,SAAI,WAAU,6DACb,8BAAC,UAAO,SAAS,MAAM,QAAQ,kBAAI,GACrC;AAAA,KACF;AAEJ;AAMe,SAAR,cAA+B;AAAA,EACpC;AAAA,EACA;AACF,GAGG;AACD,QAAM,UAAU,SAAS;AACzB,QAAM,eAAe,aAAa,cAAc,SAAS,QAAQ,CAAC;AAIlE,QAAM,SACQ,sBAAU,YAAY,KAAK,aAAa,QAAQ,aAAa,QAAQ;AACnF,QAAM,cAAc,SAAS,QAAQ,KAAK,OAAO,KAAK,IAAI;AAC1D,QAAM,iBAAiB,aAAa,sBAAsB,SAAS,UAAU,WAAW,CAAC;AAEzF,MAAI,CAAa,sBAAU,YAAY,KAAK,CAAC,UAAU,CAAa,sBAAU,cAAc,GAAG;AAC7F,WACE,oBAAC,SAAI,WAAU,aACb,+BAAC,SACC;AAAA,0BAAC,QAAG,WAAU,yCAAwC,6BAAe;AAAA,MACrE,oBAAC,OAAE,WAAU,sCAAqC,yCAAsB;AAAA,OAC1E,GACF;AAAA,EAEJ;AAEA,MAAI,OAAO,OAAO,cAAc,SAAS;AACvC,WACE;AAAA,MAAC;AAAA;AAAA,QACC;AAAA,QACA,SAAS;AAAA,QACT;AAAA;AAAA,IACF;AAAA,EAEJ;AAEA,SACE;AAAA,IAAC;AAAA;AAAA,MACC;AAAA,MACA,SAAS;AAAA,MACT,UAAU,eAAe;AAAA,MACzB;AAAA;AAAA,EACF;AAEJ;","names":[]}
@@ -808,6 +808,41 @@ var isOAuthErrorBody = (body) => {
808
808
  if (Array.isArray(obj.errors)) return false;
809
809
  return typeof obj.error === "string";
810
810
  };
811
+ var ProtectedResourceMetadata = Schema4.Struct({
812
+ resource: Schema4.String,
813
+ authorization_servers: Schema4.Array(Schema4.String)
814
+ });
815
+ var decodeProtectedResourceMetadata = Schema4.decodeUnknownOption(
816
+ Schema4.fromJsonString(ProtectedResourceMetadata)
817
+ );
818
+ var protectedResourceMetadataUrl = (endpoint) => {
819
+ const path = endpoint.pathname === "/" ? "" : endpoint.pathname;
820
+ return `${endpoint.origin}/.well-known/oauth-protected-resource${path}`;
821
+ };
822
+ var resourceMatchesEndpoint = (resource, endpoint) => {
823
+ if (!URL.canParse(resource)) return false;
824
+ const parsed = new URL(resource);
825
+ if (parsed.origin !== endpoint.origin) return false;
826
+ const resourcePath = parsed.pathname.replace(/\/+$/, "");
827
+ const endpointPath = endpoint.pathname.replace(/\/+$/, "");
828
+ return endpointPath === resourcePath || endpointPath.startsWith(`${resourcePath}/`);
829
+ };
830
+ var probeProtectedResourceMetadata = (client, endpoint, timeoutMs) => Effect5.gen(function* () {
831
+ const response = yield* client.execute(
832
+ HttpClientRequest.get(protectedResourceMetadataUrl(endpoint)).pipe(
833
+ HttpClientRequest.setHeader("accept", "application/json")
834
+ )
835
+ ).pipe(Effect5.timeout(Duration.millis(timeoutMs)));
836
+ if (response.status < 200 || response.status >= 300) return false;
837
+ const body = yield* response.text.pipe(
838
+ Effect5.timeout(Duration.millis(timeoutMs)),
839
+ Effect5.catch(() => Effect5.succeed(""))
840
+ );
841
+ const metadata = decodeProtectedResourceMetadata(body);
842
+ if (Option4.isNone(metadata)) return false;
843
+ if (metadata.value.authorization_servers.length === 0) return false;
844
+ return resourceMatchesEndpoint(metadata.value.resource, endpoint);
845
+ }).pipe(Effect5.catch(() => Effect5.succeed(false)));
811
846
  var ErrorMessageShape = Schema4.Struct({ message: Schema4.String });
812
847
  var decodeErrorMessageShape = Schema4.decodeUnknownOption(ErrorMessageShape);
813
848
  var reasonFromBoundaryCause = (cause) => {
@@ -836,6 +871,9 @@ var probeMcpEndpointShape = (endpoint, options = {}) => Effect5.gen(function* ()
836
871
  if (response.status === 401) {
837
872
  const wwwAuth = readHeader(response.headers, "www-authenticate");
838
873
  if (!wwwAuth || !/^\s*bearer\b/i.test(wwwAuth)) {
874
+ if (yield* probeProtectedResourceMetadata(client, url, timeoutMs)) {
875
+ return { kind: "mcp", requiresAuth: true };
876
+ }
839
877
  return {
840
878
  kind: "not-mcp",
841
879
  category: "auth-required",
@@ -851,6 +889,9 @@ var probeMcpEndpointShape = (endpoint, options = {}) => Effect5.gen(function* ()
851
889
  if (isSse) return { kind: "mcp", requiresAuth: true };
852
890
  const body = yield* readBody(response);
853
891
  if (!isJsonRpcEnvelope(body) && !isOAuthErrorBody(body)) {
892
+ if (yield* probeProtectedResourceMetadata(client, url, timeoutMs)) {
893
+ return { kind: "mcp", requiresAuth: true };
894
+ }
854
895
  return {
855
896
  kind: "not-mcp",
856
897
  category: "auth-required",
@@ -2274,4 +2315,4 @@ export {
2274
2315
  makeMcpStore,
2275
2316
  mcpPlugin
2276
2317
  };
2277
- //# sourceMappingURL=chunk-NQT7NAGE.js.map
2318
+ //# sourceMappingURL=chunk-2DOCEPYN.js.map
@@ -1 +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":["// ---------------------------------------------------------------------------\n// MCP plugin storage — four tables:\n// - mcp_source: per-source structural data (transport, endpoint,\n// stdio command/args/env, etc.) plus the auth flattened into\n// columns so source-owned credential slots are queryable. The non-ref\n// structural data still lives in `config` as JSON because it's\n// plugin-private and varies by transport (`remote` vs `stdio`\n// have different shapes).\n// - mcp_source_header / mcp_source_query_param: child tables for\n// remote sources' headers and query_params SecretBackedMap entries.\n// - mcp_binding: per-tool McpToolBinding (toolId/toolName/description/\n// input+output schemas/annotations). Stays JSON: it carries no\n// refs, and `inputSchema` / `outputSchema` are arbitrary\n// user-supplied JSON Schemas — a legitimate JSON case.\n// OAuth session storage lives at the core level in `oauth2_session`\n// and is owned by `ctx.oauth`.\n// ---------------------------------------------------------------------------\n\nimport { Effect, Option, Schema } from \"effect\";\n\nimport {\n ConfiguredCredentialBinding,\n defineSchema,\n type StorageDeps,\n type StorageFailure,\n} from \"@executor-js/sdk/core\";\n\nimport {\n McpToolBinding,\n McpStoredSourceData,\n type McpConnectionAuth,\n type ConfiguredMcpCredentialValue,\n} 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 // Plugin-private structural data minus the ref-bearing fields\n // (auth, headers, queryParams). For remote sources: transport,\n // endpoint, remoteTransport. For stdio: transport, command,\n // args, env, cwd.\n config: { type: \"json\", required: true },\n // Flattened McpConnectionAuth. The stored source only names slots;\n // concrete per-user/per-workspace values live in core credential_binding.\n auth_kind: {\n type: [\"none\", \"header\", \"oauth2\"],\n required: true,\n defaultValue: \"none\",\n },\n // Header-auth fields.\n auth_header_name: { type: \"string\", required: false },\n auth_header_slot: { type: \"string\", required: false },\n auth_header_prefix: { type: \"string\", required: false },\n // OAuth2 auth fields.\n auth_connection_slot: { type: \"string\", required: false },\n auth_client_id_slot: {\n type: \"string\",\n required: false,\n },\n auth_client_secret_slot: {\n type: \"string\",\n required: false,\n },\n created_at: { type: \"date\", required: true },\n },\n },\n mcp_source_header: {\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 name: { type: \"string\", required: true },\n kind: { type: [\"text\", \"binding\"], required: true },\n text_value: { type: \"string\", required: false },\n slot_key: { type: \"string\", required: false },\n prefix: { type: \"string\", required: false },\n },\n },\n mcp_source_query_param: {\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 name: { type: \"string\", required: true },\n kind: { type: [\"text\", \"binding\"], required: true },\n text_value: { type: \"string\", required: false },\n slot_key: { type: \"string\", required: false },\n prefix: { type: \"string\", required: false },\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);\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\n// --- auth column packing/unpacking ------------------------------------------\n\ninterface AuthColumns {\n readonly auth_kind: \"none\" | \"header\" | \"oauth2\";\n readonly auth_header_name?: string;\n readonly auth_header_slot?: string;\n readonly auth_header_prefix?: string;\n readonly auth_connection_slot?: string;\n readonly auth_client_id_slot?: string;\n readonly auth_client_secret_slot?: string;\n}\n\nconst authToColumns = (auth: McpConnectionAuth): AuthColumns => {\n if (auth.kind === \"header\") {\n return {\n auth_kind: \"header\",\n auth_header_name: auth.headerName,\n auth_header_slot: auth.secretSlot,\n auth_header_prefix: auth.prefix,\n };\n }\n if (auth.kind === \"oauth2\") {\n return {\n auth_kind: \"oauth2\",\n auth_connection_slot: auth.connectionSlot,\n auth_client_id_slot: auth.clientIdSlot,\n auth_client_secret_slot: auth.clientSecretSlot,\n };\n }\n return { auth_kind: \"none\" };\n};\n\nconst columnsToAuth = (row: Record<string, unknown>): McpConnectionAuth => {\n const kind = row.auth_kind;\n if (kind === \"header\" && typeof row.auth_header_slot === \"string\") {\n const prefix = row.auth_header_prefix as string | null | undefined;\n return {\n kind: \"header\",\n headerName: (row.auth_header_name as string | null) ?? \"\",\n secretSlot: row.auth_header_slot,\n ...(prefix ? { prefix } : {}),\n };\n }\n if (kind === \"oauth2\" && typeof row.auth_connection_slot === \"string\") {\n const cid = row.auth_client_id_slot as string | null | undefined;\n const csec = row.auth_client_secret_slot as string | null | undefined;\n return {\n kind: \"oauth2\",\n connectionSlot: row.auth_connection_slot,\n ...(cid ? { clientIdSlot: cid } : {}),\n ...(csec ? { clientSecretSlot: csec } : {}),\n };\n }\n return { kind: \"none\" };\n};\n\n// --- ConfiguredCredentialValue map <-> child rows ---------------------------\n\ninterface ConfiguredCredentialRow {\n readonly id: string;\n readonly scope_id: string;\n readonly source_id: string;\n readonly name: string;\n readonly kind: \"text\" | \"binding\";\n readonly text_value?: string;\n readonly slot_key?: string;\n readonly prefix?: string;\n readonly [k: string]: unknown;\n}\n\nconst valueMapToRows = (\n sourceId: string,\n scope: string,\n values: Record<string, ConfiguredMcpCredentialValue> | undefined,\n): readonly ConfiguredCredentialRow[] => {\n if (!values) return [];\n return Object.entries(values).map(([name, value]) => {\n const id = JSON.stringify([sourceId, name]);\n if (typeof value === \"string\") {\n return {\n id,\n scope_id: scope,\n source_id: sourceId,\n name,\n kind: \"text\",\n text_value: value,\n };\n }\n return {\n id,\n scope_id: scope,\n source_id: sourceId,\n name,\n kind: \"binding\",\n slot_key: value.slot,\n prefix: value.prefix,\n };\n });\n};\n\nconst rowsToValueMap = (\n rows: readonly Record<string, unknown>[],\n): Record<string, ConfiguredMcpCredentialValue> => {\n const out: Record<string, ConfiguredMcpCredentialValue> = {};\n for (const row of rows) {\n if (typeof row.name !== \"string\") continue;\n const name = row.name;\n if (row.kind === \"binding\" && typeof row.slot_key === \"string\") {\n const prefix = row.prefix as string | undefined | null;\n out[name] = prefix\n ? ConfiguredCredentialBinding.make({ kind: \"binding\", slot: row.slot_key, prefix })\n : ConfiguredCredentialBinding.make({ kind: \"binding\", slot: row.slot_key });\n } else if (row.kind === \"text\" && typeof row.text_value === \"string\") {\n out[name] = row.text_value;\n }\n }\n return out;\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<{\n readonly toolId: string;\n readonly binding: McpToolBinding;\n }>,\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<{\n readonly toolId: string;\n readonly binding: McpToolBinding;\n }>,\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: (namespace: string, scope: string) => Effect.Effect<void, StorageFailure>;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nexport const makeMcpStore = ({ adapter: db }: 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: yield* hydrateSourceData(row, namespace, scope),\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 yield* hydrateSourceData(row, namespace, scope);\n }),\n\n putSource: (source) =>\n Effect.gen(function* () {\n const now = new Date();\n // Drop the source row and its child rows; recreate. Two-step\n // matches the existing put-overwrites-existing semantic.\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* deleteSourceChildren(source.namespace, source.scope);\n\n const auth: McpConnectionAuth =\n source.config.transport === \"remote\" ? source.config.auth : { kind: \"none\" };\n const authCols = authToColumns(auth);\n const headers = source.config.transport === \"remote\" ? source.config.headers : undefined;\n const queryParams =\n source.config.transport === \"remote\" ? source.config.queryParams : undefined;\n\n // The encoded config keeps every plugin-private field but\n // strips auth/headers/queryParams — those moved to columns/\n // child tables. We round-trip through encodeSourceData so the\n // remaining fields stay in the same JSON shape decode expects.\n const encodedConfig = stripExtractedFields(\n encodeSourceData(source.config) as Record<string, unknown>,\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: encodedConfig,\n created_at: now,\n ...authCols,\n },\n forceAllowId: true,\n });\n\n const headerRows = valueMapToRows(source.namespace, source.scope, headers);\n if (headerRows.length > 0) {\n yield* db.createMany({\n model: \"mcp_source_header\",\n data: headerRows,\n forceAllowId: true,\n });\n }\n const paramRows = valueMapToRows(source.namespace, source.scope, queryParams);\n if (paramRows.length > 0) {\n yield* db.createMany({\n model: \"mcp_source_query_param\",\n data: paramRows,\n forceAllowId: true,\n });\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* deleteSourceChildren(namespace, scope);\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 // ---------------------------------------------------------------------\n // Private helpers — depend on `db` so they live inside the closure.\n // ---------------------------------------------------------------------\n\n function deleteSourceChildren(namespace: string, scope: string) {\n return Effect.gen(function* () {\n for (const model of [\"mcp_source_header\", \"mcp_source_query_param\"] as const) {\n yield* db.deleteMany({\n model,\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n }\n });\n }\n\n function hydrateSourceData(\n row: Record<string, unknown>,\n namespace: string,\n scope: string,\n ): Effect.Effect<McpStoredSourceData, StorageFailure> {\n return Effect.gen(function* () {\n // The stored JSON has auth/headers/queryParams stripped (those\n // moved to columns / child tables). We must rehydrate the full\n // shape BEFORE handing it to the schema decoder, because\n // `McpRemoteSourceData.auth` is required.\n const partial = coerceJson(row.config) as Record<string, unknown>;\n if (partial.transport !== \"remote\") {\n // stdio sources have no extracted fields — decode as-is.\n return decodeSourceData(partial);\n }\n const headerRows = yield* db.findMany({\n model: \"mcp_source_header\",\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n const paramRows = yield* db.findMany({\n model: \"mcp_source_query_param\",\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n const headers = rowsToValueMap(headerRows);\n const queryParams = rowsToValueMap(paramRows);\n const reassembled = {\n ...partial,\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n ...(Object.keys(queryParams).length > 0 ? { queryParams } : {}),\n auth: columnsToAuth(row),\n };\n return decodeSourceData(reassembled);\n });\n }\n};\n\n// Strip auth/headers/queryParams from the encoded source-data shape.\n// Keeps the remaining structural fields (transport, endpoint, etc.) in\n// the JSON config column. Per-transport: only the remote variant has\n// these fields, so this is a no-op for stdio.\nconst stripExtractedFields = (encoded: Record<string, unknown>): Record<string, unknown> => {\n if (encoded.transport !== \"remote\") return encoded;\n const { auth, headers, queryParams, ...rest } = encoded;\n void auth;\n void headers;\n void queryParams;\n return rest;\n};\n","import {\n Duration,\n Effect,\n Exit,\n Layer,\n Match,\n Option,\n Predicate,\n Result,\n Scope,\n ScopedCache,\n} from \"effect\";\nimport type { HttpClient } from \"effect/unstable/http\";\n\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\n\nimport {\n ConfiguredCredentialBinding,\n ConnectionId,\n type CredentialBindingRef,\n type CredentialBindingValue,\n ScopeId,\n SecretId,\n SourceDetectionResult,\n definePlugin,\n resolveSecretBackedMap as resolveSharedSecretBackedMap,\n type PluginCtx,\n type StorageFailure,\n StorageError,\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, McpInvocationError, McpToolDiscoveryError } from \"./errors\";\nimport { invokeMcpTool } from \"./invoke\";\nimport { deriveMcpNamespace, type McpToolManifest, type McpToolManifestEntry } from \"./manifest\";\nimport { probeMcpEndpointShape, type McpShapeProbeResult } from \"./probe-shape\";\nimport {\n MCP_HEADER_AUTH_SLOT,\n MCP_OAUTH_CLIENT_ID_SLOT,\n MCP_OAUTH_CLIENT_SECRET_SLOT,\n MCP_OAUTH_CONNECTION_SLOT,\n McpToolBinding,\n McpSourceBindingInput,\n McpSourceBindingRef,\n mcpHeaderSlot,\n mcpQueryParamSlot,\n type McpConnectionAuth,\n type McpConnectionAuthInput,\n type McpCredentialInput,\n type McpSourceBindingValue,\n type SecretBackedValue,\n type McpStoredSourceData,\n type ConfiguredMcpCredentialValue,\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, McpCredentialInput>;\n readonly headers?: Record<string, McpCredentialInput>;\n readonly namespace?: string;\n readonly auth?: McpConnectionAuthInput;\n /**\n * Scope that owns any direct credentials supplied on this call. Required\n * whenever headers/queryParams/auth carry direct secret or connection ids.\n */\n readonly credentialTargetScope?: string;\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 supportsDynamicRegistration: 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, McpCredentialInput>;\n readonly queryParams?: Record<string, McpCredentialInput>;\n readonly credentialTargetScope?: string;\n readonly auth?: McpConnectionAuthInput;\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 = (\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\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\";\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 coreBindingToMcpBinding = (binding: CredentialBindingRef): McpSourceBindingRef =>\n McpSourceBindingRef.make({\n sourceId: binding.sourceId,\n sourceScopeId: binding.sourceScopeId,\n scopeId: binding.scopeId,\n slot: binding.slotKey,\n value: binding.value,\n createdAt: binding.createdAt,\n updatedAt: binding.updatedAt,\n });\n\nconst listMcpSourceBindings = (\n ctx: PluginCtx<McpBindingStore>,\n sourceId: string,\n sourceScope: string,\n): Effect.Effect<readonly McpSourceBindingRef[], StorageFailure> =>\n Effect.gen(function* () {\n const ranks = scopeRanks(ctx);\n const sourceSourceRank = scopeRank(ranks, sourceScope);\n if (sourceSourceRank === Infinity) return [];\n const bindings = yield* ctx.credentialBindings.listForSource({\n pluginId: MCP_PLUGIN_ID,\n sourceId,\n sourceScope: ScopeId.make(sourceScope),\n });\n return bindings\n .filter((binding) => scopeRank(ranks, binding.scopeId) <= sourceSourceRank)\n .map(coreBindingToMcpBinding);\n });\n\nconst resolveMcpSourceBinding = (\n ctx: PluginCtx<McpBindingStore>,\n sourceId: string,\n sourceScope: string,\n slot: string,\n): Effect.Effect<McpSourceBindingRef | 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 ? coreBindingToMcpBinding(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 bindingTargetScope = (\n targetScope: string | undefined,\n bindings: readonly unknown[],\n): Effect.Effect<string | undefined, McpConnectionError> => {\n if (bindings.length === 0) return Effect.succeed(undefined);\n if (targetScope) return Effect.succeed(targetScope);\n return Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: \"credentialTargetScope is required when adding direct MCP credentials\",\n }),\n );\n};\n\nconst targetScopeForBinding = (\n fallbackTargetScope: string | undefined,\n binding: { readonly targetScope?: string },\n): Effect.Effect<string, McpConnectionError> => {\n const targetScope = binding.targetScope ?? fallbackTargetScope;\n if (targetScope) return Effect.succeed(targetScope);\n return Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: \"credentialTargetScope is required when adding direct MCP credentials\",\n }),\n );\n};\n\nconst canonicalizeCredentialMap = (\n values: Record<string, McpCredentialInput> | undefined,\n slotForName: (name: string) => string,\n): {\n readonly values: Record<string, ConfiguredMcpCredentialValue>;\n readonly bindings: ReadonlyArray<{\n readonly slot: string;\n readonly value: McpSourceBindingValue;\n readonly targetScope?: string;\n }>;\n} => {\n const nextValues: Record<string, ConfiguredMcpCredentialValue> = {};\n const bindings: Array<{ slot: string; value: McpSourceBindingValue; targetScope?: string }> = [];\n for (const [name, value] of Object.entries(values ?? {})) {\n if (typeof value === \"string\") {\n nextValues[name] = value;\n continue;\n }\n if (\"kind\" in value) {\n nextValues[name] = value;\n continue;\n }\n const slot = slotForName(name);\n nextValues[name] = ConfiguredCredentialBinding.make({\n kind: \"binding\",\n slot,\n prefix: value.prefix,\n });\n bindings.push({\n slot,\n targetScope: \"targetScope\" in value ? value.targetScope : undefined,\n value: {\n kind: \"secret\",\n secretId: SecretId.make(value.secretId),\n ...(\"secretScopeId\" in value && value.secretScopeId\n ? { secretScopeId: value.secretScopeId }\n : {}),\n },\n });\n }\n return { values: nextValues, bindings };\n};\n\nconst canonicalizeAuth = (\n auth: McpConnectionAuthInput | undefined,\n): {\n readonly auth: McpConnectionAuth;\n readonly bindings: ReadonlyArray<{\n readonly slot: string;\n readonly value: McpSourceBindingValue;\n readonly targetScope?: string;\n }>;\n} => {\n if (!auth || auth.kind === \"none\") return { auth: { kind: \"none\" }, bindings: [] };\n if (auth.kind === \"header\") {\n if (\"secretSlot\" in auth) return { auth, bindings: [] };\n return {\n auth: {\n kind: \"header\",\n headerName: auth.headerName,\n secretSlot: MCP_HEADER_AUTH_SLOT,\n prefix: auth.prefix,\n },\n bindings: [\n {\n slot: MCP_HEADER_AUTH_SLOT,\n targetScope: auth.targetScope,\n value: {\n kind: \"secret\",\n secretId: SecretId.make(auth.secretId),\n ...(auth.secretScopeId ? { secretScopeId: auth.secretScopeId } : {}),\n },\n },\n ],\n };\n }\n if (\"connectionSlot\" in auth) return { auth, bindings: [] };\n const bindings: Array<{ slot: string; value: McpSourceBindingValue; targetScope?: string }> = [\n {\n slot: MCP_OAUTH_CONNECTION_SLOT,\n value: {\n kind: \"connection\",\n connectionId: ConnectionId.make(auth.connectionId),\n },\n },\n ];\n if (auth.clientIdSecretId) {\n bindings.push({\n slot: MCP_OAUTH_CLIENT_ID_SLOT,\n value: { kind: \"secret\", secretId: SecretId.make(auth.clientIdSecretId) },\n });\n }\n if (auth.clientSecretSecretId) {\n bindings.push({\n slot: MCP_OAUTH_CLIENT_SECRET_SLOT,\n value: { kind: \"secret\", secretId: SecretId.make(auth.clientSecretSecretId) },\n });\n }\n return {\n auth: {\n kind: \"oauth2\",\n connectionSlot: MCP_OAUTH_CONNECTION_SLOT,\n ...(auth.clientIdSecretId ? { clientIdSlot: MCP_OAUTH_CLIENT_ID_SLOT } : {}),\n ...(auth.clientSecretSecretId ? { 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 plainStringMap = (\n values: Record<string, McpCredentialInput> | 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\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, McpConnectionError | 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 secret = yield* ctx.secrets.getAtScope(binding.value.secretId, binding.scopeId).pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () =>\n Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve secret for ${params.missingLabel} \"${name}\"`,\n }),\n ),\n ),\n );\n if (secret === null) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: `Missing secret \"${binding.value.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 McpConnectionError({\n transport: \"remote\",\n message: `Missing binding for ${params.missingLabel} \"${name}\"`,\n });\n }\n return Object.keys(resolved).length > 0 ? resolved : undefined;\n });\n\nconst resolveMcpCredentialInputMap = (\n ctx: PluginCtx<McpBindingStore>,\n values: Record<string, McpCredentialInput> | 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, McpConnectionError | 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 if (\"kind\" in value) {\n const slotResolved = yield* resolveMcpBindingValueMap(\n ctx,\n { [name]: value },\n {\n sourceId: params.sourceId,\n sourceScope: params.sourceScope,\n missingLabel: params.missingLabel,\n },\n );\n if (slotResolved?.[name] !== undefined) resolved[name] = slotResolved[name];\n continue;\n }\n const secretScope =\n \"secretScopeId\" in value\n ? (value.secretScopeId ?? value.targetScope)\n : (params.targetScope ?? params.sourceScope);\n const secret = yield* ctx.secrets.getAtScope(SecretId.make(value.secretId), secretScope).pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () =>\n Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve secret for ${params.missingLabel} \"${name}\"`,\n }),\n ),\n ),\n );\n if (secret === null) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: `Missing secret \"${value.secretId}\" for ${params.missingLabel} \"${name}\"`,\n });\n }\n resolved[name] = value.prefix ? `${value.prefix}${secret}` : secret;\n }\n return Object.keys(resolved).length > 0 ? resolved : undefined;\n });\n\nconst resolveMcpHeaderAuth = (\n ctx: PluginCtx<McpBindingStore>,\n sourceId: string,\n sourceScope: string,\n auth: McpConnectionAuth,\n): Effect.Effect<Record<string, string>, McpConnectionError | 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 secret = yield* ctx.secrets.getAtScope(binding.value.secretId, binding.scopeId).pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () =>\n Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve header auth binding \"${auth.secretSlot}\"`,\n }),\n ),\n ),\n );\n if (secret === null) {\n return yield* new McpConnectionError({\n transport: \"remote\",\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 McpConnectionError({\n transport: \"remote\",\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, McpConnectionError | 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 McpConnectionError({\n transport: \"remote\",\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.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 resolveMcpInputAuth = (\n ctx: PluginCtx<McpBindingStore>,\n sourceId: string,\n sourceScope: string,\n targetScope: string | undefined,\n auth: McpConnectionAuthInput | undefined,\n): Effect.Effect<\n { readonly headers: Record<string, string>; readonly authProvider?: OAuthClientProvider },\n McpConnectionError | StorageFailure\n> =>\n Effect.gen(function* () {\n if (!auth || auth.kind === \"none\") return { headers: {} };\n if (auth.kind === \"header\") {\n if (\"secretSlot\" in auth) {\n const headers = yield* resolveMcpHeaderAuth(ctx, sourceId, sourceScope, auth);\n return { headers };\n }\n const secretScope = auth.secretScopeId ?? auth.targetScope ?? targetScope ?? sourceScope;\n const secret = yield* ctx.secrets.getAtScope(SecretId.make(auth.secretId), secretScope).pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () =>\n Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve secret \"${auth.secretId}\"`,\n }),\n ),\n ),\n );\n if (secret === null) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve secret \"${auth.secretId}\"`,\n });\n }\n return {\n headers: { [auth.headerName]: auth.prefix ? `${auth.prefix}${secret}` : secret },\n };\n }\n const connection =\n \"connectionId\" in auth\n ? { id: ConnectionId.make(auth.connectionId), scope: targetScope ?? sourceScope }\n : yield* Effect.gen(function* () {\n const binding = yield* resolveMcpSourceBinding(\n ctx,\n sourceId,\n sourceScope,\n auth.connectionSlot,\n );\n return binding?.value.kind === \"connection\"\n ? { id: binding.value.connectionId, scope: binding.scopeId }\n : null;\n });\n if (connection === null) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: `Missing OAuth connection binding for MCP source \"${sourceId}\"`,\n });\n }\n const accessToken = yield* ctx.connections\n .accessTokenAtScope(connection.id, connection.scope)\n .pipe(\n Effect.mapError(\n ({ message }) =>\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve OAuth connection \"${connection.id}\": ${message}`,\n }),\n ),\n );\n return { headers: {}, authProvider: 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, 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<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) =>\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 secretRef = (id: string): string => `${SECRET_REF_PREFIX}${id}`;\n\nconst authToConfig = (auth: McpConnectionAuthInput | undefined): McpAuthConfig | undefined => {\n if (!auth) return undefined;\n if (auth.kind === \"none\") return { kind: \"none\" };\n if (auth.kind === \"header\") {\n if (!(\"secretId\" in auth)) return undefined;\n return {\n kind: \"header\",\n headerName: auth.headerName,\n secret: secretRef(auth.secretId),\n prefix: auth.prefix,\n };\n }\n if (!(\"connectionId\" in auth)) return undefined;\n return {\n kind: \"oauth2\",\n connectionId: auth.connectionId,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Storage-form → input-form reconstruction\n//\n// `toMcpConfigEntry` consumes the `McpSourceConfig` *input* shape — the\n// legacy form with `secretId` / `connectionId`, which `authToConfig` and\n// `plainStringMap` 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 secretId: value.secretId,\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: \"header\",\n headerName: auth.headerName,\n secretId: value.secretId,\n prefix: auth.prefix,\n };\n }\n const connection = bySlot.get(auth.connectionSlot);\n if (connection?.kind !== \"connection\") return undefined;\n return { kind: \"oauth2\", connectionId: connection.connectionId };\n};\n\nconst inputFormFromStored = (\n bindings: ReadonlyArray<CredentialBindingRef>,\n stored: McpStoredSourceData,\n scope: string,\n sourceName: string,\n namespace: string,\n): McpSourceConfig => {\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: 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 // 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: canonicalizeCredentialMap(config.headers, mcpHeaderSlot),\n queryParams: canonicalizeCredentialMap(config.queryParams, mcpQueryParamSlot),\n auth: canonicalizeAuth(config.auth),\n }\n : null;\n const directBindings = canonicalRemote\n ? [\n ...canonicalRemote.headers.bindings,\n ...canonicalRemote.queryParams.bindings,\n ...canonicalRemote.auth.bindings,\n ]\n : [];\n for (const binding of directBindings) {\n const bindingTargetScope = yield* targetScopeForBinding(\n config.transport === \"remote\" ? config.credentialTargetScope : undefined,\n binding,\n );\n yield* validateMcpBindingTarget(ctx, {\n sourceId: namespace,\n sourceScope: config.scope,\n targetScope: bindingTargetScope,\n });\n }\n const targetScope =\n config.transport === \"remote\" && directBindings[0]\n ? yield* targetScopeForBinding(config.credentialTargetScope, directBindings[0])\n : undefined;\n const sd = toStoredSourceData(\n config,\n canonicalRemote\n ? {\n headers: canonicalRemote.headers.values,\n queryParams: canonicalRemote.queryParams.values,\n auth: canonicalRemote.auth.auth,\n }\n : undefined,\n );\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* (\n config.transport === \"remote\"\n ? Effect.gen(function* () {\n const resolvedHeaders = yield* resolveMcpCredentialInputMap(ctx, config.headers, {\n sourceId: namespace,\n sourceScope: config.scope,\n targetScope,\n missingLabel: \"header\",\n });\n const resolvedQueryParams = yield* resolveMcpCredentialInputMap(\n ctx,\n config.queryParams,\n {\n sourceId: namespace,\n sourceScope: config.scope,\n targetScope,\n missingLabel: \"query parameter\",\n },\n );\n const resolvedAuth = yield* resolveMcpInputAuth(\n ctx,\n namespace,\n config.scope,\n targetScope,\n config.auth,\n );\n const headers = {\n ...(resolvedHeaders ?? {}),\n ...resolvedAuth.headers,\n };\n return {\n transport: \"remote\" as const,\n endpoint: config.endpoint,\n remoteTransport: config.remoteTransport ?? \"auto\",\n queryParams: resolvedQueryParams,\n headers: Object.keys(headers).length > 0 ? headers : undefined,\n authProvider: resolvedAuth.authProvider,\n };\n })\n : resolveConnectorInput(namespace, config.scope, sd, ctx, allowStdio)\n ).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 > = 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\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 if (directBindings.length > 0) {\n for (const binding of directBindings) {\n const bindingTargetScope = yield* targetScopeForBinding(\n config.transport === \"remote\" ? config.credentialTargetScope : undefined,\n binding,\n );\n yield* ctx.credentialBindings.set({\n targetScope: ScopeId.make(bindingTargetScope),\n pluginId: MCP_PLUGIN_ID,\n sourceId: namespace,\n sourceScope: ScopeId.make(config.scope),\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 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.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: 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 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 const targetScope = yield* bindingTargetScope(\n input.credentialTargetScope,\n directBindings,\n );\n if (targetScope) {\n yield* validateMcpBindingTarget(ctx, {\n sourceId: namespace,\n sourceScope: scope,\n targetScope,\n });\n }\n\n const remote = existing.config;\n const updatedConfig: McpStoredSourceData = {\n ...remote,\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 sourceName = input.name?.trim() || existing.name;\n\n const affectedPrefixes = [\n ...(input.headers !== undefined ? [\"header:\"] : []),\n ...(input.queryParams !== undefined ? [\"query_param:\"] : []),\n ...(input.auth !== undefined ? [\"auth:\"] : []),\n ];\n const replacementTargetScope = targetScope ?? input.credentialTargetScope ?? scope;\n yield* ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.storage.putSource({\n namespace,\n scope,\n name: sourceName,\n config: updatedConfig,\n });\n if (affectedPrefixes.length > 0 || directBindings.length > 0) {\n yield* ctx.credentialBindings.replaceForSource({\n targetScope: ScopeId.make(replacementTargetScope),\n pluginId: MCP_PLUGIN_ID,\n sourceId: namespace,\n sourceScope: ScopeId.make(scope),\n slotPrefixes: affectedPrefixes,\n bindings: directBindings.map((binding) => ({\n slotKey: binding.slot,\n value: binding.value,\n })),\n });\n }\n }),\n );\n\n if (configFile) {\n const bindings = yield* ctx.credentialBindings.listForSource({\n pluginId: MCP_PLUGIN_ID,\n sourceId: namespace,\n sourceScope: ScopeId.make(scope),\n });\n const inputForm = inputFormFromStored(\n bindings,\n updatedConfig,\n scope,\n sourceName,\n namespace,\n );\n yield* configFile\n .upsertSource(toMcpConfigEntry(namespace, sourceName, inputForm))\n .pipe(Effect.withSpan(\"mcp.plugin.config_file.upsert\"));\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 listSourceBindings: (sourceId: string, sourceScope: string) =>\n listMcpSourceBindings(ctx, sourceId, sourceScope),\n setSourceBinding: (input: McpSourceBindingInput) =>\n Effect.gen(function* () {\n yield* validateMcpBindingTarget(ctx, {\n sourceId: input.sourceId,\n sourceScope: input.sourceScope,\n targetScope: input.scope,\n });\n const binding = yield* ctx.credentialBindings.set({\n targetScope: input.scope,\n pluginId: MCP_PLUGIN_ID,\n sourceId: input.sourceId,\n sourceScope: input.sourceScope,\n slotKey: input.slot,\n value: input.value,\n });\n return coreBindingToMcpBinding(binding);\n }),\n removeSourceBinding: (sourceId: string, sourceScope: string, slot: string, scope: string) =>\n Effect.gen(function* () {\n yield* validateMcpBindingTarget(ctx, {\n sourceId,\n sourceScope,\n targetScope: scope,\n });\n yield* ctx.credentialBindings.remove({\n targetScope: ScopeId.make(scope),\n pluginId: MCP_PLUGIN_ID,\n sourceId,\n sourceScope: ScopeId.make(sourceScope),\n slotKey: slot,\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 + 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;\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 return 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 }).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 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 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.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 readonly updateSource: (\n namespace: string,\n scope: string,\n input: McpUpdateSourceInput,\n ) => Effect.Effect<void, McpExtensionFailure>;\n readonly listSourceBindings: (\n sourceId: string,\n sourceScope: string,\n ) => Effect.Effect<readonly McpSourceBindingRef[], StorageFailure>;\n readonly setSourceBinding: (\n input: McpSourceBindingInput,\n ) => Effect.Effect<McpSourceBindingRef, StorageFailure>;\n readonly removeSourceBinding: (\n sourceId: string,\n sourceScope: string,\n slot: string,\n scope: string,\n ) => Effect.Effect<void, StorageFailure>;\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 { 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<McpConnection, McpConnectionError>;\n readonly connectionCache: ScopedCache.ScopedCache<string, McpConnection, McpConnectionError>;\n readonly pendingConnectors: Map<string, Effect.Effect<McpConnection, McpConnectionError>>;\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\" ? \"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\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 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 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":";;;;;;;;;;;;;;;;;AAkBA,SAAS,QAAQ,QAAQ,cAAc;AAEvC;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAaA,IAAM,YAAY,aAAa;AAAA,EACpC,YAAY;AAAA,IACV,QAAQ;AAAA,MACN,IAAI,EAAE,MAAM,UAAU,UAAU,KAAK;AAAA,MACrC,UAAU,EAAE,MAAM,UAAU,UAAU,MAAM,OAAO,KAAK;AAAA,MACxD,MAAM,EAAE,MAAM,UAAU,UAAU,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA,MAKvC,QAAQ,EAAE,MAAM,QAAQ,UAAU,KAAK;AAAA;AAAA;AAAA,MAGvC,WAAW;AAAA,QACT,MAAM,CAAC,QAAQ,UAAU,QAAQ;AAAA,QACjC,UAAU;AAAA,QACV,cAAc;AAAA,MAChB;AAAA;AAAA,MAEA,kB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B,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,eAAOG,aAAY,cAAc,QAAQ,eAAe;AACxD,eAAO,MAAM,MAAM,QAAQ,YAAYK,MAAK,IAAI;AAChD,mBAAW,UAAU;AAAA,MACvB;AAAA,IACF,CAAC,EAAE,KAAKR,QAAO,SAAS,kBAAkB,CAAC;AAAA,EAC/C;AAKF,CAAC;","names":["Duration","Effect","Exit","Option","Predicate","ScopedCache","ConfiguredCredentialBinding","Effect","Effect","Effect","Option","Schema","Schema","Option","Option","Effect","Effect","Option","Schema","Schema","Option","Effect","Effect","Option","Schema","Effect","ConfiguredCredentialBinding","Predicate","ScopedCache","Duration","entry","bindingTargetScope","Option","Exit"]}
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":["// ---------------------------------------------------------------------------\n// MCP plugin storage — four tables:\n// - mcp_source: per-source structural data (transport, endpoint,\n// stdio command/args/env, etc.) plus the auth flattened into\n// columns so source-owned credential slots are queryable. The non-ref\n// structural data still lives in `config` as JSON because it's\n// plugin-private and varies by transport (`remote` vs `stdio`\n// have different shapes).\n// - mcp_source_header / mcp_source_query_param: child tables for\n// remote sources' headers and query_params SecretBackedMap entries.\n// - mcp_binding: per-tool McpToolBinding (toolId/toolName/description/\n// input+output schemas/annotations). Stays JSON: it carries no\n// refs, and `inputSchema` / `outputSchema` are arbitrary\n// user-supplied JSON Schemas — a legitimate JSON case.\n// OAuth session storage lives at the core level in `oauth2_session`\n// and is owned by `ctx.oauth`.\n// ---------------------------------------------------------------------------\n\nimport { Effect, Option, Schema } from \"effect\";\n\nimport {\n ConfiguredCredentialBinding,\n defineSchema,\n type StorageDeps,\n type StorageFailure,\n} from \"@executor-js/sdk/core\";\n\nimport {\n McpToolBinding,\n McpStoredSourceData,\n type McpConnectionAuth,\n type ConfiguredMcpCredentialValue,\n} 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 // Plugin-private structural data minus the ref-bearing fields\n // (auth, headers, queryParams). For remote sources: transport,\n // endpoint, remoteTransport. For stdio: transport, command,\n // args, env, cwd.\n config: { type: \"json\", required: true },\n // Flattened McpConnectionAuth. The stored source only names slots;\n // concrete per-user/per-workspace values live in core credential_binding.\n auth_kind: {\n type: [\"none\", \"header\", \"oauth2\"],\n required: true,\n defaultValue: \"none\",\n },\n // Header-auth fields.\n auth_header_name: { type: \"string\", required: false },\n auth_header_slot: { type: \"string\", required: false },\n auth_header_prefix: { type: \"string\", required: false },\n // OAuth2 auth fields.\n auth_connection_slot: { type: \"string\", required: false },\n auth_client_id_slot: {\n type: \"string\",\n required: false,\n },\n auth_client_secret_slot: {\n type: \"string\",\n required: false,\n },\n created_at: { type: \"date\", required: true },\n },\n },\n mcp_source_header: {\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 name: { type: \"string\", required: true },\n kind: { type: [\"text\", \"binding\"], required: true },\n text_value: { type: \"string\", required: false },\n slot_key: { type: \"string\", required: false },\n prefix: { type: \"string\", required: false },\n },\n },\n mcp_source_query_param: {\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 name: { type: \"string\", required: true },\n kind: { type: [\"text\", \"binding\"], required: true },\n text_value: { type: \"string\", required: false },\n slot_key: { type: \"string\", required: false },\n prefix: { type: \"string\", required: false },\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);\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\n// --- auth column packing/unpacking ------------------------------------------\n\ninterface AuthColumns {\n readonly auth_kind: \"none\" | \"header\" | \"oauth2\";\n readonly auth_header_name?: string;\n readonly auth_header_slot?: string;\n readonly auth_header_prefix?: string;\n readonly auth_connection_slot?: string;\n readonly auth_client_id_slot?: string;\n readonly auth_client_secret_slot?: string;\n}\n\nconst authToColumns = (auth: McpConnectionAuth): AuthColumns => {\n if (auth.kind === \"header\") {\n return {\n auth_kind: \"header\",\n auth_header_name: auth.headerName,\n auth_header_slot: auth.secretSlot,\n auth_header_prefix: auth.prefix,\n };\n }\n if (auth.kind === \"oauth2\") {\n return {\n auth_kind: \"oauth2\",\n auth_connection_slot: auth.connectionSlot,\n auth_client_id_slot: auth.clientIdSlot,\n auth_client_secret_slot: auth.clientSecretSlot,\n };\n }\n return { auth_kind: \"none\" };\n};\n\nconst columnsToAuth = (row: Record<string, unknown>): McpConnectionAuth => {\n const kind = row.auth_kind;\n if (kind === \"header\" && typeof row.auth_header_slot === \"string\") {\n const prefix = row.auth_header_prefix as string | null | undefined;\n return {\n kind: \"header\",\n headerName: (row.auth_header_name as string | null) ?? \"\",\n secretSlot: row.auth_header_slot,\n ...(prefix ? { prefix } : {}),\n };\n }\n if (kind === \"oauth2\" && typeof row.auth_connection_slot === \"string\") {\n const cid = row.auth_client_id_slot as string | null | undefined;\n const csec = row.auth_client_secret_slot as string | null | undefined;\n return {\n kind: \"oauth2\",\n connectionSlot: row.auth_connection_slot,\n ...(cid ? { clientIdSlot: cid } : {}),\n ...(csec ? { clientSecretSlot: csec } : {}),\n };\n }\n return { kind: \"none\" };\n};\n\n// --- ConfiguredCredentialValue map <-> child rows ---------------------------\n\ninterface ConfiguredCredentialRow {\n readonly id: string;\n readonly scope_id: string;\n readonly source_id: string;\n readonly name: string;\n readonly kind: \"text\" | \"binding\";\n readonly text_value?: string;\n readonly slot_key?: string;\n readonly prefix?: string;\n readonly [k: string]: unknown;\n}\n\nconst valueMapToRows = (\n sourceId: string,\n scope: string,\n values: Record<string, ConfiguredMcpCredentialValue> | undefined,\n): readonly ConfiguredCredentialRow[] => {\n if (!values) return [];\n return Object.entries(values).map(([name, value]) => {\n const id = JSON.stringify([sourceId, name]);\n if (typeof value === \"string\") {\n return {\n id,\n scope_id: scope,\n source_id: sourceId,\n name,\n kind: \"text\",\n text_value: value,\n };\n }\n return {\n id,\n scope_id: scope,\n source_id: sourceId,\n name,\n kind: \"binding\",\n slot_key: value.slot,\n prefix: value.prefix,\n };\n });\n};\n\nconst rowsToValueMap = (\n rows: readonly Record<string, unknown>[],\n): Record<string, ConfiguredMcpCredentialValue> => {\n const out: Record<string, ConfiguredMcpCredentialValue> = {};\n for (const row of rows) {\n if (typeof row.name !== \"string\") continue;\n const name = row.name;\n if (row.kind === \"binding\" && typeof row.slot_key === \"string\") {\n const prefix = row.prefix as string | undefined | null;\n out[name] = prefix\n ? ConfiguredCredentialBinding.make({ kind: \"binding\", slot: row.slot_key, prefix })\n : ConfiguredCredentialBinding.make({ kind: \"binding\", slot: row.slot_key });\n } else if (row.kind === \"text\" && typeof row.text_value === \"string\") {\n out[name] = row.text_value;\n }\n }\n return out;\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<{\n readonly toolId: string;\n readonly binding: McpToolBinding;\n }>,\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<{\n readonly toolId: string;\n readonly binding: McpToolBinding;\n }>,\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: (namespace: string, scope: string) => Effect.Effect<void, StorageFailure>;\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\nexport const makeMcpStore = ({ adapter: db }: 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: yield* hydrateSourceData(row, namespace, scope),\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 yield* hydrateSourceData(row, namespace, scope);\n }),\n\n putSource: (source) =>\n Effect.gen(function* () {\n const now = new Date();\n // Drop the source row and its child rows; recreate. Two-step\n // matches the existing put-overwrites-existing semantic.\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* deleteSourceChildren(source.namespace, source.scope);\n\n const auth: McpConnectionAuth =\n source.config.transport === \"remote\" ? source.config.auth : { kind: \"none\" };\n const authCols = authToColumns(auth);\n const headers = source.config.transport === \"remote\" ? source.config.headers : undefined;\n const queryParams =\n source.config.transport === \"remote\" ? source.config.queryParams : undefined;\n\n // The encoded config keeps every plugin-private field but\n // strips auth/headers/queryParams — those moved to columns/\n // child tables. We round-trip through encodeSourceData so the\n // remaining fields stay in the same JSON shape decode expects.\n const encodedConfig = stripExtractedFields(\n encodeSourceData(source.config) as Record<string, unknown>,\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: encodedConfig,\n created_at: now,\n ...authCols,\n },\n forceAllowId: true,\n });\n\n const headerRows = valueMapToRows(source.namespace, source.scope, headers);\n if (headerRows.length > 0) {\n yield* db.createMany({\n model: \"mcp_source_header\",\n data: headerRows,\n forceAllowId: true,\n });\n }\n const paramRows = valueMapToRows(source.namespace, source.scope, queryParams);\n if (paramRows.length > 0) {\n yield* db.createMany({\n model: \"mcp_source_query_param\",\n data: paramRows,\n forceAllowId: true,\n });\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* deleteSourceChildren(namespace, scope);\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 // ---------------------------------------------------------------------\n // Private helpers — depend on `db` so they live inside the closure.\n // ---------------------------------------------------------------------\n\n function deleteSourceChildren(namespace: string, scope: string) {\n return Effect.gen(function* () {\n for (const model of [\"mcp_source_header\", \"mcp_source_query_param\"] as const) {\n yield* db.deleteMany({\n model,\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n }\n });\n }\n\n function hydrateSourceData(\n row: Record<string, unknown>,\n namespace: string,\n scope: string,\n ): Effect.Effect<McpStoredSourceData, StorageFailure> {\n return Effect.gen(function* () {\n // The stored JSON has auth/headers/queryParams stripped (those\n // moved to columns / child tables). We must rehydrate the full\n // shape BEFORE handing it to the schema decoder, because\n // `McpRemoteSourceData.auth` is required.\n const partial = coerceJson(row.config) as Record<string, unknown>;\n if (partial.transport !== \"remote\") {\n // stdio sources have no extracted fields — decode as-is.\n return decodeSourceData(partial);\n }\n const headerRows = yield* db.findMany({\n model: \"mcp_source_header\",\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n const paramRows = yield* db.findMany({\n model: \"mcp_source_query_param\",\n where: [\n { field: \"source_id\", value: namespace },\n { field: \"scope_id\", value: scope },\n ],\n });\n const headers = rowsToValueMap(headerRows);\n const queryParams = rowsToValueMap(paramRows);\n const reassembled = {\n ...partial,\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n ...(Object.keys(queryParams).length > 0 ? { queryParams } : {}),\n auth: columnsToAuth(row),\n };\n return decodeSourceData(reassembled);\n });\n }\n};\n\n// Strip auth/headers/queryParams from the encoded source-data shape.\n// Keeps the remaining structural fields (transport, endpoint, etc.) in\n// the JSON config column. Per-transport: only the remote variant has\n// these fields, so this is a no-op for stdio.\nconst stripExtractedFields = (encoded: Record<string, unknown>): Record<string, unknown> => {\n if (encoded.transport !== \"remote\") return encoded;\n const { auth, headers, queryParams, ...rest } = encoded;\n void auth;\n void headers;\n void queryParams;\n return rest;\n};\n","import {\n Duration,\n Effect,\n Exit,\n Layer,\n Match,\n Option,\n Predicate,\n Result,\n Scope,\n ScopedCache,\n} from \"effect\";\nimport type { HttpClient } from \"effect/unstable/http\";\n\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\n\nimport {\n ConfiguredCredentialBinding,\n ConnectionId,\n type CredentialBindingRef,\n type CredentialBindingValue,\n ScopeId,\n SecretId,\n SourceDetectionResult,\n definePlugin,\n resolveSecretBackedMap as resolveSharedSecretBackedMap,\n type PluginCtx,\n type StorageFailure,\n StorageError,\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, McpInvocationError, McpToolDiscoveryError } from \"./errors\";\nimport { invokeMcpTool } from \"./invoke\";\nimport { deriveMcpNamespace, type McpToolManifest, type McpToolManifestEntry } from \"./manifest\";\nimport { probeMcpEndpointShape, type McpShapeProbeResult } from \"./probe-shape\";\nimport {\n MCP_HEADER_AUTH_SLOT,\n MCP_OAUTH_CLIENT_ID_SLOT,\n MCP_OAUTH_CLIENT_SECRET_SLOT,\n MCP_OAUTH_CONNECTION_SLOT,\n McpToolBinding,\n McpSourceBindingInput,\n McpSourceBindingRef,\n mcpHeaderSlot,\n mcpQueryParamSlot,\n type McpConnectionAuth,\n type McpConnectionAuthInput,\n type McpCredentialInput,\n type McpSourceBindingValue,\n type SecretBackedValue,\n type McpStoredSourceData,\n type ConfiguredMcpCredentialValue,\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, McpCredentialInput>;\n readonly headers?: Record<string, McpCredentialInput>;\n readonly namespace?: string;\n readonly auth?: McpConnectionAuthInput;\n /**\n * Scope that owns any direct credentials supplied on this call. Required\n * whenever headers/queryParams/auth carry direct secret or connection ids.\n */\n readonly credentialTargetScope?: string;\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 supportsDynamicRegistration: 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, McpCredentialInput>;\n readonly queryParams?: Record<string, McpCredentialInput>;\n readonly credentialTargetScope?: string;\n readonly auth?: McpConnectionAuthInput;\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 = (\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\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\";\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 coreBindingToMcpBinding = (binding: CredentialBindingRef): McpSourceBindingRef =>\n McpSourceBindingRef.make({\n sourceId: binding.sourceId,\n sourceScopeId: binding.sourceScopeId,\n scopeId: binding.scopeId,\n slot: binding.slotKey,\n value: binding.value,\n createdAt: binding.createdAt,\n updatedAt: binding.updatedAt,\n });\n\nconst listMcpSourceBindings = (\n ctx: PluginCtx<McpBindingStore>,\n sourceId: string,\n sourceScope: string,\n): Effect.Effect<readonly McpSourceBindingRef[], StorageFailure> =>\n Effect.gen(function* () {\n const ranks = scopeRanks(ctx);\n const sourceSourceRank = scopeRank(ranks, sourceScope);\n if (sourceSourceRank === Infinity) return [];\n const bindings = yield* ctx.credentialBindings.listForSource({\n pluginId: MCP_PLUGIN_ID,\n sourceId,\n sourceScope: ScopeId.make(sourceScope),\n });\n return bindings\n .filter((binding) => scopeRank(ranks, binding.scopeId) <= sourceSourceRank)\n .map(coreBindingToMcpBinding);\n });\n\nconst resolveMcpSourceBinding = (\n ctx: PluginCtx<McpBindingStore>,\n sourceId: string,\n sourceScope: string,\n slot: string,\n): Effect.Effect<McpSourceBindingRef | 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 ? coreBindingToMcpBinding(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 bindingTargetScope = (\n targetScope: string | undefined,\n bindings: readonly unknown[],\n): Effect.Effect<string | undefined, McpConnectionError> => {\n if (bindings.length === 0) return Effect.succeed(undefined);\n if (targetScope) return Effect.succeed(targetScope);\n return Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: \"credentialTargetScope is required when adding direct MCP credentials\",\n }),\n );\n};\n\nconst targetScopeForBinding = (\n fallbackTargetScope: string | undefined,\n binding: { readonly targetScope?: string },\n): Effect.Effect<string, McpConnectionError> => {\n const targetScope = binding.targetScope ?? fallbackTargetScope;\n if (targetScope) return Effect.succeed(targetScope);\n return Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: \"credentialTargetScope is required when adding direct MCP credentials\",\n }),\n );\n};\n\nconst canonicalizeCredentialMap = (\n values: Record<string, McpCredentialInput> | undefined,\n slotForName: (name: string) => string,\n): {\n readonly values: Record<string, ConfiguredMcpCredentialValue>;\n readonly bindings: ReadonlyArray<{\n readonly slot: string;\n readonly value: McpSourceBindingValue;\n readonly targetScope?: string;\n }>;\n} => {\n const nextValues: Record<string, ConfiguredMcpCredentialValue> = {};\n const bindings: Array<{ slot: string; value: McpSourceBindingValue; targetScope?: string }> = [];\n for (const [name, value] of Object.entries(values ?? {})) {\n if (typeof value === \"string\") {\n nextValues[name] = value;\n continue;\n }\n if (\"kind\" in value) {\n nextValues[name] = value;\n continue;\n }\n const slot = slotForName(name);\n nextValues[name] = ConfiguredCredentialBinding.make({\n kind: \"binding\",\n slot,\n prefix: value.prefix,\n });\n bindings.push({\n slot,\n targetScope: \"targetScope\" in value ? value.targetScope : undefined,\n value: {\n kind: \"secret\",\n secretId: SecretId.make(value.secretId),\n ...(\"secretScopeId\" in value && value.secretScopeId\n ? { secretScopeId: value.secretScopeId }\n : {}),\n },\n });\n }\n return { values: nextValues, bindings };\n};\n\nconst canonicalizeAuth = (\n auth: McpConnectionAuthInput | undefined,\n): {\n readonly auth: McpConnectionAuth;\n readonly bindings: ReadonlyArray<{\n readonly slot: string;\n readonly value: McpSourceBindingValue;\n readonly targetScope?: string;\n }>;\n} => {\n if (!auth || auth.kind === \"none\") return { auth: { kind: \"none\" }, bindings: [] };\n if (auth.kind === \"header\") {\n if (\"secretSlot\" in auth) return { auth, bindings: [] };\n return {\n auth: {\n kind: \"header\",\n headerName: auth.headerName,\n secretSlot: MCP_HEADER_AUTH_SLOT,\n prefix: auth.prefix,\n },\n bindings: [\n {\n slot: MCP_HEADER_AUTH_SLOT,\n targetScope: auth.targetScope,\n value: {\n kind: \"secret\",\n secretId: SecretId.make(auth.secretId),\n ...(auth.secretScopeId ? { secretScopeId: auth.secretScopeId } : {}),\n },\n },\n ],\n };\n }\n if (\"connectionSlot\" in auth) return { auth, bindings: [] };\n const bindings: Array<{ slot: string; value: McpSourceBindingValue; targetScope?: string }> = [\n {\n slot: MCP_OAUTH_CONNECTION_SLOT,\n value: {\n kind: \"connection\",\n connectionId: ConnectionId.make(auth.connectionId),\n },\n },\n ];\n if (auth.clientIdSecretId) {\n bindings.push({\n slot: MCP_OAUTH_CLIENT_ID_SLOT,\n value: { kind: \"secret\", secretId: SecretId.make(auth.clientIdSecretId) },\n });\n }\n if (auth.clientSecretSecretId) {\n bindings.push({\n slot: MCP_OAUTH_CLIENT_SECRET_SLOT,\n value: { kind: \"secret\", secretId: SecretId.make(auth.clientSecretSecretId) },\n });\n }\n return {\n auth: {\n kind: \"oauth2\",\n connectionSlot: MCP_OAUTH_CONNECTION_SLOT,\n ...(auth.clientIdSecretId ? { clientIdSlot: MCP_OAUTH_CLIENT_ID_SLOT } : {}),\n ...(auth.clientSecretSecretId ? { 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 plainStringMap = (\n values: Record<string, McpCredentialInput> | 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\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, McpConnectionError | 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 secret = yield* ctx.secrets.getAtScope(binding.value.secretId, binding.scopeId).pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () =>\n Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve secret for ${params.missingLabel} \"${name}\"`,\n }),\n ),\n ),\n );\n if (secret === null) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: `Missing secret \"${binding.value.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 McpConnectionError({\n transport: \"remote\",\n message: `Missing binding for ${params.missingLabel} \"${name}\"`,\n });\n }\n return Object.keys(resolved).length > 0 ? resolved : undefined;\n });\n\nconst resolveMcpCredentialInputMap = (\n ctx: PluginCtx<McpBindingStore>,\n values: Record<string, McpCredentialInput> | 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, McpConnectionError | 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 if (\"kind\" in value) {\n const slotResolved = yield* resolveMcpBindingValueMap(\n ctx,\n { [name]: value },\n {\n sourceId: params.sourceId,\n sourceScope: params.sourceScope,\n missingLabel: params.missingLabel,\n },\n );\n if (slotResolved?.[name] !== undefined) resolved[name] = slotResolved[name];\n continue;\n }\n const secretScope =\n \"secretScopeId\" in value\n ? (value.secretScopeId ?? value.targetScope)\n : (params.targetScope ?? params.sourceScope);\n const secret = yield* ctx.secrets.getAtScope(SecretId.make(value.secretId), secretScope).pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () =>\n Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve secret for ${params.missingLabel} \"${name}\"`,\n }),\n ),\n ),\n );\n if (secret === null) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: `Missing secret \"${value.secretId}\" for ${params.missingLabel} \"${name}\"`,\n });\n }\n resolved[name] = value.prefix ? `${value.prefix}${secret}` : secret;\n }\n return Object.keys(resolved).length > 0 ? resolved : undefined;\n });\n\nconst resolveMcpHeaderAuth = (\n ctx: PluginCtx<McpBindingStore>,\n sourceId: string,\n sourceScope: string,\n auth: McpConnectionAuth,\n): Effect.Effect<Record<string, string>, McpConnectionError | 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 secret = yield* ctx.secrets.getAtScope(binding.value.secretId, binding.scopeId).pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () =>\n Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve header auth binding \"${auth.secretSlot}\"`,\n }),\n ),\n ),\n );\n if (secret === null) {\n return yield* new McpConnectionError({\n transport: \"remote\",\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 McpConnectionError({\n transport: \"remote\",\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, McpConnectionError | 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 McpConnectionError({\n transport: \"remote\",\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.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 resolveMcpInputAuth = (\n ctx: PluginCtx<McpBindingStore>,\n sourceId: string,\n sourceScope: string,\n targetScope: string | undefined,\n auth: McpConnectionAuthInput | undefined,\n): Effect.Effect<\n { readonly headers: Record<string, string>; readonly authProvider?: OAuthClientProvider },\n McpConnectionError | StorageFailure\n> =>\n Effect.gen(function* () {\n if (!auth || auth.kind === \"none\") return { headers: {} };\n if (auth.kind === \"header\") {\n if (\"secretSlot\" in auth) {\n const headers = yield* resolveMcpHeaderAuth(ctx, sourceId, sourceScope, auth);\n return { headers };\n }\n const secretScope = auth.secretScopeId ?? auth.targetScope ?? targetScope ?? sourceScope;\n const secret = yield* ctx.secrets.getAtScope(SecretId.make(auth.secretId), secretScope).pipe(\n Effect.catchTag(\"SecretOwnedByConnectionError\", () =>\n Effect.fail(\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve secret \"${auth.secretId}\"`,\n }),\n ),\n ),\n );\n if (secret === null) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve secret \"${auth.secretId}\"`,\n });\n }\n return {\n headers: { [auth.headerName]: auth.prefix ? `${auth.prefix}${secret}` : secret },\n };\n }\n const connection =\n \"connectionId\" in auth\n ? { id: ConnectionId.make(auth.connectionId), scope: targetScope ?? sourceScope }\n : yield* Effect.gen(function* () {\n const binding = yield* resolveMcpSourceBinding(\n ctx,\n sourceId,\n sourceScope,\n auth.connectionSlot,\n );\n return binding?.value.kind === \"connection\"\n ? { id: binding.value.connectionId, scope: binding.scopeId }\n : null;\n });\n if (connection === null) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: `Missing OAuth connection binding for MCP source \"${sourceId}\"`,\n });\n }\n const accessToken = yield* ctx.connections\n .accessTokenAtScope(connection.id, connection.scope)\n .pipe(\n Effect.mapError(\n ({ message }) =>\n new McpConnectionError({\n transport: \"remote\",\n message: `Failed to resolve OAuth connection \"${connection.id}\": ${message}`,\n }),\n ),\n );\n return { headers: {}, authProvider: 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, 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<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) =>\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 secretRef = (id: string): string => `${SECRET_REF_PREFIX}${id}`;\n\nconst authToConfig = (auth: McpConnectionAuthInput | undefined): McpAuthConfig | undefined => {\n if (!auth) return undefined;\n if (auth.kind === \"none\") return { kind: \"none\" };\n if (auth.kind === \"header\") {\n if (!(\"secretId\" in auth)) return undefined;\n return {\n kind: \"header\",\n headerName: auth.headerName,\n secret: secretRef(auth.secretId),\n prefix: auth.prefix,\n };\n }\n if (!(\"connectionId\" in auth)) return undefined;\n return {\n kind: \"oauth2\",\n connectionId: auth.connectionId,\n };\n};\n\n// ---------------------------------------------------------------------------\n// Storage-form → input-form reconstruction\n//\n// `toMcpConfigEntry` consumes the `McpSourceConfig` *input* shape — the\n// legacy form with `secretId` / `connectionId`, which `authToConfig` and\n// `plainStringMap` 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 secretId: value.secretId,\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: \"header\",\n headerName: auth.headerName,\n secretId: value.secretId,\n prefix: auth.prefix,\n };\n }\n const connection = bySlot.get(auth.connectionSlot);\n if (connection?.kind !== \"connection\") return undefined;\n return { kind: \"oauth2\", connectionId: connection.connectionId };\n};\n\nconst inputFormFromStored = (\n bindings: ReadonlyArray<CredentialBindingRef>,\n stored: McpStoredSourceData,\n scope: string,\n sourceName: string,\n namespace: string,\n): McpSourceConfig => {\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: 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 // 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: canonicalizeCredentialMap(config.headers, mcpHeaderSlot),\n queryParams: canonicalizeCredentialMap(config.queryParams, mcpQueryParamSlot),\n auth: canonicalizeAuth(config.auth),\n }\n : null;\n const directBindings = canonicalRemote\n ? [\n ...canonicalRemote.headers.bindings,\n ...canonicalRemote.queryParams.bindings,\n ...canonicalRemote.auth.bindings,\n ]\n : [];\n for (const binding of directBindings) {\n const bindingTargetScope = yield* targetScopeForBinding(\n config.transport === \"remote\" ? config.credentialTargetScope : undefined,\n binding,\n );\n yield* validateMcpBindingTarget(ctx, {\n sourceId: namespace,\n sourceScope: config.scope,\n targetScope: bindingTargetScope,\n });\n }\n const targetScope =\n config.transport === \"remote\" && directBindings[0]\n ? yield* targetScopeForBinding(config.credentialTargetScope, directBindings[0])\n : undefined;\n const sd = toStoredSourceData(\n config,\n canonicalRemote\n ? {\n headers: canonicalRemote.headers.values,\n queryParams: canonicalRemote.queryParams.values,\n auth: canonicalRemote.auth.auth,\n }\n : undefined,\n );\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* (\n config.transport === \"remote\"\n ? Effect.gen(function* () {\n const resolvedHeaders = yield* resolveMcpCredentialInputMap(ctx, config.headers, {\n sourceId: namespace,\n sourceScope: config.scope,\n targetScope,\n missingLabel: \"header\",\n });\n const resolvedQueryParams = yield* resolveMcpCredentialInputMap(\n ctx,\n config.queryParams,\n {\n sourceId: namespace,\n sourceScope: config.scope,\n targetScope,\n missingLabel: \"query parameter\",\n },\n );\n const resolvedAuth = yield* resolveMcpInputAuth(\n ctx,\n namespace,\n config.scope,\n targetScope,\n config.auth,\n );\n const headers = {\n ...(resolvedHeaders ?? {}),\n ...resolvedAuth.headers,\n };\n return {\n transport: \"remote\" as const,\n endpoint: config.endpoint,\n remoteTransport: config.remoteTransport ?? \"auto\",\n queryParams: resolvedQueryParams,\n headers: Object.keys(headers).length > 0 ? headers : undefined,\n authProvider: resolvedAuth.authProvider,\n };\n })\n : resolveConnectorInput(namespace, config.scope, sd, ctx, allowStdio)\n ).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 > = 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\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 if (directBindings.length > 0) {\n for (const binding of directBindings) {\n const bindingTargetScope = yield* targetScopeForBinding(\n config.transport === \"remote\" ? config.credentialTargetScope : undefined,\n binding,\n );\n yield* ctx.credentialBindings.set({\n targetScope: ScopeId.make(bindingTargetScope),\n pluginId: MCP_PLUGIN_ID,\n sourceId: namespace,\n sourceScope: ScopeId.make(config.scope),\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 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.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: 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 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 const targetScope = yield* bindingTargetScope(\n input.credentialTargetScope,\n directBindings,\n );\n if (targetScope) {\n yield* validateMcpBindingTarget(ctx, {\n sourceId: namespace,\n sourceScope: scope,\n targetScope,\n });\n }\n\n const remote = existing.config;\n const updatedConfig: McpStoredSourceData = {\n ...remote,\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 sourceName = input.name?.trim() || existing.name;\n\n const affectedPrefixes = [\n ...(input.headers !== undefined ? [\"header:\"] : []),\n ...(input.queryParams !== undefined ? [\"query_param:\"] : []),\n ...(input.auth !== undefined ? [\"auth:\"] : []),\n ];\n const replacementTargetScope = targetScope ?? input.credentialTargetScope ?? scope;\n yield* ctx.transaction(\n Effect.gen(function* () {\n yield* ctx.storage.putSource({\n namespace,\n scope,\n name: sourceName,\n config: updatedConfig,\n });\n if (affectedPrefixes.length > 0 || directBindings.length > 0) {\n yield* ctx.credentialBindings.replaceForSource({\n targetScope: ScopeId.make(replacementTargetScope),\n pluginId: MCP_PLUGIN_ID,\n sourceId: namespace,\n sourceScope: ScopeId.make(scope),\n slotPrefixes: affectedPrefixes,\n bindings: directBindings.map((binding) => ({\n slotKey: binding.slot,\n value: binding.value,\n })),\n });\n }\n }),\n );\n\n if (configFile) {\n const bindings = yield* ctx.credentialBindings.listForSource({\n pluginId: MCP_PLUGIN_ID,\n sourceId: namespace,\n sourceScope: ScopeId.make(scope),\n });\n const inputForm = inputFormFromStored(\n bindings,\n updatedConfig,\n scope,\n sourceName,\n namespace,\n );\n yield* configFile\n .upsertSource(toMcpConfigEntry(namespace, sourceName, inputForm))\n .pipe(Effect.withSpan(\"mcp.plugin.config_file.upsert\"));\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 listSourceBindings: (sourceId: string, sourceScope: string) =>\n listMcpSourceBindings(ctx, sourceId, sourceScope),\n setSourceBinding: (input: McpSourceBindingInput) =>\n Effect.gen(function* () {\n yield* validateMcpBindingTarget(ctx, {\n sourceId: input.sourceId,\n sourceScope: input.sourceScope,\n targetScope: input.scope,\n });\n const binding = yield* ctx.credentialBindings.set({\n targetScope: input.scope,\n pluginId: MCP_PLUGIN_ID,\n sourceId: input.sourceId,\n sourceScope: input.sourceScope,\n slotKey: input.slot,\n value: input.value,\n });\n return coreBindingToMcpBinding(binding);\n }),\n removeSourceBinding: (sourceId: string, sourceScope: string, slot: string, scope: string) =>\n Effect.gen(function* () {\n yield* validateMcpBindingTarget(ctx, {\n sourceId,\n sourceScope,\n targetScope: scope,\n });\n yield* ctx.credentialBindings.remove({\n targetScope: ScopeId.make(scope),\n pluginId: MCP_PLUGIN_ID,\n sourceId,\n sourceScope: ScopeId.make(sourceScope),\n slotKey: slot,\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 + 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;\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 return 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 }).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 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 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.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 readonly updateSource: (\n namespace: string,\n scope: string,\n input: McpUpdateSourceInput,\n ) => Effect.Effect<void, McpExtensionFailure>;\n readonly listSourceBindings: (\n sourceId: string,\n sourceScope: string,\n ) => Effect.Effect<readonly McpSourceBindingRef[], StorageFailure>;\n readonly setSourceBinding: (\n input: McpSourceBindingInput,\n ) => Effect.Effect<McpSourceBindingRef, StorageFailure>;\n readonly removeSourceBinding: (\n sourceId: string,\n sourceScope: string,\n slot: string,\n scope: string,\n ) => Effect.Effect<void, StorageFailure>;\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 { 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<McpConnection, McpConnectionError>;\n readonly connectionCache: ScopedCache.ScopedCache<string, McpConnection, McpConnectionError>;\n readonly pendingConnectors: Map<string, Effect.Effect<McpConnection, McpConnectionError>>;\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\" ? \"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":";;;;;;;;;;;;;;;;;AAkBA,SAAS,QAAQ,QAAQ,cAAc;AAEvC;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AAaA,IAAM,YAAY,aAAa;AAAA,EACpC,YAAY;AAAA,IACV,QAAQ;AAAA,MACN,IAAI,EAAE,MAAM,UAAU,UAAU,KAAK;AAAA,MACrC,UAAU,EAAE,MAAM,UAAU,UAAU,MAAM,OAAO,KAAK;AAA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;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,eAAOG,aAAY,cAAc,QAAQ,eAAe;AACxD,eAAO,MAAM,MAAM,QAAQ,YAAYK,MAAK,IAAI;AAChD,mBAAW,UAAU;AAAA,MACvB;AAAA,IACF,CAAC,EAAE,KAAKR,QAAO,SAAS,kBAAkB,CAAC;AAAA,EAC/C;AAKF,CAAC;","names":["Duration","Effect","Exit","Option","Predicate","ScopedCache","ConfiguredCredentialBinding","Effect","Effect","Effect","Option","Schema","Schema","Option","Option","Effect","Effect","Option","Schema","Schema","Option","Effect","Effect","Option","Schema","Effect","ConfiguredCredentialBinding","Predicate","ScopedCache","Duration","entry","bindingTargetScope","Option","Exit"]}
package/dist/client.js CHANGED
@@ -9,7 +9,7 @@ import { defineClientPlugin } from "@executor-js/sdk/client";
9
9
  import { lazy } from "react";
10
10
  import { jsx } from "react/jsx-runtime";
11
11
  var importAdd = () => import("./AddMcpSource-TLAL463B.js");
12
- var importEdit = () => import("./EditMcpSource-CWN6HIC4.js");
12
+ var importEdit = () => import("./EditMcpSource-FAWEECNU.js");
13
13
  var importSummary = () => import("./McpSourceSummary-257JNETP.js");
14
14
  var LazyAddMcpSource = lazy(importAdd);
15
15
  var LazyEditMcpSource = lazy(importEdit);
package/dist/core.js CHANGED
@@ -2,7 +2,7 @@ import {
2
2
  makeMcpStore,
3
3
  mcpPlugin,
4
4
  mcpSchema
5
- } from "./chunk-NQT7NAGE.js";
5
+ } from "./chunk-2DOCEPYN.js";
6
6
  import {
7
7
  ConfiguredMcpCredentialValue,
8
8
  MCP_HEADER_AUTH_SLOT,
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  mcpPlugin
3
- } from "./chunk-NQT7NAGE.js";
3
+ } from "./chunk-2DOCEPYN.js";
4
4
  import "./chunk-M6REVU6O.js";
5
5
  export {
6
6
  mcpPlugin
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@executor-js/plugin-mcp",
3
- "version": "1.4.27",
3
+ "version": "1.4.29",
4
4
  "homepage": "https://github.com/RhysSullivan/executor/tree/main/packages/plugins/mcp",
5
5
  "bugs": {
6
6
  "url": "https://github.com/RhysSullivan/executor/issues"
@@ -54,15 +54,15 @@
54
54
  "dependencies": {
55
55
  "@cfworker/json-schema": "^4.1.1",
56
56
  "@effect/platform-node": "4.0.0-beta.59",
57
- "@executor-js/config": "1.4.27",
58
- "@executor-js/sdk": "1.4.27",
57
+ "@executor-js/config": "1.4.29",
58
+ "@executor-js/sdk": "1.4.29",
59
59
  "@modelcontextprotocol/sdk": "^1.29.0",
60
60
  "effect": "4.0.0-beta.59"
61
61
  },
62
62
  "devDependencies": {
63
63
  "@effect/atom-react": "4.0.0-beta.59",
64
64
  "@effect/vitest": "4.0.0-beta.59",
65
- "@executor-js/storage-core": "1.4.27",
65
+ "@executor-js/storage-core": "1.4.29",
66
66
  "@types/node": "^24.3.1",
67
67
  "@types/react": "^19.1.0",
68
68
  "bun-types": "^1.2.22",