@executor-js/plugin-mcp 1.5.11 → 1.5.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{AddMcpSource-ZDNQ7F6I.js → AddMcpSource-HCJNPYGW.js} +25 -5
- package/dist/AddMcpSource-HCJNPYGW.js.map +1 -0
- package/dist/{EditMcpSource-75NJRWZR.js → EditMcpSource-BV5ZEWEY.js} +41 -60
- package/dist/EditMcpSource-BV5ZEWEY.js.map +1 -0
- package/dist/{McpAccountsPanel-QBCSCJE7.js → McpAccountsPanel-Y3D6HSPC.js} +2 -2
- package/dist/api/group.d.ts +5 -0
- package/dist/api/index.d.ts +6 -0
- package/dist/{chunk-3AOD4VAW.js → chunk-AL7N323J.js} +7 -2
- package/dist/chunk-AL7N323J.js.map +1 -0
- package/dist/{chunk-6BJ6MZF7.js → chunk-QAG34CWT.js} +20 -8
- package/dist/chunk-QAG34CWT.js.map +1 -0
- package/dist/client.js +6 -6
- package/dist/client.js.map +1 -1
- package/dist/core.js +1 -1
- package/dist/index.js +1 -1
- package/dist/react/EditMcpSource.d.ts +2 -4
- package/dist/react/McpRemoteSourceFields.d.ts +4 -0
- package/dist/react/atoms.d.ts +3 -0
- package/dist/react/client.d.ts +3 -0
- package/dist/sdk/manifest.d.ts +3 -0
- package/dist/sdk/plugin.d.ts +12 -0
- package/package.json +3 -3
- package/dist/AddMcpSource-ZDNQ7F6I.js.map +0 -1
- package/dist/EditMcpSource-75NJRWZR.js.map +0 -1
- package/dist/chunk-3AOD4VAW.js.map +0 -1
- package/dist/chunk-6BJ6MZF7.js.map +0 -1
- /package/dist/{McpAccountsPanel-QBCSCJE7.js.map → McpAccountsPanel-Y3D6HSPC.js.map} +0 -0
package/dist/sdk/plugin.d.ts
CHANGED
|
@@ -7,6 +7,8 @@ import { type McpAuthMethod, type McpIntegrationConfig as McpIntegrationConfigTy
|
|
|
7
7
|
declare const McpRemoteServerInputSchema: Schema.Struct<{
|
|
8
8
|
readonly transport: Schema.optional<Schema.Literal<"remote">>;
|
|
9
9
|
readonly name: Schema.String;
|
|
10
|
+
/** Agent-visible catalog description. Defaults to the display name. */
|
|
11
|
+
readonly description: Schema.optional<Schema.String>;
|
|
10
12
|
readonly endpoint: Schema.String;
|
|
11
13
|
readonly remoteTransport: Schema.optional<Schema.Literals<readonly ["streamable-http", "sse", "auto"]>>;
|
|
12
14
|
readonly headers: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
|
|
@@ -47,6 +49,7 @@ declare const McpRemoteServerInputSchema: Schema.Struct<{
|
|
|
47
49
|
declare const McpStdioServerInputSchema: Schema.Struct<{
|
|
48
50
|
readonly transport: Schema.Literal<"stdio">;
|
|
49
51
|
readonly name: Schema.String;
|
|
52
|
+
readonly description: Schema.optional<Schema.String>;
|
|
50
53
|
readonly command: Schema.String;
|
|
51
54
|
readonly args: Schema.optional<Schema.$Array<Schema.String>>;
|
|
52
55
|
readonly env: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
|
|
@@ -56,6 +59,8 @@ declare const McpStdioServerInputSchema: Schema.Struct<{
|
|
|
56
59
|
declare const McpAddServerInputSchema: Schema.Union<readonly [Schema.Struct<{
|
|
57
60
|
readonly transport: Schema.optional<Schema.Literal<"remote">>;
|
|
58
61
|
readonly name: Schema.String;
|
|
62
|
+
/** Agent-visible catalog description. Defaults to the display name. */
|
|
63
|
+
readonly description: Schema.optional<Schema.String>;
|
|
59
64
|
readonly endpoint: Schema.String;
|
|
60
65
|
readonly remoteTransport: Schema.optional<Schema.Literals<readonly ["streamable-http", "sse", "auto"]>>;
|
|
61
66
|
readonly headers: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
|
|
@@ -95,6 +100,7 @@ declare const McpAddServerInputSchema: Schema.Union<readonly [Schema.Struct<{
|
|
|
95
100
|
}>, Schema.Struct<{
|
|
96
101
|
readonly transport: Schema.Literal<"stdio">;
|
|
97
102
|
readonly name: Schema.String;
|
|
103
|
+
readonly description: Schema.optional<Schema.String>;
|
|
98
104
|
readonly command: Schema.String;
|
|
99
105
|
readonly args: Schema.optional<Schema.$Array<Schema.String>>;
|
|
100
106
|
readonly env: Schema.optional<Schema.$Record<Schema.String, Schema.String>>;
|
|
@@ -141,6 +147,9 @@ declare const McpProbeEndpointOutputSchema: Schema.Struct<{
|
|
|
141
147
|
readonly slug: Schema.String;
|
|
142
148
|
readonly toolCount: Schema.NullOr<Schema.Number>;
|
|
143
149
|
readonly serverName: Schema.NullOr<Schema.String>;
|
|
150
|
+
/** The server's `instructions` from initialize — prefill for the add form's
|
|
151
|
+
* description. Only available when the probe connected unauthenticated. */
|
|
152
|
+
readonly instructions: Schema.NullOr<Schema.String>;
|
|
144
153
|
}>;
|
|
145
154
|
export type McpRemoteServerInput = typeof McpRemoteServerInputSchema.Type;
|
|
146
155
|
export type McpStdioServerInput = typeof McpStdioServerInputSchema.Type;
|
|
@@ -178,6 +187,7 @@ export declare const mcpPlugin: import("@executor-js/sdk").ConfiguredPlugin<"mcp
|
|
|
178
187
|
slug: string;
|
|
179
188
|
toolCount: number;
|
|
180
189
|
serverName: string | null;
|
|
190
|
+
instructions: string | null;
|
|
181
191
|
} | {
|
|
182
192
|
connected: false;
|
|
183
193
|
requiresAuthentication: true;
|
|
@@ -187,6 +197,7 @@ export declare const mcpPlugin: import("@executor-js/sdk").ConfiguredPlugin<"mcp
|
|
|
187
197
|
slug: string;
|
|
188
198
|
toolCount: null;
|
|
189
199
|
serverName: null;
|
|
200
|
+
instructions: null;
|
|
190
201
|
} | {
|
|
191
202
|
connected: false;
|
|
192
203
|
requiresAuthentication: true;
|
|
@@ -196,6 +207,7 @@ export declare const mcpPlugin: import("@executor-js/sdk").ConfiguredPlugin<"mcp
|
|
|
196
207
|
slug: string;
|
|
197
208
|
toolCount: null;
|
|
198
209
|
serverName: null;
|
|
210
|
+
instructions: null;
|
|
199
211
|
}, McpConnectionError, never>;
|
|
200
212
|
addServer: (input: McpServerInput) => Effect.Effect<{
|
|
201
213
|
slug: string;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@executor-js/plugin-mcp",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.12",
|
|
4
4
|
"homepage": "https://github.com/RhysSullivan/executor/tree/main/packages/plugins/mcp",
|
|
5
5
|
"bugs": {
|
|
6
6
|
"url": "https://github.com/RhysSullivan/executor/issues"
|
|
@@ -54,8 +54,8 @@
|
|
|
54
54
|
"dependencies": {
|
|
55
55
|
"@cfworker/json-schema": "^4.1.1",
|
|
56
56
|
"@effect/platform-node": "4.0.0-beta.59",
|
|
57
|
-
"@executor-js/config": "1.5.
|
|
58
|
-
"@executor-js/sdk": "1.5.
|
|
57
|
+
"@executor-js/config": "1.5.12",
|
|
58
|
+
"@executor-js/sdk": "1.5.12",
|
|
59
59
|
"@modelcontextprotocol/sdk": "^1.29.0",
|
|
60
60
|
"zod": "4.3.6"
|
|
61
61
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/AddMcpSource.tsx","../src/react/McpRemoteSourceFields.tsx"],"sourcesContent":["import { useReducer, useCallback, useEffect, useMemo, useRef, useState } from \"react\";\nimport { useAtomSet } from \"@effect/atom-react\";\nimport * as Exit from \"effect/Exit\";\nimport * as Match from \"effect/Match\";\n\nimport { Button } from \"@executor-js/react/components/button\";\nimport {\n AuthMethodListEditor,\n useAuthMethodList,\n type AuthMethodRow,\n type AuthMethodSeed,\n} from \"@executor-js/react/components/auth-method-list-editor\";\nimport {\n CardStack,\n CardStackContent,\n CardStackEntryField,\n} from \"@executor-js/react/components/card-stack\";\nimport { FloatActions } from \"@executor-js/react/components/float-actions\";\nimport { Input } from \"@executor-js/react/components/input\";\nimport { Spinner } from \"@executor-js/react/components/spinner\";\nimport { Textarea } from \"@executor-js/react/components/textarea\";\nimport {\n integrationDisplayNameFromUrl,\n slugifyNamespace,\n IntegrationIdentityFields,\n useIntegrationIdentity,\n} from \"@executor-js/react/plugins/integration-identity\";\nimport {\n addIntegrationErrorMessage,\n errorMessageFromExit,\n FormErrorAlert,\n SlugCollisionAlert,\n useSlugAlreadyExists,\n} from \"@executor-js/react/lib/integration-add\";\n\nimport { integrationWriteKeys } from \"@executor-js/react/api/reactivity-keys\";\nimport type { McpAuthMethodInput } from \"../sdk/types\";\nimport { probeMcpEndpoint, addMcpServer } from \"./atoms\";\nimport { McpRemoteSourceFields } from \"./McpRemoteSourceFields\";\nimport { mcpAuthMethodInputFromEditorValue, mcpWireAuthInput } from \"./auth-method-config\";\nimport { mcpPresets, type McpPreset } from \"../sdk/presets\";\n\n// The remote add flow REGISTERS the server's declared auth methods through the\n// shared `AuthMethodListEditor` — accounts (the API key value / OAuth sign-in)\n// are added later from the integration's detail hub (P6: add without auth,\n// connect later). The probe SEEDS the list (detected OAuth → an OAuth row; a\n// 401 without OAuth → a bearer-header row; open server → a no-auth row) and\n// the user can add alternate methods (e.g. an API key alongside OAuth, or a\n// declared method on a server that advertises none).\n\nconst STDIO_ENV_ESCAPE_REPLACEMENTS: Readonly<Record<string, string>> = {\n \"\\\\\": \"\\\\\",\n n: \"\\n\",\n r: \"\\r\",\n t: \"\\t\",\n '\"': '\"',\n};\n\n// ---------------------------------------------------------------------------\n// Preset lookup\n// ---------------------------------------------------------------------------\n\nfunction findPreset(id: string | undefined): McpPreset | undefined {\n if (!id) return undefined;\n return mcpPresets.find((p) => p.id === id);\n}\n\n// ---------------------------------------------------------------------------\n// State machine (remote flow)\n// ---------------------------------------------------------------------------\n\ntype ProbeResult = {\n connected: boolean;\n requiresAuthentication: boolean;\n requiresOAuth: boolean;\n supportsDynamicRegistration: boolean;\n name: string;\n slug: string;\n toolCount: number | null;\n serverName: string | null;\n};\n\ntype State =\n | { step: \"url\"; url: string }\n | { step: \"probing\"; url: string; probe: ProbeResult | null }\n | { step: \"probed\"; url: string; probe: ProbeResult }\n | { step: \"adding\"; url: string; probe: ProbeResult }\n | {\n step: \"error\";\n url: string;\n probe: ProbeResult | null;\n error: string;\n };\n\ntype Action =\n | { type: \"set-url\"; url: string }\n | { type: \"probe-start\" }\n | { type: \"probe-ok\"; probe: ProbeResult }\n | { type: \"probe-fail\"; error: string }\n | { type: \"add-start\" }\n | { type: \"add-fail\"; error: string }\n | { type: \"retry\" };\n\nconst init: State = { step: \"url\", url: \"\" };\n\nfunction reducer(state: State, action: Action): State {\n return Match.value(action).pipe(\n Match.discriminator(\"type\")(\"set-url\", (a): State => ({ step: \"url\", url: a.url })),\n Match.discriminator(\"type\")(\n \"probe-start\",\n (): State => ({\n step: \"probing\",\n url: state.url,\n probe: \"probe\" in state ? state.probe : null,\n }),\n ),\n Match.discriminator(\"type\")(\n \"probe-ok\",\n (a): State => ({ step: \"probed\", url: state.url, probe: a.probe }),\n ),\n Match.discriminator(\"type\")(\n \"probe-fail\",\n (a): State => ({\n step: \"error\",\n url: state.url,\n probe: null,\n error: a.error,\n }),\n ),\n Match.discriminator(\"type\")(\"add-start\", (): State => {\n const probe = \"probe\" in state ? state.probe : null;\n if (!probe) return state;\n return { step: \"adding\", url: state.url, probe };\n }),\n Match.discriminator(\"type\")(\"add-fail\", (a): State => {\n if (state.step !== \"adding\") return state;\n return {\n step: \"error\",\n url: state.url,\n probe: state.probe,\n error: a.error,\n };\n }),\n Match.discriminator(\"type\")(\"retry\", (): State => {\n if (state.step !== \"error\") return state;\n return state.probe\n ? { step: \"probed\", url: state.url, probe: state.probe }\n : { step: \"url\", url: state.url };\n }),\n Match.exhaustive,\n );\n}\n\n// ---------------------------------------------------------------------------\n// Component\n// ---------------------------------------------------------------------------\n\nexport default function AddMcpSource(props: {\n onComplete: (slug?: string) => void;\n onCancel: () => void;\n initialUrl?: string;\n initialPreset?: string;\n /** Whether the stdio transport is enabled on the server. */\n allowStdio?: boolean;\n}) {\n const allowStdio = props.allowStdio ?? false;\n const rawPreset = findPreset(props.initialPreset);\n // Drop stdio presets when stdio is disabled — the caller should have\n // already filtered these out, but defence-in-depth.\n const preset = rawPreset?.transport === \"stdio\" && !allowStdio ? undefined : rawPreset;\n const isStdioPreset = preset?.transport === \"stdio\";\n\n const [transport, setTransport] = useState<\"remote\" | \"stdio\">(\n isStdioPreset && allowStdio ? \"stdio\" : \"remote\",\n );\n\n // --- Stdio state ---\n const [stdioCommand, setStdioCommand] = useState(isStdioPreset ? preset.command : \"\");\n const [stdioArgs, setStdioArgs] = useState(\n isStdioPreset && preset.args ? preset.args.join(\" \") : \"\",\n );\n const [stdioEnv, setStdioEnv] = useState(\"\");\n const stdioIdentity = useIntegrationIdentity({\n fallbackName: isStdioPreset ? preset.name : stdioCommand,\n });\n const [stdioAdding, setStdioAdding] = useState(false);\n const [stdioError, setStdioError] = useState<string | null>(null);\n\n // --- Remote state ---\n const remoteUrl =\n !isStdioPreset && preset?.transport === undefined && preset?.url\n ? preset.url\n : (props.initialUrl ?? \"\");\n\n const [state, dispatch] = useReducer(\n reducer,\n remoteUrl ? { step: \"url\" as const, url: remoteUrl } : init,\n );\n\n const doProbe = useAtomSet(probeMcpEndpoint, { mode: \"promiseExit\" });\n const doAddServer = useAtomSet(addMcpServer, { mode: \"promiseExit\" });\n\n const probe = \"probe\" in state ? state.probe : null;\n\n // The probe seeds the method list: detected OAuth → an OAuth row; a 401\n // without OAuth metadata → a bearer-header row; an open server → a no-auth\n // row. The user can edit any row or add alternate methods alongside.\n const authMethodSeeds: readonly AuthMethodSeed[] = useMemo(() => {\n if (!probe) return [];\n if (probe.requiresOAuth) {\n return [\n {\n value: { kind: \"oauth\", authorizationUrl: \"\", tokenUrl: \"\", scopes: [] },\n label: \"Detected\",\n },\n ];\n }\n if (probe.requiresAuthentication) {\n return [\n {\n value: {\n kind: \"apikey\",\n placements: [{ carrier: \"header\", name: \"Authorization\", prefix: \"Bearer \" }],\n },\n label: \"Detected\",\n },\n ];\n }\n return [{ value: { kind: \"none\" }, label: \"Detected\" }];\n }, [probe]);\n const authMethodList = useAuthMethodList(authMethodSeeds);\n\n const remoteIdentity = useIntegrationIdentity({\n fallbackName:\n integrationDisplayNameFromUrl(state.url, \"MCP\") ?? probe?.serverName ?? probe?.name ?? \"\",\n });\n const isProbing = state.step === \"probing\";\n const isAdding = state.step === \"adding\";\n\n // Pre-empt the API's `IntegrationAlreadyExistsError`: adding an integration\n // whose slug already exists clobbers the existing one's connections/policies,\n // so the API blocks it. Surface that here from the tenant-scoped catalog list.\n // A blank derived namespace lets the server assign the slug, so only flag a\n // collision when the user-derived slug is non-empty.\n const remoteSlug = slugifyNamespace(remoteIdentity.namespace);\n const stdioSlug = slugifyNamespace(stdioIdentity.namespace);\n const remoteSlugExists = useSlugAlreadyExists(remoteSlug);\n const stdioSlugExists = useSlugAlreadyExists(stdioSlug);\n\n const canAdd = Boolean(probe) && !isAdding && !remoteSlugExists;\n // Probe failures are shown inline on the URL field; other failures\n // (add server) render in the bottom error block.\n const probeError = state.step === \"error\" && state.probe === null ? state.error : null;\n const otherError = state.step === \"error\" && state.probe !== null ? state.error : null;\n\n // ---- Remote actions ----\n\n const handleProbe = useCallback(async () => {\n dispatch({ type: \"probe-start\" });\n const exit = await doProbe({\n payload: { endpoint: state.url.trim() },\n });\n if (Exit.isFailure(exit)) {\n dispatch({\n type: \"probe-fail\",\n error: errorMessageFromExit(exit, \"Failed to connect\"),\n });\n return;\n }\n dispatch({ type: \"probe-ok\", probe: exit.value });\n }, [state.url, doProbe]);\n\n // Keep the latest handleProbe in a ref so the debounced effect can call it\n // without depending on its identity (which changes every render).\n const handleProbeRef = useRef(handleProbe);\n handleProbeRef.current = handleProbe;\n\n // Auto-probe whenever the URL changes (debounced) while we're on the\n // remote transport and not already probing/probed.\n useEffect(() => {\n if (transport !== \"remote\") return;\n if (state.step !== \"url\") return;\n const trimmed = state.url.trim();\n if (!trimmed) return;\n const handle = setTimeout(() => {\n handleProbeRef.current();\n }, 400);\n return () => clearTimeout(handle);\n }, [transport, state.step, state.url]);\n\n // Register the integration with the declared auth methods, returning the\n // assigned slug (or null on failure — an error is dispatched in that case).\n const registerIntegration = useCallback(\n async (authenticationTemplate: readonly McpAuthMethodInput[]): Promise<string | null> => {\n const displayName = remoteIdentity.name.trim() || probe?.serverName || probe?.name || \"MCP\";\n const slug = slugifyNamespace(remoteIdentity.namespace) || undefined;\n const exit = await doAddServer({\n payload: {\n transport: \"remote\" as const,\n name: displayName,\n endpoint: state.url.trim(),\n ...(slug ? { slug } : {}),\n authenticationTemplate,\n },\n reactivityKeys: integrationWriteKeys,\n });\n if (Exit.isFailure(exit)) {\n dispatch({\n type: \"add-fail\",\n error: addIntegrationErrorMessage(exit, slug ?? displayName, \"Failed to add server\"),\n });\n return null;\n }\n return exit.value.slug;\n },\n [doAddServer, probe, remoteIdentity, state.url],\n );\n\n const handleAddRemote = useCallback(async () => {\n if (!probe) return;\n dispatch({ type: \"add-start\" });\n // Every row registers as a declared method (a lone no-auth row registers\n // the open-server method). Slugs are assigned server-side by kind.\n const methods = authMethodList.rows.map((row: AuthMethodRow) =>\n mcpWireAuthInput(mcpAuthMethodInputFromEditorValue(row.value)),\n );\n const slug = await registerIntegration(\n methods.length > 0 ? methods : [{ kind: \"none\" as const }],\n );\n if (slug === null) return;\n props.onComplete(slug);\n }, [probe, authMethodList.rows, registerIntegration, props]);\n\n // ---- Stdio actions ----\n\n const parseStdioArgs = (raw: string): string[] => {\n if (!raw.trim()) return [];\n const args: string[] = [];\n const regex = /[^\\s\"]+|\"([^\"]*)\"/g;\n let match;\n while ((match = regex.exec(raw)) !== null) {\n args.push(match[1] ?? match[0]);\n }\n return args;\n };\n\n const parseStdioEnvValue = (raw: string): string => {\n const value = raw.trim();\n if (value.length < 2) return value;\n\n const quote = value[0];\n if ((quote !== '\"' && quote !== \"'\") || value[value.length - 1] !== quote) {\n return value;\n }\n\n const inner = value.slice(1, -1);\n if (quote === \"'\") return inner;\n\n return inner.replace(\n /\\\\([\\\\nrt\"])/g,\n (_, escaped: string) => STDIO_ENV_ESCAPE_REPLACEMENTS[escaped] ?? escaped,\n );\n };\n\n const parseStdioEnv = (raw: string): Record<string, string> | undefined => {\n if (!raw.trim()) return undefined;\n const env: Record<string, string> = {};\n for (const line of raw.split(\"\\n\")) {\n const eq = line.indexOf(\"=\");\n if (eq > 0) {\n env[line.slice(0, eq).trim()] = parseStdioEnvValue(line.slice(eq + 1));\n }\n }\n return Object.keys(env).length > 0 ? env : undefined;\n };\n\n const handleAddStdio = useCallback(async () => {\n const cmd = stdioCommand.trim();\n if (!cmd) return;\n setStdioAdding(true);\n setStdioError(null);\n const displayName = stdioIdentity.name.trim() || cmd;\n const slug = slugifyNamespace(stdioIdentity.namespace) || undefined;\n const exit = await doAddServer({\n payload: {\n transport: \"stdio\" as const,\n name: displayName,\n ...(slug ? { slug } : {}),\n command: cmd,\n args: parseStdioArgs(stdioArgs),\n env: parseStdioEnv(stdioEnv),\n },\n reactivityKeys: integrationWriteKeys,\n });\n if (Exit.isFailure(exit)) {\n setStdioError(addIntegrationErrorMessage(exit, slug ?? displayName, \"Failed to add server\"));\n setStdioAdding(false);\n return;\n }\n props.onComplete(exit.value.slug);\n }, [stdioCommand, stdioArgs, stdioEnv, stdioIdentity, doAddServer, props]);\n\n // ---- Render ----\n\n return (\n <div className=\"flex flex-1 flex-col gap-6\">\n <div>\n <h1 className=\"text-xl font-semibold text-foreground\">Add MCP Source</h1>\n <p className=\"mt-1 text-[13px] text-muted-foreground\">\n Connect to an MCP server to discover and use its tools.\n </p>\n </div>\n\n {/* Transport toggle — only shown when stdio is enabled server-side */}\n {allowStdio && (\n <div className=\"flex gap-1 rounded-lg border border-border bg-muted/30 p-1\">\n <Button\n variant=\"ghost\"\n type=\"button\"\n onClick={() => setTransport(\"remote\")}\n className={`flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-colors ${\n transport === \"remote\"\n ? \"bg-background text-foreground shadow-sm\"\n : \"text-muted-foreground hover:text-foreground\"\n }`}\n >\n Remote\n </Button>\n <Button\n variant=\"ghost\"\n type=\"button\"\n onClick={() => setTransport(\"stdio\")}\n className={`flex-1 rounded-md px-3 py-1.5 text-sm font-medium transition-colors ${\n transport === \"stdio\"\n ? \"bg-background text-foreground shadow-sm\"\n : \"text-muted-foreground hover:text-foreground\"\n }`}\n >\n Stdio\n </Button>\n </div>\n )}\n\n {transport === \"remote\" ? (\n <>\n <McpRemoteSourceFields\n url={state.url}\n onUrlChange={(url) => dispatch({ type: \"set-url\", url })}\n identity={remoteIdentity}\n preview={probe}\n probing={isProbing}\n error={probeError}\n onRetry={handleProbe}\n />\n\n {/* Authentication — declares the auth methods to register through the\n shared list editor. The credentials themselves (API key value /\n OAuth sign-in) are added from the integration's detail hub after\n adding. */}\n {probe && (\n <AuthMethodListEditor\n list={authMethodList}\n title=\"How does this server authenticate?\"\n oauthMetadata=\"discovered\"\n emptyHint=\"No methods declared. Add a method, or add the server without auth and connect from the integration page later.\"\n footerHint=\"Every method here is registered with the server. Connect an account from the integration page after adding.\"\n />\n )}\n\n {/* Error (add server). Probe errors show inline on the field. */}\n {otherError && (\n <div className=\"space-y-2\">\n <FormErrorAlert message={otherError} />\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={() => dispatch({ type: \"retry\" })}\n className=\"text-xs\"\n >\n Try again\n </Button>\n </div>\n )}\n\n {remoteSlugExists && !isAdding && <SlugCollisionAlert slug={remoteSlug} />}\n\n <FloatActions>\n <Button\n type=\"button\"\n variant=\"ghost\"\n onClick={() => props.onCancel()}\n disabled={isAdding}\n >\n Cancel\n </Button>\n {(probe || isProbing) && (\n <Button type=\"button\" onClick={handleAddRemote} disabled={!canAdd}>\n {isAdding ? (\n <>\n <Spinner className=\"size-3.5\" /> Adding…\n </>\n ) : (\n \"Add source\"\n )}\n </Button>\n )}\n </FloatActions>\n </>\n ) : (\n <>\n {/* Stdio form */}\n <CardStack>\n <CardStackContent className=\"border-t-0\">\n <CardStackEntryField\n label=\"Command\"\n description=\"- The executable to run (e.g. npx, uvx, node).\"\n >\n <Input\n value={stdioCommand}\n onChange={(e) => setStdioCommand((e.target as HTMLInputElement).value)}\n placeholder=\"npx\"\n className=\"font-mono text-sm\"\n />\n </CardStackEntryField>\n\n <CardStackEntryField\n label=\"Arguments\"\n description=\"- Space-separated arguments passed to the command.\"\n >\n <Input\n value={stdioArgs}\n onChange={(e) => setStdioArgs((e.target as HTMLInputElement).value)}\n placeholder=\"-y chrome-devtools-mcp@latest\"\n className=\"font-mono text-sm\"\n />\n </CardStackEntryField>\n\n <CardStackEntryField\n label=\"Environment variables\"\n description=\"- One per line, KEY=value format.\"\n >\n <Textarea\n value={stdioEnv}\n onChange={(e) => setStdioEnv((e.target as HTMLTextAreaElement).value)}\n placeholder={\"KEY=value\\nANOTHER=value\"}\n rows={3}\n maxRows={10}\n className=\"font-mono text-sm\"\n />\n </CardStackEntryField>\n </CardStackContent>\n </CardStack>\n\n <IntegrationIdentityFields identity={stdioIdentity} namePlaceholder=\"My MCP Server\" />\n\n {/* Stdio error */}\n {stdioError && <FormErrorAlert message={stdioError} />}\n\n {stdioSlugExists && !stdioAdding && <SlugCollisionAlert slug={stdioSlug} />}\n\n <FloatActions>\n <Button\n type=\"button\"\n variant=\"ghost\"\n onClick={() => props.onCancel()}\n disabled={stdioAdding}\n >\n Cancel\n </Button>\n <Button\n type=\"button\"\n onClick={handleAddStdio}\n disabled={!stdioCommand.trim() || stdioAdding || stdioSlugExists}\n >\n {stdioAdding ? (\n <>\n <Spinner className=\"size-3.5\" /> Adding…\n </>\n ) : (\n \"Add source\"\n )}\n </Button>\n </FloatActions>\n </>\n )}\n </div>\n );\n}\n","import { Badge } from \"@executor-js/react/components/badge\";\nimport {\n CardStack,\n CardStackContent,\n CardStackEntry,\n CardStackEntryActions,\n CardStackEntryContent,\n CardStackEntryDescription,\n CardStackEntryField,\n CardStackEntryMedia,\n CardStackEntryTitle,\n} from \"@executor-js/react/components/card-stack\";\nimport { FieldError } from \"@executor-js/react/components/field\";\nimport { Input } from \"@executor-js/react/components/input\";\nimport { Skeleton } from \"@executor-js/react/components/skeleton\";\nimport { IntegrationFavicon } from \"@executor-js/react/components/integration-favicon\";\nimport { IOSSpinner } from \"@executor-js/react/components/spinner\";\nimport { Button } from \"@executor-js/react/components/button\";\nimport {\n IntegrationIdentityFieldRows,\n type IntegrationIdentity,\n} from \"@executor-js/react/plugins/integration-identity\";\n\nexport type McpRemoteSourcePreview = {\n readonly name: string;\n readonly serverName: string | null;\n readonly connected: boolean;\n readonly requiresAuthentication: boolean;\n readonly requiresOAuth: boolean;\n readonly toolCount: number | null;\n};\n\nexport function McpRemoteSourceFields(props: {\n readonly url: string;\n readonly onUrlChange: (url: string) => void;\n readonly identity: IntegrationIdentity;\n readonly preview: McpRemoteSourcePreview | null;\n readonly probing?: boolean;\n readonly error?: string | null;\n readonly onRetry?: () => void;\n readonly namespaceReadOnly?: boolean;\n readonly urlDisabled?: boolean;\n}) {\n const previewDescription = props.preview\n ? props.preview.connected\n ? props.preview.toolCount === null\n ? null\n : `${props.preview.toolCount} tool${props.preview.toolCount !== 1 ? \"s\" : \"\"} available`\n : props.preview.requiresOAuth\n ? \"OAuth required to discover tools\"\n : props.preview.requiresAuthentication\n ? \"Authentication required to discover tools\"\n : \"Ready to add\"\n : null;\n\n if (props.preview) {\n return (\n <CardStack>\n <CardStackContent className=\"border-t-0\">\n <CardStackEntry>\n <CardStackEntryMedia>\n <IntegrationFavicon url={props.url} size={32} />\n </CardStackEntryMedia>\n <CardStackEntryContent>\n <CardStackEntryTitle>\n {props.preview.serverName ?? props.preview.name}\n </CardStackEntryTitle>\n {previewDescription ? (\n <CardStackEntryDescription>{previewDescription}</CardStackEntryDescription>\n ) : null}\n </CardStackEntryContent>\n <CardStackEntryActions>\n {props.preview.connected ? (\n <Badge\n variant=\"outline\"\n className=\"border-emerald-500/20 bg-emerald-500/10 text-[10px] text-emerald-600 dark:text-emerald-400\"\n >\n Connected\n </Badge>\n ) : props.preview.requiresOAuth ? (\n <Badge\n variant=\"outline\"\n className=\"border-amber-500/20 bg-amber-500/10 text-[10px] text-amber-600 dark:text-amber-400\"\n >\n OAuth required\n </Badge>\n ) : (\n <Badge\n variant=\"outline\"\n className=\"border-amber-500/20 bg-amber-500/10 text-[10px] text-amber-600 dark:text-amber-400\"\n >\n Auth required\n </Badge>\n )}\n </CardStackEntryActions>\n </CardStackEntry>\n <IntegrationIdentityFieldRows\n identity={props.identity}\n namePlaceholder=\"e.g. Linear\"\n namespaceReadOnly={props.namespaceReadOnly}\n />\n <CardStackEntryField label=\"Server URL\">\n <Input\n value={props.url}\n onChange={(e) => props.onUrlChange((e.target as HTMLInputElement).value)}\n placeholder=\"https://mcp.example.com\"\n className=\"w-full font-mono text-sm\"\n disabled={props.urlDisabled}\n />\n </CardStackEntryField>\n </CardStackContent>\n </CardStack>\n );\n }\n\n if (props.probing) {\n return (\n <CardStack>\n <CardStackContent className=\"border-t-0\">\n <CardStackEntry>\n <CardStackEntryMedia>\n <Skeleton className=\"size-4 rounded\" />\n </CardStackEntryMedia>\n <CardStackEntryContent>\n <Skeleton className=\"h-4 w-40\" />\n <Skeleton className=\"mt-1 h-3 w-32\" />\n </CardStackEntryContent>\n <CardStackEntryActions>\n <Skeleton className=\"h-4 w-20 rounded-full\" />\n </CardStackEntryActions>\n </CardStackEntry>\n </CardStackContent>\n </CardStack>\n );\n }\n\n return (\n <CardStack>\n <CardStackContent className=\"border-t-0\">\n <CardStackEntryField label=\"Server URL\">\n <div className=\"relative\">\n <Input\n value={props.url}\n onChange={(e) => props.onUrlChange((e.target as HTMLInputElement).value)}\n placeholder=\"https://mcp.example.com\"\n className=\"w-full pr-9 font-mono text-sm\"\n aria-invalid={props.error ? true : undefined}\n disabled={props.urlDisabled}\n />\n {props.probing && (\n <div className=\"pointer-events-none absolute right-2 top-1/2 -translate-y-1/2\">\n <IOSSpinner className=\"size-4\" />\n </div>\n )}\n </div>\n {props.error && (\n <div className=\"mt-2 space-y-2\">\n <FieldError>{props.error}</FieldError>\n {props.onRetry && (\n <Button\n type=\"button\"\n variant=\"outline\"\n size=\"sm\"\n onClick={props.onRetry}\n className=\"h-7 px-2 text-xs\"\n >\n Try again\n </Button>\n )}\n </div>\n )}\n </CardStackEntryField>\n </CardStackContent>\n </CardStack>\n );\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,YAAY,aAAa,WAAW,SAAS,QAAQ,gBAAgB;AAC9E,SAAS,kBAAkB;AAC3B,YAAY,UAAU;AACtB,YAAY,WAAW;AAEvB,SAAS,UAAAA,eAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP;AAAA,EACE,aAAAC;AAAA,EACA,oBAAAC;AAAA,EACA,uBAAAC;AAAA,OACK;AACP,SAAS,oBAAoB;AAC7B,SAAS,SAAAC,cAAa;AACtB,SAAS,eAAe;AACxB,SAAS,gBAAgB;AACzB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,4BAA4B;;;ACnCrC,SAAS,aAAa;AACtB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AACtB,SAAS,gBAAgB;AACzB,SAAS,0BAA0B;AACnC,SAAS,kBAAkB;AAC3B,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,OAEK;AAwCO,cAEF,YAFE;AA7BP,SAAS,sBAAsB,OAUnC;AACD,QAAM,qBAAqB,MAAM,UAC7B,MAAM,QAAQ,YACZ,MAAM,QAAQ,cAAc,OAC1B,OACA,GAAG,MAAM,QAAQ,SAAS,QAAQ,MAAM,QAAQ,cAAc,IAAI,MAAM,EAAE,eAC5E,MAAM,QAAQ,gBACZ,qCACA,MAAM,QAAQ,yBACZ,8CACA,iBACN;AAEJ,MAAI,MAAM,SAAS;AACjB,WACE,oBAAC,aACC,+BAAC,oB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AA,UAACG;AAAA,UAAA;AAAA,YACC,MAAK;AAAA,YACL,SAAQ;AAAA,YACR,SAAS,MAAM,MAAM,SAAS;AAAA,YAC9B,UAAU;AAAA,YACX;AAAA;AAAA,QAED;AAAA,QACA,gBAAAH;AAAA,UAACG;AAAA,UAAA;AAAA,YACC,MAAK;AAAA,YACL,SAAS;AAAA,YACT,UAAU,CAAC,aAAa,KAAK,KAAK,eAAe;AAAA,YAEhD,wBACC,gBAAAF,MAAA,YACE;AAAA,8BAAAD,KAAC,WAAQ,WAAU,YAAW;AAAA,cAAE;AAAA,eAClC,IAEA;AAAA;AAAA,QAEJ;AAAA,SACF;AAAA,OACF;AAAA,KAEJ;AAEJ;","names":["Button","CardStack","CardStackContent","CardStackEntryField","Input","jsx","jsxs","value","Button","CardStack","CardStackContent","CardStackEntryField","Input"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/EditMcpSource.tsx"],"sourcesContent":["import { useCallback, useMemo, useState } from \"react\";\nimport { useAtomValue, useAtomSet } from \"@effect/atom-react\";\nimport * as AsyncResult from \"effect/unstable/reactivity/AsyncResult\";\nimport * as Exit from \"effect/Exit\";\n\nimport { IntegrationSlug } from \"@executor-js/sdk/shared\";\nimport { apiKeyMethodLabel, type AuthPlacement } from \"@executor-js/sdk/http-auth\";\nimport { integrationWriteKeys } from \"@executor-js/react/api/reactivity-keys\";\nimport {\n AuthMethodListEditor,\n useAuthMethodList,\n type AuthMethodRow,\n type AuthMethodSeed,\n} from \"@executor-js/react/components/auth-method-list-editor\";\nimport { Button } from \"@executor-js/react/components/button\";\nimport {\n CardStack,\n CardStackContent,\n CardStackEntry,\n CardStackEntryContent,\n CardStackEntryDescription,\n CardStackEntryTitle,\n} from \"@executor-js/react/components/card-stack\";\nimport { Badge } from \"@executor-js/react/components/badge\";\nimport { FormErrorAlert } from \"@executor-js/react/lib/integration-add\";\n\nimport { configureMcpAuth, mcpServerAtom } from \"./atoms\";\nimport type {\n McpAuthMethod,\n McpCanonicalAuthMethodInput,\n McpIntegrationConfig,\n} from \"../sdk/types\";\nimport {\n editorValueFromMcpAuthMethod,\n mcpAuthMethodInputFromEditorValue,\n mcpWireAuthInput,\n} from \"./auth-method-config\";\n\ntype McpServer = {\n readonly slug: IntegrationSlug;\n readonly description: string;\n readonly kind: string;\n readonly canRemove: boolean;\n readonly canRefresh: boolean;\n readonly config: McpIntegrationConfig;\n};\n\ntype McpRemoteConfig = Extract<McpIntegrationConfig, { transport: \"remote\" }>;\n\nconst methodSeedLabel = (method: McpAuthMethod): string => {\n if (method.kind === \"oauth2\") return \"OAuth\";\n if (method.kind === \"apikey\") return apiKeyMethodLabel(method);\n return \"No authentication\";\n};\n\nconst samePlacements = (\n a: readonly AuthPlacement[] | undefined,\n b: readonly AuthPlacement[] | undefined,\n): boolean => {\n const left = a ?? [];\n const right = b ?? [];\n if (left.length !== right.length) return false;\n return left.every((placement: AuthPlacement, index: number) => {\n const other = right[index];\n return (\n other !== undefined &&\n placement.carrier === other.carrier &&\n placement.name === other.name &&\n (placement.prefix ?? \"\") === (other.prefix ?? \"\") &&\n (placement.variable ?? \"\") === (other.variable ?? \"\") &&\n (placement.literal ?? null) === (other.literal ?? null)\n );\n });\n};\n\n// ---------------------------------------------------------------------------\n// Remote edit — v2: the integration's endpoint is part of its identity\n// (opaque-to-core config); the editable surface is the declared auth-method\n// LIST, through the same shared editor as the add flow. Accounts (credentials)\n// are managed from the integration page's accounts hub.\n// ---------------------------------------------------------------------------\n\nfunction RemoteEdit(props: {\n server: McpServer & { config: McpRemoteConfig };\n onSave: () => void;\n}) {\n const { server } = props;\n const doConfigureAuth = useAtomSet(configureMcpAuth, { mode: \"promiseExit\" });\n\n const seeds = useMemo<readonly AuthMethodSeed[]>(\n () =>\n server.config.authenticationTemplate.map(\n (method: McpAuthMethod): AuthMethodSeed => ({\n value: editorValueFromMcpAuthMethod(method),\n slug: method.slug,\n label: methodSeedLabel(method),\n }),\n ),\n [server.config.authenticationTemplate],\n );\n const list = useAuthMethodList(seeds);\n\n const [saving, setSaving] = useState(false);\n const [error, setError] = useState<string | null>(null);\n\n // The edited methods, slugs preserved for seeded rows so existing\n // connections (bound by template slug) stay attached. New rows omit the\n // slug — the backend assigns kind-based ones.\n const editedMethods = useMemo<readonly McpCanonicalAuthMethodInput[]>(\n () =>\n list.rows.map((row: AuthMethodRow): McpCanonicalAuthMethodInput => {\n const input = mcpAuthMethodInputFromEditorValue(row.value);\n return row.seedSlug !== undefined ? { ...input, slug: row.seedSlug } : input;\n }),\n [list.rows],\n );\n\n const methodsChanged = useMemo(() => {\n const stored = server.config.authenticationTemplate;\n if (editedMethods.length !== stored.length) return true;\n return editedMethods.some((method: McpCanonicalAuthMethodInput, index: number) => {\n const current = stored[index];\n if (!current) return true;\n if ((method.slug ?? \"\") !== current.slug) return true;\n if (method.kind !== current.kind) return true;\n if (method.kind === \"apikey\" && current.kind === \"apikey\") {\n return !samePlacements(method.placements, current.placements);\n }\n return false;\n });\n }, [editedMethods, server.config.authenticationTemplate]);\n\n const handleSave = useCallback(async () => {\n setSaving(true);\n setError(null);\n const exit = await doConfigureAuth({\n params: { slug: server.slug },\n payload: {\n authenticationTemplate:\n editedMethods.length > 0\n ? editedMethods.map(mcpWireAuthInput)\n : [{ kind: \"none\" as const }],\n mode: \"replace\",\n },\n reactivityKeys: integrationWriteKeys,\n });\n if (Exit.isFailure(exit)) {\n setError(\"Failed to update authentication methods\");\n setSaving(false);\n return;\n }\n setSaving(false);\n }, [doConfigureAuth, editedMethods, server.slug]);\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 Manage how this MCP server authenticates. The endpoint is part of the server's identity —\n remove and re-add to change it. Accounts are added from the integration page.\n </p>\n </div>\n\n <CardStack>\n <CardStackContent className=\"border-t-0\">\n <CardStackEntry>\n <CardStackEntryContent>\n <CardStackEntryTitle>{server.description || String(server.slug)}</CardStackEntryTitle>\n <CardStackEntryDescription className=\"font-mono text-xs\">\n {server.config.endpoint}\n </CardStackEntryDescription>\n </CardStackEntryContent>\n <Badge variant=\"secondary\" className=\"text-xs\">\n remote\n </Badge>\n </CardStackEntry>\n </CardStackContent>\n </CardStack>\n\n <AuthMethodListEditor\n list={list}\n title=\"How does this server authenticate?\"\n oauthMetadata=\"discovered\"\n emptyHint=\"No methods declared. Add one, or save to mark this server as open (no authentication).\"\n footerHint=\"Connections pick one of these methods. Removing a method detaches connections created against it.\"\n />\n\n {methodsChanged ? (\n <div className=\"flex justify-end\">\n <Button type=\"button\" size=\"sm\" onClick={() => void handleSave()} disabled={saving}>\n {saving ? \"Saving…\" : \"Save authentication methods\"}\n </Button>\n </div>\n ) : null}\n\n {error && <FormErrorAlert message={error} />}\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// Stdio read-only view\n// ---------------------------------------------------------------------------\n\nfunction StdioReadOnly(props: {\n server: McpServer & { config: Extract<McpIntegrationConfig, { transport: \"stdio\" }> };\n onSave: () => void;\n}) {\n const { command, args } = props.server.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\">\n {String(props.server.slug)}\n </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 — `sourceId` is the integration slug (v2).\n// ---------------------------------------------------------------------------\n\nexport default function EditMcpSource({\n sourceId,\n onSave,\n}: {\n readonly sourceId: string;\n readonly onSave: () => void;\n}) {\n const slug = IntegrationSlug.make(sourceId);\n const serverResult = useAtomValue(mcpServerAtom(slug));\n const server = AsyncResult.isSuccess(serverResult) ? serverResult.value : null;\n\n if (!AsyncResult.isSuccess(serverResult) || server === null) {\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 (server.config.transport === \"stdio\") {\n return (\n <StdioReadOnly\n server={\n server as McpServer & { config: Extract<McpIntegrationConfig, { transport: \"stdio\" }> }\n }\n onSave={onSave}\n />\n );\n }\n\n return <RemoteEdit server={server as McpServer & { config: McpRemoteConfig }} onSave={onSave} />;\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,aAAa,SAAS,gBAAgB;AAC/C,SAAS,cAAc,kBAAkB;AACzC,YAAY,iBAAiB;AAC7B,YAAY,UAAU;AAEtB,SAAS,uBAAuB;AAChC,SAAS,yBAA6C;AACtD,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,OAGK;AACP,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa;AACtB,SAAS,sBAAsB;AAoIzB,SACE,KADF;AA3GN,IAAM,kBAAkB,CAAC,WAAkC;AACzD,MAAI,OAAO,SAAS,SAAU,QAAO;AACrC,MAAI,OAAO,SAAS,SAAU,QAAO,kBAAkB,MAAM;AAC7D,SAAO;AACT;AAEA,IAAM,iBAAiB,CACrB,GACA,MACY;AACZ,QAAM,OAAO,KAAK,CAAC;AACnB,QAAM,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AAI,CAAC;AACrD,QAAM,SAAqB,sBAAU,YAAY,IAAI,aAAa,QAAQ;AAE1E,MAAI,CAAa,sBAAU,YAAY,KAAK,WAAW,MAAM;AAC3D,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,QAGA;AAAA;AAAA,IACF;AAAA,EAEJ;AAEA,SAAO,oBAAC,cAAW,QAA2D,QAAgB;AAChG;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/react/atoms.ts","../src/react/client.ts","../src/api/group.ts","../src/react/auth-method-config.ts"],"sourcesContent":["import type { IntegrationSlug } from \"@executor-js/sdk/shared\";\nimport { ReactivityKey } from \"@executor-js/react/api/reactivity-keys\";\nimport { McpClient } from \"./client\";\n\n// ---------------------------------------------------------------------------\n// Query atoms (v2)\n//\n// An MCP server is an integration. `getServer` reads the integration row's\n// opaque config (transport, endpoint, auth template). Credentials are separate\n// owner-scoped connections, created through the core connections / oauth surface\n// — there is no per-server credential binding to read here anymore.\n// ---------------------------------------------------------------------------\n\nexport const mcpServerAtom = (slug: IntegrationSlug) =>\n McpClient.query(\"mcp\", \"getServer\", {\n params: { slug },\n timeToLive: \"15 seconds\",\n reactivityKeys: [ReactivityKey.integrations, ReactivityKey.tools],\n });\n\n// ---------------------------------------------------------------------------\n// Mutation atoms\n// ---------------------------------------------------------------------------\n\nexport const probeMcpEndpoint = McpClient.mutation(\"mcp\", \"probeEndpoint\");\nexport const addMcpServer = McpClient.mutation(\"mcp\", \"addServer\");\nexport const removeMcpServer = McpClient.mutation(\"mcp\", \"removeServer\");\nexport const configureMcpServer = McpClient.mutation(\"mcp\", \"configureServer\");\n// Merge-append auth methods onto an integration's `authenticationTemplate`.\nexport const configureMcpAuth = McpClient.mutation(\"mcp\", \"configureAuth\");\n","import { createPluginAtomClient } from \"@executor-js/sdk/client\";\nimport {\n getExecutorApiBaseUrl,\n getExecutorServerAuthorizationHeader,\n} from \"@executor-js/react/api/server-connection\";\nimport { McpGroup } from \"../api/group\";\n\nexport const McpClient = createPluginAtomClient(McpGroup, {\n baseUrl: getExecutorApiBaseUrl,\n authorizationHeader: getExecutorServerAuthorizationHeader,\n});\n","import { HttpApiEndpoint, HttpApiGroup } from \"effect/unstable/httpapi\";\nimport { Schema } from \"effect\";\nimport {\n IntegrationSlug,\n InternalError,\n IntegrationAlreadyExistsError,\n} from \"@executor-js/sdk/shared\";\n\nimport { McpConnectionError, McpToolDiscoveryError } from \"../sdk/errors\";\nimport {\n McpAuthMethod,\n McpAuthMethodInput,\n McpAuthShorthand,\n McpIntegrationConfig,\n} from \"../sdk/types\";\n\n// ---------------------------------------------------------------------------\n// Params\n// ---------------------------------------------------------------------------\n\nconst SlugParams = { slug: IntegrationSlug };\n\nconst StringMap = Schema.Record(Schema.String, Schema.String);\n\n// ---------------------------------------------------------------------------\n// Add server — discriminated union on transport. An MCP server is registered\n// as an integration; connections (credentials) are created separately through\n// the core connections / oauth surface.\n// ---------------------------------------------------------------------------\n\nconst AddRemoteServerPayload = Schema.Struct({\n transport: Schema.optional(Schema.Literal(\"remote\")),\n name: Schema.String,\n endpoint: Schema.String,\n remoteTransport: Schema.optional(Schema.Literals([\"streamable-http\", \"sse\", \"auto\"])),\n slug: Schema.optional(Schema.String),\n queryParams: Schema.optional(StringMap),\n headers: Schema.optional(StringMap),\n /** Declared auth methods a connection can be applied through. */\n authenticationTemplate: Schema.optional(Schema.Array(McpAuthMethodInput)),\n /** Single-method shorthand (legacy callers); ignored when\n * `authenticationTemplate` is present. */\n auth: Schema.optional(McpAuthShorthand),\n});\n\nconst AddStdioServerPayload = Schema.Struct({\n transport: Schema.Literal(\"stdio\"),\n name: Schema.String,\n command: Schema.String,\n args: Schema.optional(Schema.Array(Schema.String)),\n env: Schema.optional(StringMap),\n cwd: Schema.optional(Schema.String),\n slug: Schema.optional(Schema.String),\n});\n\nconst AddServerPayload = Schema.Union([AddRemoteServerPayload, AddStdioServerPayload]);\n\nconst ProbeEndpointPayload = Schema.Struct({\n endpoint: Schema.String,\n headers: Schema.optional(StringMap),\n queryParams: Schema.optional(StringMap),\n});\n\nconst ProbeEndpointResponse = Schema.Struct({\n connected: Schema.Boolean,\n requiresAuthentication: Schema.Boolean,\n requiresOAuth: Schema.Boolean,\n supportsDynamicRegistration: Schema.Boolean,\n name: Schema.String,\n slug: Schema.String,\n toolCount: Schema.NullOr(Schema.Number),\n serverName: Schema.NullOr(Schema.String),\n});\n\n// ---------------------------------------------------------------------------\n// Responses\n// ---------------------------------------------------------------------------\n\nconst AddServerResponse = Schema.Struct({\n slug: Schema.String,\n});\n\nconst RemoveServerResponse = Schema.Struct({\n removed: Schema.Boolean,\n});\n\nconst ConfigureServerPayload = Schema.Struct({\n config: McpIntegrationConfig,\n});\n\nconst ConfigureServerResponse = Schema.Struct({\n config: McpIntegrationConfig,\n});\n\n// The configureAuth payload/response — custom auth methods to merge-append\n// onto the integration's `authenticationTemplate` (or `replace` the set).\n// Mirrors the GraphQL/OpenAPI configure endpoints.\nconst ConfigureAuthPayload = Schema.Struct({\n authenticationTemplate: Schema.Array(McpAuthMethodInput),\n mode: Schema.optional(Schema.Literals([\"merge\", \"replace\"])),\n});\n\nconst ConfigureAuthResponse = Schema.Struct({\n authenticationTemplate: Schema.Array(McpAuthMethod),\n});\n\nconst GetServerResponse = Schema.NullOr(\n Schema.Struct({\n slug: IntegrationSlug,\n description: Schema.String,\n kind: Schema.String,\n canRemove: Schema.Boolean,\n canRefresh: Schema.Boolean,\n config: McpIntegrationConfig,\n }),\n);\n\n// ---------------------------------------------------------------------------\n// Group\n//\n// Integrations are tenant-level (no scope segment); plugin domain errors carry\n// their own `HttpApiSchema` status (4xx). `InternalError` is the shared opaque\n// 500 translated at the HTTP edge.\n// ---------------------------------------------------------------------------\n\nexport const McpGroup = HttpApiGroup.make(\"mcp\")\n .add(\n HttpApiEndpoint.post(\"probeEndpoint\", \"/mcp/probe\", {\n payload: ProbeEndpointPayload,\n success: ProbeEndpointResponse,\n error: [InternalError, McpConnectionError, McpToolDiscoveryError],\n }),\n )\n .add(\n HttpApiEndpoint.post(\"addServer\", \"/mcp/servers\", {\n payload: AddServerPayload,\n success: AddServerResponse,\n error: [\n InternalError,\n McpConnectionError,\n McpToolDiscoveryError,\n IntegrationAlreadyExistsError,\n ],\n }),\n )\n .add(\n HttpApiEndpoint.delete(\"removeServer\", \"/mcp/servers/:slug\", {\n params: SlugParams,\n success: RemoveServerResponse,\n error: [InternalError, McpConnectionError, McpToolDiscoveryError],\n }),\n )\n .add(\n HttpApiEndpoint.get(\"getServer\", \"/mcp/servers/:slug\", {\n params: SlugParams,\n success: GetServerResponse,\n error: [InternalError, McpConnectionError, McpToolDiscoveryError],\n }),\n )\n .add(\n HttpApiEndpoint.post(\"configureServer\", \"/mcp/servers/:slug/config\", {\n params: SlugParams,\n payload: ConfigureServerPayload,\n success: ConfigureServerResponse,\n error: [InternalError, McpConnectionError, McpToolDiscoveryError],\n }),\n )\n .add(\n HttpApiEndpoint.post(\"configureAuth\", \"/mcp/servers/:slug/auth\", {\n params: SlugParams,\n payload: ConfigureAuthPayload,\n success: ConfigureAuthResponse,\n error: [InternalError, McpConnectionError, McpToolDiscoveryError],\n }),\n );\n","// ---------------------------------------------------------------------------\n// MCP ↔ generic auth-method converters — a thin oauth adapter over the shared\n// codec (`@executor-js/react/lib/shared-auth-method-codec`). The apikey/none\n// paths (multi-placement, multi-variable) live in the shared codec; MCP only\n// contributes its oauth flavor: endpoint-less methods whose metadata is\n// discovered at connect time (`discoveryUrl` = the MCP endpoint).\n// ---------------------------------------------------------------------------\n\nimport { AuthTemplateSlug } from \"@executor-js/sdk/shared\";\nimport type { AuthTemplateEditorValue } from \"@executor-js/react/components/auth-template-editor\";\nimport type { AuthMethod, Placement } from \"@executor-js/react/lib/auth-placements\";\nimport {\n authMethodFromSharedTemplate,\n editorValueFromSharedMethod,\n sharedMethodInputFromEditorValue,\n wirePlacementsFromEditor,\n} from \"@executor-js/react/lib/shared-auth-method-codec\";\n\nimport { wireAuthInputFromShared } from \"@executor-js/react/lib/shared-auth-method-codec\";\nimport type { McpAuthMethod, McpAuthMethodInput, McpCanonicalAuthMethodInput } from \"../sdk/types\";\n\n/** Serialize a canonical method into the wire input union (apikey → the\n * request-shaped dialect; none/oauth2 pass through). */\nexport const mcpWireAuthInput = (\n method: McpAuthMethod | McpCanonicalAuthMethodInput,\n): McpAuthMethodInput => wireAuthInputFromShared(method) as McpAuthMethodInput;\n\nconst oauthAuthMethod = (slug: string, endpoint: string): AuthMethod => ({\n id: slug,\n label: \"OAuth\",\n kind: \"oauth\",\n source: slug.startsWith(\"custom_\") ? \"custom\" : \"spec\",\n template: AuthTemplateSlug.make(slug),\n placements: [],\n oauth: { discoveryUrl: endpoint, supportsDynamicRegistration: true },\n});\n\n/** Convert a generic editor value into one MCP auth-method input (no slug —\n * the backend assigns carrier-derived slugs). An apikey value keeps every\n * named placement (headers and query params mix freely); one with no usable\n * placement falls back to `none`. */\nexport function mcpAuthMethodInputFromEditorValue(\n value: AuthTemplateEditorValue,\n): McpCanonicalAuthMethodInput {\n if (value.kind === \"oauth\") return { kind: \"oauth2\" };\n return (sharedMethodInputFromEditorValue(value) ?? {\n kind: \"none\",\n }) as McpCanonicalAuthMethodInput;\n}\n\n/** Convert one stored MCP method into the generic editor value. */\nexport function editorValueFromMcpAuthMethod(method: McpAuthMethod): AuthTemplateEditorValue {\n if (method.kind === \"oauth2\") {\n return { kind: \"oauth\", authorizationUrl: \"\", tokenUrl: \"\", scopes: [] };\n }\n return editorValueFromSharedMethod(method);\n}\n\n/** Project the stored methods into the generic `AuthMethod[]` the hub renders.\n * Mirrors the server's `describeMcpAuthMethods`; `custom_` slugs mark\n * user-created methods (removable from the hub). `endpoint` feeds the oauth\n * method's probe-at-connect `discoveryUrl`. */\nexport function authMethodsFromConfig(\n methods: readonly McpAuthMethod[],\n endpoint: string,\n): AuthMethod[] {\n return methods.map((method: McpAuthMethod): AuthMethod => {\n if (method.kind === \"oauth2\") return oauthAuthMethod(method.slug, endpoint);\n return authMethodFromSharedTemplate(method);\n });\n}\n\n/** Build the MCP method input for a custom method from generic placements —\n * ONE method carrying every named placement (header + query mix in a single\n * method; each placement renders from its own input variable, or shares one).\n * Empty when no placement is usable. */\nexport function mcpAuthMethodInputsFromPlacements(\n placements: readonly Placement[],\n): McpCanonicalAuthMethodInput[] {\n const wire = wirePlacementsFromEditor(placements);\n if (wire.length === 0) return [];\n return [{ kind: \"apikey\", placements: wire }];\n}\n"],"mappings":";;;;;;;;;;AACA,SAAS,qBAAqB;;;ACD9B,SAAS,8BAA8B;AACvC;AAAA,EACE;AAAA,EACA;AAAA,OACK;;;ACJP,SAAS,iBAAiB,oBAAoB;AAC9C,SAAS,cAAc;AACvB;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAcP,IAAM,aAAa,EAAE,MAAM,gBAAgB;AAE3C,IAAM,YAAY,OAAO,OAAO,OAAO,QAAQ,OAAO,MAAM;AAQ5D,IAAM,yBAAyB,OAAO,OAAO;AAAA,EAC3C,WAAW,OAAO,SAAS,OAAO,QAAQ,QAAQ,CAAC;AAAA,EACnD,MAAM,OAAO;AAAA,EACb,UAAU,OAAO;AAAA,EACjB,iBAAiB,OAAO,SAAS,OAAO,SAAS,CAAC,mBAAmB,OAAO,MAAM,CAAC,CAAC;AAAA,EACpF,MAAM,OAAO,SAAS,OAAO,MAAM;AAAA,EACnC,aAAa,OAAO,SAAS,SAAS;AAAA,EACtC,SAAS,OAAO,SAAS,SAAS;AAAA;AAAA,EAElC,wBAAwB,OAAO,SAAS,OAAO,MAAM,kBAAkB,CAAC;AAAA;AAAA;AAAA,EAGxE,MAAM,OAAO,SAAS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AAA,EACzE;AACA,SAAO,4BAA4B,MAAM;AAC3C;AAMO,SAAS,sBACd,SACA,UACc;AACd,SAAO,QAAQ,IAAI,CAAC,WAAsC;AACxD,QAAI,OAAO,SAAS,SAAU,QAAO,gBAAgB,OAAO,MAAM,QAAQ;AAC1E,WAAO,6BAA6B,MAAM;AAAA,EAC5C,CAAC;AACH;AAMO,SAAS,kCACd,YAC+B;AAC/B,QAAM,OAAO,yBAAyB,UAAU;AAChD,MAAI,KAAK,WAAW,EAAG,QAAO,CAAC;AAC/B,SAAO,CAAC,EAAE,MAAM,UAAU,YAAY,KAAK,CAAC;AAC9C;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/sdk/manifest.ts","../src/sdk/plugin.ts","../src/sdk/connection.ts","../src/sdk/discover.ts","../src/sdk/invoke.ts","../src/sdk/probe-shape.ts"],"sourcesContent":["import { Option, Schema } from \"effect\";\n\nimport { McpToolAnnotations } from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Output types\n// ---------------------------------------------------------------------------\n\nexport interface McpToolManifestEntry {\n readonly toolId: string;\n readonly toolName: string;\n readonly description: string | null;\n readonly inputSchema?: unknown;\n readonly outputSchema?: unknown;\n readonly annotations?: McpToolAnnotations;\n}\n\nexport interface McpServerMetadata {\n readonly name: string | null;\n readonly version: string | null;\n}\n\nexport interface McpToolManifest {\n readonly server: McpServerMetadata | null;\n readonly tools: readonly McpToolManifestEntry[];\n}\n\n// ---------------------------------------------------------------------------\n// Schemas\n// ---------------------------------------------------------------------------\n\nconst ListedTool = Schema.Struct({\n name: Schema.String,\n description: Schema.optional(Schema.NullOr(Schema.String)),\n inputSchema: Schema.optional(Schema.Unknown),\n parameters: Schema.optional(Schema.Unknown),\n outputSchema: Schema.optional(Schema.Unknown),\n annotations: Schema.optional(McpToolAnnotations),\n});\n\nconst ListToolsResult = Schema.Struct({\n tools: Schema.Array(ListedTool),\n});\n\nconst ServerInfo = Schema.Struct({\n name: Schema.optional(Schema.String),\n version: Schema.optional(Schema.String),\n});\n\nconst decodeListToolsResult = Schema.decodeUnknownOption(ListToolsResult);\nconst decodeServerInfo = Schema.decodeUnknownOption(ServerInfo);\n\nexport const isListToolsResult = (value: unknown): boolean =>\n Option.isSome(decodeListToolsResult(value));\n\n// ---------------------------------------------------------------------------\n// Tool ID sanitization\n// ---------------------------------------------------------------------------\n\nconst sanitize = (value: string): string => {\n const s = value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n return s || \"tool\";\n};\n\nconst uniqueId = (value: string, seen: Map<string, number>): string => {\n const base = sanitize(value);\n const n = (seen.get(base) ?? 0) + 1;\n seen.set(base, n);\n return n === 1 ? base : `${base}_${n}`;\n};\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport const joinToolPath = (namespace: string | undefined, toolId: string): string =>\n namespace?.trim() ? `${namespace}.${toolId}` : toolId;\n\nexport const extractManifestFromListToolsResult = (\n listToolsResult: unknown,\n metadata?: { serverInfo?: unknown },\n): McpToolManifest => {\n const seen = new Map<string, number>();\n\n const listed = decodeListToolsResult(listToolsResult).pipe(\n Option.map((result) => result.tools),\n Option.getOrElse(() => []),\n );\n\n const server = decodeServerInfo(metadata?.serverInfo).pipe(\n Option.map(\n (info): McpServerMetadata => ({\n name: info.name ?? null,\n version: info.version ?? null,\n }),\n ),\n Option.getOrNull,\n );\n\n const tools = listed.flatMap((tool): McpToolManifestEntry[] => {\n const toolName = tool.name.trim();\n if (!toolName) return [];\n\n return [\n {\n toolId: uniqueId(toolName, seen),\n toolName,\n description: tool.description ?? null,\n inputSchema: tool.inputSchema ?? tool.parameters,\n outputSchema: tool.outputSchema,\n annotations: tool.annotations,\n },\n ];\n });\n\n return { server, tools };\n};\n\n// ---------------------------------------------------------------------------\n// Namespace derivation\n// ---------------------------------------------------------------------------\n\nconst slugify = (value: string): string =>\n value\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"_\")\n .replace(/^_+|_+$/g, \"\");\n\nconst hostnameOf = (url: string): string | null => {\n if (!URL.canParse(url)) return null;\n return new URL(url).hostname;\n};\n\nconst basenameOf = (path: string): string => path.trim().split(/[\\\\/]/).pop() ?? path.trim();\n\nexport const deriveMcpNamespace = (input: {\n name?: string | null;\n endpoint?: string | null;\n command?: string | null;\n}): string => {\n if (input.name?.trim()) return slugify(input.name) || \"mcp\";\n\n const fromEndpoint = input.endpoint?.trim() ? hostnameOf(input.endpoint) : null;\n if (fromEndpoint) return slugify(fromEndpoint) || \"mcp\";\n\n if (input.command?.trim()) return slugify(basenameOf(input.command)) || \"mcp\";\n\n return \"mcp\";\n};\n","import { Effect, Layer, Match, Option, Result, Schema } from \"effect\";\nimport type { HttpClient } from \"effect/unstable/http\";\n\nimport type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport { CallToolResultSchema } from \"@modelcontextprotocol/sdk/types.js\";\nimport * as z from \"zod/v4\";\n\nimport {\n authToolFailure,\n definePlugin,\n IntegrationAlreadyExistsError,\n IntegrationSlug,\n mergeAuthTemplates,\n OAuthClientSlug,\n tool,\n ToolResult,\n type AuthMethodDescriptor,\n type Integration,\n type IntegrationConfig,\n type IntegrationRecord,\n type OAuthClientSummary,\n type Owner,\n type PluginCtx,\n type StaticToolSchema,\n type StorageFailure,\n type ToolAnnotations,\n type ToolDef,\n ToolName,\n} from \"@executor-js/sdk\";\n\nimport {\n TOKEN_VARIABLE,\n describeApiKeyAuthMethod,\n describeNoneAuthMethod,\n renderAuthPlacements,\n requiredPlacementVariables,\n} from \"@executor-js/sdk/http-auth\";\n\nimport { createMcpConnector, type ConnectorInput, type McpConnector } from \"./connection\";\nimport { discoverTools } from \"./discover\";\nimport { McpConnectionError, McpToolDiscoveryError } from \"./errors\";\nimport { invokeMcpTool } from \"./invoke\";\nimport { deriveMcpNamespace, type McpToolManifestEntry } from \"./manifest\";\nimport { mcpPresets } from \"./presets\";\nimport { probeMcpEndpointShape, type McpShapeProbeResult } from \"./probe-shape\";\nimport {\n McpAuthMethodInput,\n McpAuthShorthand,\n McpRemoteTransport,\n type McpAuthMethod,\n type McpToolAnnotations,\n expandMcpAuthMethodInputs,\n mcpAuthMethodFromShorthand,\n normalizeMcpAuthMethods,\n parseMcpIntegrationConfig,\n type McpIntegrationConfig as McpIntegrationConfigType,\n type McpRemoteIntegrationConfig,\n type McpStdioIntegrationConfig,\n} from \"./types\";\n\nconst MCP_PLUGIN_ID = \"mcp\" as const;\n\nconst legacyOAuthClientSlugCandidate = (value: string): string | null => {\n const slug = value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return slug.length > 0 ? slug : null;\n};\n\nconst legacyOAuthClientSlugCandidates = (\n slug: string,\n integration: (Integration & { readonly config: IntegrationConfig }) | null,\n): ReadonlySet<string> => {\n const candidates = new Set<string>();\n const fromSlug = legacyOAuthClientSlugCandidate(slug);\n if (fromSlug) candidates.add(fromSlug);\n const fromDescription =\n integration == null ? null : legacyOAuthClientSlugCandidate(integration.description);\n if (fromDescription) candidates.add(fromDescription);\n return candidates;\n};\n\nconst oauthClientKey = (owner: Owner, slug: OAuthClientSlug): string => `${owner}:${String(slug)}`;\n\nconst legacyMcpClientMatches = (\n client: OAuthClientSummary,\n candidates: ReadonlySet<string>,\n config: McpIntegrationConfigType | null,\n): boolean => {\n if (!candidates.has(String(client.slug))) return false;\n if (\n !config ||\n config.transport !== \"remote\" ||\n !config.authenticationTemplate.some((method: McpAuthMethod) => method.kind === \"oauth2\")\n ) {\n return false;\n }\n return client.grant === \"authorization_code\" && (client.resource ?? null) === config.endpoint;\n};\n\n// ---------------------------------------------------------------------------\n// Tool annotations carry an `mcp` envelope alongside the executor's policy\n// hints. The executor persists `ToolDef.annotations` verbatim into the tool\n// row's JSON column, so the real MCP tool name + upstream annotations survive\n// to `invokeTool` / `resolveAnnotations` with no plugin-side store (resolveTools\n// has no ctx to write one anyway). The envelope is opaque to core.\n// ---------------------------------------------------------------------------\n\ninterface McpToolStamp {\n readonly toolName: string;\n readonly upstream?: McpToolAnnotations;\n}\n\ntype StampedAnnotations = ToolAnnotations & { readonly mcp: McpToolStamp };\n\nconst McpStampSchema = Schema.Struct({\n toolName: Schema.String,\n upstream: Schema.optional(\n Schema.Struct({\n title: Schema.optional(Schema.String),\n readOnlyHint: Schema.optional(Schema.Boolean),\n destructiveHint: Schema.optional(Schema.Boolean),\n idempotentHint: Schema.optional(Schema.Boolean),\n openWorldHint: Schema.optional(Schema.Boolean),\n }),\n ),\n});\nconst AnnotationsWithStamp = Schema.Struct({ mcp: McpStampSchema });\nconst decodeStamp = Schema.decodeUnknownOption(AnnotationsWithStamp);\n\nconst readStamp = (annotations: unknown): McpToolStamp | null =>\n Option.match(decodeStamp(annotations), {\n onNone: () => null,\n onSome: (decoded) => decoded.mcp,\n });\n\n// ---------------------------------------------------------------------------\n// Extension input shapes — `addServer` registers an MCP integration. A\n// connection (the credential) is then created against it via\n// `executor.connections.create` / `oauth.start`.\n// ---------------------------------------------------------------------------\n\nconst McpRemoteServerInputSchema = Schema.Struct({\n transport: Schema.optional(Schema.Literal(\"remote\")),\n name: Schema.String,\n endpoint: Schema.String,\n remoteTransport: Schema.optional(McpRemoteTransport),\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n slug: Schema.optional(Schema.String),\n /** Declared auth methods a connection can be applied through. */\n authenticationTemplate: Schema.optional(Schema.Array(McpAuthMethodInput)),\n /** Single-method shorthand (legacy callers). Ignored when\n * `authenticationTemplate` is present. Defaults to none. */\n auth: Schema.optional(McpAuthShorthand),\n});\n\nconst McpStdioServerInputSchema = Schema.Struct({\n transport: Schema.Literal(\"stdio\"),\n name: Schema.String,\n command: Schema.String,\n args: Schema.optional(Schema.Array(Schema.String)),\n env: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n cwd: Schema.optional(Schema.String),\n slug: Schema.optional(Schema.String),\n});\n\nconst McpAddServerInputSchema = Schema.Union([\n McpRemoteServerInputSchema,\n McpStdioServerInputSchema,\n]);\n\nconst McpAddServerOutputSchema = Schema.Struct({\n slug: Schema.String,\n});\n\n/** Input for the custom-method-create flow. `merge` (default) appends onto the\n * integration's existing `authenticationTemplate`; `replace` swaps the whole\n * declared set. Mirrors the OpenAPI/GraphQL `configureAuth` inputs. */\nexport const McpConfigureAuthInputSchema = Schema.Struct({\n authenticationTemplate: Schema.Array(McpAuthMethodInput),\n mode: Schema.optional(Schema.Literals([\"merge\", \"replace\"])),\n});\nexport type McpConfigureAuthInput = typeof McpConfigureAuthInputSchema.Type;\n\nconst McpProbeEndpointInputSchema = Schema.Struct({\n endpoint: Schema.String,\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n});\n\nconst McpProbeEndpointOutputSchema = Schema.Struct({\n connected: Schema.Boolean,\n requiresAuthentication: Schema.Boolean,\n requiresOAuth: Schema.Boolean,\n supportsDynamicRegistration: Schema.Boolean,\n name: Schema.String,\n slug: Schema.String,\n toolCount: Schema.NullOr(Schema.Number),\n serverName: Schema.NullOr(Schema.String),\n});\n\n// ---------------------------------------------------------------------------\n// Extension input/output shapes — `addServer` registers an MCP integration. A\n// connection (the credential) is then created against it via\n// `executor.connections.create` / `oauth.start`. Types are inferred from the\n// schemas above so the wire shape and the TS surface can't drift.\n// ---------------------------------------------------------------------------\n\nexport type McpRemoteServerInput = typeof McpRemoteServerInputSchema.Type;\nexport type McpStdioServerInput = typeof McpStdioServerInputSchema.Type;\nexport type McpServerInput = typeof McpAddServerInputSchema.Type;\nexport type McpProbeResult = typeof McpProbeEndpointOutputSchema.Type;\nexport type McpProbeEndpointInput = typeof McpProbeEndpointInputSchema.Type;\n\nconst McpGetServerInputSchema = Schema.Struct({\n slug: Schema.String,\n});\n\nconst McpGetServerOutputSchema = Schema.Struct({\n integration: Schema.NullOr(Schema.Unknown),\n});\n\nconst schemaToStaticToolSchema = <A, I>(schema: Schema.Decoder<A, I>): StaticToolSchema<A, I> =>\n Schema.toStandardSchemaV1(Schema.toStandardJSONSchemaV1(schema) as never) as StaticToolSchema<\n A,\n I\n >;\n\nconst McpAddServerInputStandardSchema = schemaToStaticToolSchema(McpAddServerInputSchema);\nconst McpAddServerOutputStandardSchema = schemaToStaticToolSchema(McpAddServerOutputSchema);\nconst McpProbeEndpointInputStandardSchema = schemaToStaticToolSchema(McpProbeEndpointInputSchema);\nconst McpProbeEndpointOutputStandardSchema = schemaToStaticToolSchema(McpProbeEndpointOutputSchema);\nconst McpGetServerInputStandardSchema = schemaToStaticToolSchema(McpGetServerInputSchema);\nconst McpGetServerOutputStandardSchema = schemaToStaticToolSchema(McpGetServerOutputSchema);\n\nconst mcpToolFailure = (code: string, message: string, details?: unknown) =>\n ToolResult.fail({\n code,\n message,\n ...(details === undefined ? {} : { details }),\n });\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst slugFrom = (slug: string): IntegrationSlug => IntegrationSlug.make(slug);\n\nconst normalizeSlug = (input: McpServerInput): string =>\n input.slug ??\n deriveMcpNamespace({\n name: input.name,\n endpoint: input.transport === \"stdio\" ? undefined : input.endpoint,\n command: input.transport === \"stdio\" ? input.command : undefined,\n });\n\nconst toIntegrationConfig = (input: McpServerInput): McpIntegrationConfigType => {\n if (input.transport === \"stdio\") {\n return {\n transport: \"stdio\",\n command: input.command,\n args: input.args ? [...input.args] : undefined,\n env: input.env,\n cwd: input.cwd,\n };\n }\n return {\n transport: \"remote\",\n endpoint: input.endpoint,\n remoteTransport: input.remoteTransport ?? \"auto\",\n queryParams: input.queryParams,\n headers: input.headers,\n authenticationTemplate: input.authenticationTemplate\n ? normalizeMcpAuthMethods(input.authenticationTemplate)\n : [mcpAuthMethodFromShorthand(input.auth ?? { kind: \"none\" })],\n };\n};\n\ntype JsonSchemaObject = Record<string, unknown> & {\n readonly properties?: Record<string, unknown>;\n};\n\nconst McpCallToolResultJsonSchema = z.toJSONSchema(CallToolResultSchema) as JsonSchemaObject;\n\nconst mcpCallToolResultOutputSchema = (structuredContentSchema?: unknown): JsonSchemaObject => {\n const defaultStructuredContentSchema =\n McpCallToolResultJsonSchema.properties?.structuredContent ?? {};\n\n return {\n ...McpCallToolResultJsonSchema,\n properties: {\n ...McpCallToolResultJsonSchema.properties,\n structuredContent:\n structuredContentSchema === undefined\n ? defaultStructuredContentSchema\n : structuredContentSchema,\n isError: { const: false },\n },\n required:\n structuredContentSchema === undefined ? [\"content\"] : [\"content\", \"structuredContent\"],\n };\n};\n\n/** Build the executor-facing ToolDef for one discovered MCP tool, stamping the\n * real MCP tool name + upstream annotations into the persisted annotations so\n * they survive to invokeTool with no plugin-side store. */\nconst toToolDef = (entry: McpToolManifestEntry): ToolDef => {\n const destructive = entry.annotations?.destructiveHint === true;\n const stamp: McpToolStamp = {\n toolName: entry.toolName,\n ...(entry.annotations ? { upstream: entry.annotations } : {}),\n };\n const annotations: StampedAnnotations = {\n requiresApproval: destructive,\n ...(destructive ? { approvalDescription: entry.annotations?.title ?? entry.toolName } : {}),\n mcp: stamp,\n };\n return {\n name: ToolName.make(entry.toolId),\n description: entry.description ?? `MCP tool: ${entry.toolName}`,\n inputSchema: entry.inputSchema,\n outputSchema: mcpCallToolResultOutputSchema(entry.outputSchema),\n annotations: annotations as ToolAnnotations,\n };\n};\n\nconst McpTextContent = Schema.Struct({ type: Schema.Literal(\"text\"), text: Schema.String });\nconst McpToolCallEnvelope = Schema.Struct({\n isError: Schema.optional(Schema.Boolean),\n content: Schema.optional(Schema.Array(Schema.Unknown)),\n});\n\nconst decodeMcpTextContent = Schema.decodeUnknownOption(McpTextContent);\nconst decodeMcpToolCallEnvelope = Schema.decodeUnknownOption(McpToolCallEnvelope);\n\nconst extractMcpErrorMessage = (content: unknown): string => {\n if (Array.isArray(content)) {\n for (const item of content) {\n const decoded = Option.getOrUndefined(decodeMcpTextContent(item));\n if (decoded !== undefined && decoded.text.length > 0) return decoded.text;\n }\n }\n return \"MCP tool returned an error\";\n};\n\n/** Match `token` as a separator-bounded run inside a URL hostname or path,\n * used as a low-confidence detection hint when wire-shape detection fails. */\nconst urlMatchesToken = (url: URL, token: string): boolean => {\n const re = new RegExp(`(?:^|[^a-z0-9])${token}(?:$|[^a-z0-9])`, \"i\");\n return re.test(url.hostname) || re.test(url.pathname);\n};\n\n/** Translate a non-MCP probe outcome into a message a user can act on.\n * Exported for tests. */\nexport const userFacingProbeMessage = (\n shape: Extract<McpShapeProbeResult, { kind: \"not-mcp\" } | { kind: \"unreachable\" }>,\n): string => {\n if (shape.kind === \"unreachable\") {\n return \"Couldn't reach this URL. Check the address, your network, and that the server is running.\";\n }\n return Match.value(shape.category).pipe(\n Match.when(\n \"auth-required\",\n () =>\n \"This server requires authentication. Add credentials (Authorization header, query parameter, or API key) below and retry.\",\n ),\n Match.when(\n \"wrong-shape\",\n () =>\n \"This URL doesn't appear to host an MCP server. Double-check the address, including the path.\",\n ),\n Match.exhaustive,\n );\n};\n\n// ---------------------------------------------------------------------------\n// MCP-SDK OAuth provider adapter — wraps a pre-resolved access token so the\n// transport sends it as a Bearer header. Refresh is core's responsibility\n// (the connection row carries the OAuth grant); this adapter never initiates\n// a new flow and fails loudly if the SDK tries to.\n// ---------------------------------------------------------------------------\n\nconst makeOAuthProvider = (accessToken: string): OAuthClientProvider => ({\n get redirectUrl() {\n return \"http://localhost/oauth/callback\";\n },\n get clientMetadata() {\n return {\n redirect_uris: [\"http://localhost/oauth/callback\"],\n grant_types: [\"authorization_code\", \"refresh_token\"] as string[],\n response_types: [\"code\"] as string[],\n token_endpoint_auth_method: \"none\" as const,\n client_name: \"Executor\",\n };\n },\n clientInformation: () => undefined,\n saveClientInformation: () => undefined,\n tokens: () => ({ access_token: accessToken, token_type: \"Bearer\" }),\n saveTokens: () => undefined,\n redirectToAuthorization: async () => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- boundary: MCP SDK OAuthClientProvider callback can only signal reauthorization by throwing\n throw new Error(\"MCP OAuth re-authorization required\");\n },\n saveCodeVerifier: () => undefined,\n codeVerifier: () => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- boundary: MCP SDK OAuthClientProvider callback requires a thrown verifier failure\n throw new Error(\"No active PKCE verifier\");\n },\n saveDiscoveryState: () => undefined,\n discoveryState: () => undefined,\n});\n\n// ---------------------------------------------------------------------------\n// Connector input — render the integration config + the connection's resolved\n// value through the auth method the connection references (by template slug)\n// into a live `ConnectorInput`.\n// ---------------------------------------------------------------------------\n\n/** The auth method a connection binds: its `template` slug when it matches a\n * declared method. Otherwise fall back to the sole declared method — single-\n * method integrations historically accepted any template slug (rendering was\n * config-driven), so existing connections keep working. Ambiguity across\n * several methods renders no auth rather than guessing. */\nconst selectAuthMethod = (\n config: McpRemoteIntegrationConfig,\n templateSlug: string | null,\n): McpAuthMethod | undefined => {\n const methods = config.authenticationTemplate;\n if (templateSlug !== null) {\n const match = methods.find((method: McpAuthMethod) => method.slug === templateSlug);\n if (match) return match;\n }\n return methods.length === 1 ? methods[0] : undefined;\n};\n\nconst buildConnectorInput = (\n config: McpIntegrationConfigType,\n values: Record<string, string | null>,\n templateSlug: string | null,\n allowStdio: boolean,\n): Effect.Effect<ConnectorInput, McpConnectionError> => {\n if (config.transport === \"stdio\") {\n if (!allowStdio) {\n return Effect.fail(\n new McpConnectionError({\n transport: \"stdio\",\n message:\n \"MCP stdio transport is disabled. Enable it by passing `dangerouslyAllowStdioMCP: true` to mcpPlugin() — only safe for trusted local contexts.\",\n }),\n );\n }\n return Effect.succeed({\n transport: \"stdio\" as const,\n command: config.command,\n args: config.args,\n env: config.env,\n cwd: config.cwd,\n } satisfies McpStdioIntegrationConfig);\n }\n\n // Credential placements render OVER the integration's static headers /\n // query params — a same-named static entry is overwritten.\n const headers: Record<string, string> = { ...(config.headers ?? {}) };\n const queryParams: Record<string, string> = { ...(config.queryParams ?? {}) };\n let authProvider: OAuthClientProvider | undefined;\n\n const auth = selectAuthMethod(config, templateSlug);\n if (auth?.kind === \"apikey\") {\n const rendered = renderAuthPlacements(auth.placements, values);\n Object.assign(headers, rendered.headers);\n Object.assign(queryParams, rendered.queryParams);\n } else if (auth?.kind === \"oauth2\") {\n const token = values[TOKEN_VARIABLE];\n if (token != null) authProvider = makeOAuthProvider(token);\n }\n\n return Effect.succeed({\n transport: \"remote\" as const,\n endpoint: config.endpoint,\n remoteTransport: config.remoteTransport ?? \"auto\",\n queryParams: Object.keys(queryParams).length > 0 ? queryParams : undefined,\n headers: Object.keys(headers).length > 0 ? headers : undefined,\n authProvider,\n });\n};\n\n// ---------------------------------------------------------------------------\n// Declared auth methods — project the stored MCP config into the catalog's\n// plugin-agnostic `AuthMethodDescriptor[]`, one per declared method. Pure and\n// tolerant of a malformed or foreign config blob (returns `[]`). Exported for\n// tests.\n//\n// none → a no-auth method carrying no credential inputs\n// stdio → [] (no remote connection to configure)\n// apikey → carried placements (headers / query params) verbatim\n// oauth2 → an oauth method carrying the MCP endpoint to probe\n// (`discoveryUrl`); endpoints are discovered live at\n// connect time, so they are NOT pre-resolved here. We\n// mark `supportsDynamicRegistration: true` because MCP\n// OAuth servers are expected to support RFC 7591 DCR;\n// the connect flow probes to confirm and falls back.\n// ---------------------------------------------------------------------------\n\nexport const describeMcpAuthMethods = (\n record: IntegrationRecord,\n): readonly AuthMethodDescriptor[] => {\n const config = parseMcpIntegrationConfig(record.config);\n if (!config || config.transport === \"stdio\") return [];\n\n return config.authenticationTemplate.map((method: McpAuthMethod): AuthMethodDescriptor => {\n if (method.kind === \"apikey\") return describeApiKeyAuthMethod(method);\n if (method.kind === \"oauth2\") {\n return {\n id: method.slug,\n label: \"OAuth\",\n kind: \"oauth\",\n template: method.slug,\n oauth: { discoveryUrl: config.endpoint, supportsDynamicRegistration: true },\n };\n }\n return describeNoneAuthMethod(method.slug);\n });\n};\n\nexport const describeMcpIntegrationDisplay = (\n record: IntegrationRecord,\n): { readonly url?: string } => {\n const config = parseMcpIntegrationConfig(record.config);\n if (!config || config.transport === \"stdio\") return {};\n return { url: config.endpoint };\n};\n\n// ---------------------------------------------------------------------------\n// Plugin factory\n// ---------------------------------------------------------------------------\n\nexport interface McpPluginOptions {\n /**\n * Allow configuring stdio-transport MCP servers. Off by default.\n *\n * Stdio servers spawn a local subprocess that inherits the parent\n * `process.env`. Only enable for trusted single-user contexts.\n */\n readonly dangerouslyAllowStdioMCP?: boolean;\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n}\n\nexport const mcpPlugin = definePlugin((options?: McpPluginOptions) => {\n const allowStdio = options?.dangerouslyAllowStdioMCP ?? false;\n\n const presetEntries = (\n allowStdio\n ? mcpPresets\n : mcpPresets.filter((preset) => !(\"transport\" in preset && preset.transport === \"stdio\"))\n ).map((preset) => ({\n id: preset.id,\n name: preset.name,\n summary: preset.summary,\n ...(\"url\" in preset && preset.url ? { url: preset.url } : {}),\n ...(\"endpoint\" in preset && preset.endpoint ? { endpoint: preset.endpoint } : {}),\n ...(preset.icon ? { icon: preset.icon } : {}),\n ...(preset.featured ? { featured: preset.featured } : {}),\n transport: (\"transport\" in preset && preset.transport === \"stdio\" ? \"stdio\" : \"remote\") as\n | \"stdio\"\n | \"remote\",\n ...(\"command\" in preset ? { command: preset.command } : {}),\n ...(\"args\" in preset && preset.args ? { args: [...preset.args] } : {}),\n ...(\"env\" in preset && preset.env ? { env: preset.env } : {}),\n }));\n\n return {\n id: MCP_PLUGIN_ID,\n packageName: \"@executor-js/plugin-mcp\",\n integrationPresets: presetEntries,\n // Surfaced to the client bundle via the Vite plugin. The MCP `./client`\n // factory reads `allowStdio` and gates the stdio tab + presets.\n clientConfig: { allowStdio },\n storage: () => ({}),\n\n extension: (ctx: PluginCtx) => {\n const httpClientLayer = options?.httpClientLayer ?? ctx.httpClientLayer;\n\n const probeEndpoint = (input: string | McpProbeEndpointInput) =>\n Effect.gen(function* () {\n const endpoint = typeof input === \"string\" ? input : input.endpoint;\n const trimmed = endpoint.trim();\n if (!trimmed) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: \"Endpoint URL is required\",\n });\n }\n\n const name = yield* Effect.try({\n try: () => new URL(trimmed).hostname,\n catch: () => \"mcp\",\n }).pipe(Effect.orElseSucceed(() => \"mcp\"));\n const slug = deriveMcpNamespace({ endpoint: trimmed });\n\n const probeHeaders = typeof input === \"string\" ? undefined : input.headers;\n const probeQueryParams = typeof input === \"string\" ? undefined : input.queryParams;\n\n const connector = createMcpConnector({\n transport: \"remote\",\n endpoint: trimmed,\n headers: probeHeaders,\n queryParams: probeQueryParams,\n });\n\n const result = yield* discoverTools(connector).pipe(\n Effect.map((m) => ({ ok: true as const, manifest: m })),\n Effect.catch(() => Effect.succeed({ ok: false as const, manifest: null })),\n Effect.withSpan(\"mcp.plugin.discover_tools\"),\n );\n\n if (result.ok && result.manifest) {\n return {\n connected: true,\n requiresAuthentication: false,\n requiresOAuth: false,\n supportsDynamicRegistration: false,\n name: result.manifest.server?.name ?? name,\n slug,\n toolCount: result.manifest.tools.length,\n serverName: result.manifest.server?.name ?? null,\n } satisfies McpProbeResult;\n }\n\n // Confirm the endpoint actually speaks MCP before classifying it as\n // OAuth-protected (an OAuth-protected non-MCP service would\n // otherwise be misclassified).\n const shape = yield* probeMcpEndpointShape(trimmed, {\n httpClientLayer,\n headers: probeHeaders,\n queryParams: probeQueryParams,\n });\n if (shape.kind !== \"mcp\") {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: userFacingProbeMessage(shape),\n });\n }\n\n const probeResult = yield* ctx.oauth.probe({ url: trimmed }).pipe(\n Effect.map((oauth) => ({ ok: true as const, oauth })),\n Effect.catch(() => Effect.succeed({ ok: false as const, oauth: null })),\n Effect.withSpan(\"mcp.plugin.probe_oauth\"),\n );\n\n if (probeResult.ok) {\n return {\n connected: false,\n requiresAuthentication: true,\n requiresOAuth: true,\n supportsDynamicRegistration: probeResult.oauth.registrationEndpoint != null,\n name,\n slug,\n toolCount: null,\n serverName: null,\n } satisfies McpProbeResult;\n }\n\n if (shape.requiresAuth) {\n return {\n connected: false,\n requiresAuthentication: true,\n requiresOAuth: false,\n supportsDynamicRegistration: false,\n name,\n slug,\n toolCount: null,\n serverName: null,\n } satisfies McpProbeResult;\n }\n\n return yield* new McpConnectionError({\n transport: \"remote\",\n message:\n \"This endpoint looks like MCP, but Executor couldn't discover tools from it. Check the URL and try again.\",\n });\n }).pipe(\n Effect.withSpan(\"mcp.plugin.probe_endpoint\", {\n attributes: { \"mcp.endpoint\": typeof input === \"string\" ? input : input.endpoint },\n }),\n );\n\n const addServer = (input: McpServerInput) =>\n Effect.gen(function* () {\n const slug = normalizeSlug(input);\n const config = toIntegrationConfig(input);\n\n // Block re-adding an existing slug. The core `integrations.register`\n // primitive upserts (so boot re-registration is idempotent), but an\n // explicit add must NOT silently clobber an existing integration's\n // tools, connections, and policies. To add more auth, update the\n // existing integration instead.\n const existing = yield* ctx.core.integrations.get(slugFrom(slug));\n if (existing) {\n return yield* new IntegrationAlreadyExistsError({ slug: slugFrom(slug) });\n }\n\n yield* ctx.core.integrations\n .register({\n slug: slugFrom(slug),\n description: input.name,\n config,\n canRemove: true,\n canRefresh: true,\n })\n .pipe(\n Effect.withSpan(\"mcp.plugin.register_integration\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n return { slug };\n }).pipe(\n Effect.withSpan(\"mcp.plugin.add_server\", {\n attributes: {\n \"mcp.server.transport\": input.transport ?? \"remote\",\n \"mcp.server.name\": input.name,\n },\n }),\n );\n\n const removeServer = (slug: string) =>\n Effect.gen(function* () {\n const integration = slugFrom(slug);\n const record = yield* ctx.core.integrations.get(integration);\n const config = record ? parseMcpIntegrationConfig(record.config) : null;\n const legacyCandidates = legacyOAuthClientSlugCandidates(slug, record);\n const connections = yield* ctx.connections.list({ integration });\n const allConnections = yield* ctx.connections.list();\n const oauthClientSummaries = yield* ctx.oauth.listClients();\n const usedElsewhere = new Set(\n allConnections\n .filter((connection) => String(connection.integration) !== String(integration))\n .flatMap((connection) =>\n connection.oauthClient == null\n ? []\n : [\n oauthClientKey(\n connection.oauthClientOwner ?? connection.owner,\n connection.oauthClient,\n ),\n ],\n ),\n );\n const oauthClientsByKey = new Map(\n oauthClientSummaries.map((client) => [\n oauthClientKey(client.owner, client.slug),\n client,\n ]),\n );\n const clientsToRemove = new Map<\n string,\n { readonly owner: Owner; readonly slug: OAuthClientSlug }\n >();\n\n for (const connection of connections) {\n if (connection.oauthClient == null) continue;\n const owner = connection.oauthClientOwner ?? connection.owner;\n const key = oauthClientKey(owner, connection.oauthClient);\n const client = oauthClientsByKey.get(key);\n if (client?.origin.kind !== \"dynamic_client_registration\") continue;\n clientsToRemove.set(key, {\n owner,\n slug: connection.oauthClient,\n });\n }\n for (const client of oauthClientSummaries) {\n const key = oauthClientKey(client.owner, client.slug);\n if (usedElsewhere.has(key)) continue;\n if (\n client.origin.kind === \"dynamic_client_registration\" &&\n (client.origin.integration == null || String(client.origin.integration) === slug)\n ) {\n clientsToRemove.set(key, { owner: client.owner, slug: client.slug });\n continue;\n }\n if (legacyMcpClientMatches(client, legacyCandidates, config)) {\n clientsToRemove.set(key, { owner: client.owner, slug: client.slug });\n }\n }\n\n yield* ctx.core.integrations\n .remove(integration)\n .pipe(Effect.catchTag(\"IntegrationRemovalNotAllowedError\", () => Effect.void));\n\n yield* Effect.forEach(\n clientsToRemove.values(),\n (client) => ctx.oauth.removeClient(client.owner, client.slug),\n { discard: true },\n );\n }).pipe(\n Effect.withSpan(\"mcp.plugin.remove_server\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n\n const getServer = (slug: string) =>\n ctx.core.integrations.get(slugFrom(slug)).pipe(\n Effect.withSpan(\"mcp.plugin.get_server\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n\n const configureServer = (slug: string, config: McpIntegrationConfigType) =>\n ctx.core.integrations.update(slugFrom(slug), { config }).pipe(\n Effect.withSpan(\"mcp.plugin.configure_server\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n\n /** Merge-append auth methods onto the integration's existing\n * `authenticationTemplate` (custom-method-create flow), mirroring the\n * OpenAPI/GraphQL `configureAuth`. Returns the merged array. A no-op\n * (returns `[]`) for an unknown slug, a stdio server, or an\n * undecodable config. */\n const configureAuth = (slug: string, input: McpConfigureAuthInput) =>\n Effect.gen(function* () {\n const record = yield* ctx.core.integrations.get(slugFrom(slug));\n const current = record ? parseMcpIntegrationConfig(record.config) : null;\n if (!current || current.transport === \"stdio\") {\n return [] as readonly McpAuthMethod[];\n }\n\n // Replace mode declares the full set — backfill kind-based slugs.\n // Merge mode appends: `mergeAuthTemplates` replaces on slug match and\n // assigns fresh `custom_<id>` slugs to slug-less entries, so a custom\n // method never silently displaces a declared one.\n const merged =\n input.mode === \"replace\"\n ? normalizeMcpAuthMethods(input.authenticationTemplate)\n : mergeAuthTemplates(\n current.authenticationTemplate,\n expandMcpAuthMethodInputs(\n input.authenticationTemplate,\n ) as readonly McpAuthMethod[],\n );\n\n yield* ctx.core.integrations.update(slugFrom(slug), {\n config: { ...current, authenticationTemplate: merged },\n });\n\n return merged;\n }).pipe(\n Effect.withSpan(\"mcp.plugin.configure_auth\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n\n return {\n probeEndpoint,\n addServer,\n removeServer,\n getServer,\n configureServer,\n configureAuth,\n };\n },\n\n // -----------------------------------------------------------------------\n // Per-connection tool production. Dial the server using the connection's\n // resolved value (rendered through the integration's auth template) and\n // list its tools. The real MCP tool name + upstream annotations are\n // stamped into each ToolDef's annotations so invokeTool can recover them.\n // Discovery failures (auth not ready, server down) yield an empty tool set\n // rather than failing — the connection still lands and can be refreshed.\n // -----------------------------------------------------------------------\n resolveTools: ({ config, connection, template, getValues }) =>\n Effect.gen(function* () {\n const parsed = parseMcpIntegrationConfig(config);\n if (!parsed) return { tools: [] as readonly ToolDef[] };\n\n // Discovery tolerates unresolved credentials (an open server lists\n // tools unauthenticated; a bad value just yields zero tools).\n const values = yield* getValues().pipe(\n Effect.orElseSucceed(() => ({}) as Record<string, string | null>),\n );\n\n const built = yield* buildConnectorInput(\n parsed,\n values,\n template === null ? null : String(template),\n allowStdio,\n ).pipe(\n Effect.map((ci) => createMcpConnector(ci)),\n Effect.result,\n );\n\n const manifest = Result.isSuccess(built)\n ? yield* discoverTools(built.success).pipe(\n Effect.map((m) => ({ ok: true as const, manifest: m })),\n Effect.catch(() => Effect.succeed({ ok: false as const, manifest: null })),\n Effect.withSpan(\"mcp.plugin.discover_tools\", {\n attributes: { \"mcp.connection.name\": String(connection.name) },\n }),\n )\n : { ok: false as const, manifest: null };\n\n const entries = manifest.ok && manifest.manifest ? manifest.manifest.tools : [];\n return { tools: entries.map(toToolDef) };\n }).pipe(\n Effect.withSpan(\"mcp.plugin.resolve_tools\", {\n attributes: { \"mcp.connection.name\": String(connection.name) },\n }),\n ) as Effect.Effect<{ readonly tools: readonly ToolDef[] }, StorageFailure>,\n\n invokeTool: ({ toolRow, credential, args, elicit }) =>\n Effect.gen(function* () {\n const parsed = parseMcpIntegrationConfig(credential.config);\n if (!parsed) {\n return yield* new McpConnectionError({\n transport: \"auto\",\n message: `MCP integration \"${toolRow.integration}\" has no usable config`,\n });\n }\n\n const stamp = readStamp(toolRow.annotations);\n if (!stamp) {\n return yield* new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: `Tool \"${toolRow.name}\" is missing its MCP binding — refresh the connection`,\n });\n }\n\n const transport: string =\n parsed.transport === \"stdio\" ? \"stdio\" : (parsed.remoteTransport ?? \"auto\");\n\n // An apikey method with unresolved inputs fails the invocation\n // explicitly instead of dialing unauthenticated.\n if (parsed.transport === \"remote\") {\n const method = selectAuthMethod(parsed, String(credential.template));\n if (method?.kind === \"apikey\") {\n const missing = requiredPlacementVariables(method.placements).filter(\n (variable) => credential.values[variable] == null,\n );\n if (missing.length > 0) {\n return authToolFailure({\n code: \"connection_value_missing\",\n message: `Connection has no resolvable credential value for input(s): ${missing.join(\", \")}. Re-create the connection with the required value(s).`,\n source: { id: String(credential.integration) },\n credential: { kind: \"upstream\", label: String(credential.connection) },\n });\n }\n }\n }\n\n const connector: McpConnector = yield* buildConnectorInput(\n parsed,\n credential.values,\n String(credential.template),\n allowStdio,\n ).pipe(Effect.map((ci) => createMcpConnector(ci)));\n\n const raw = yield* invokeMcpTool({\n toolId: String(toolRow.name),\n toolName: stamp.toolName,\n args,\n transport,\n connector,\n elicit,\n });\n\n const envelope = Option.getOrUndefined(decodeMcpToolCallEnvelope(raw));\n if (envelope?.isError === true) {\n return ToolResult.fail({\n code: \"mcp_tool_error\",\n message: extractMcpErrorMessage(envelope.content),\n details: { content: envelope.content },\n });\n }\n return ToolResult.ok(raw);\n }).pipe(\n Effect.catchTag(\"McpConnectionError\", ({ message }) =>\n Effect.succeed(\n authToolFailure({\n code: \"connection_rejected\",\n message,\n source: { id: String(credential.integration) },\n credential: { kind: \"upstream\", label: String(credential.connection) },\n }),\n ),\n ),\n Effect.withSpan(\"mcp.plugin.invoke_tool\", {\n attributes: {\n \"mcp.tool.name\": String(toolRow.name),\n \"mcp.integration.slug\": String(toolRow.integration),\n },\n }),\n ),\n\n detect: ({ ctx, url }: { readonly ctx: PluginCtx; readonly url: string }) =>\n Effect.gen(function* () {\n const httpClientLayer = options?.httpClientLayer ?? ctx.httpClientLayer;\n const trimmed = url.trim();\n if (!trimmed) return null;\n\n const parsed = yield* Effect.try({\n try: () => new URL(trimmed),\n catch: (cause) => cause,\n }).pipe(Effect.option);\n if (Option.isNone(parsed)) return null;\n\n const name = parsed.value.hostname || \"mcp\";\n const slug = deriveMcpNamespace({ endpoint: trimmed });\n\n const connector = createMcpConnector({ transport: \"remote\", endpoint: trimmed });\n\n const connected = yield* discoverTools(connector).pipe(\n Effect.map(() => true),\n Effect.catch(() => Effect.succeed(false)),\n Effect.withSpan(\"mcp.plugin.discover_tools\"),\n );\n\n if (connected) {\n return {\n kind: MCP_PLUGIN_ID,\n confidence: \"high\" as const,\n endpoint: trimmed,\n name,\n slug,\n };\n }\n\n const shape = yield* probeMcpEndpointShape(trimmed, { httpClientLayer });\n if (shape.kind === \"mcp\") {\n return {\n kind: MCP_PLUGIN_ID,\n confidence: \"high\" as const,\n endpoint: trimmed,\n name,\n slug,\n };\n }\n\n // Low-confidence URL-token fallback when wire-shape detection can't\n // confirm MCP but the URL itself is a strong hint.\n if (urlMatchesToken(parsed.value, \"mcp\")) {\n return {\n kind: MCP_PLUGIN_ID,\n confidence: \"low\" as const,\n endpoint: trimmed,\n name,\n slug,\n };\n }\n\n return null;\n }).pipe(\n Effect.catch(() => Effect.succeed(null)),\n Effect.withSpan(\"mcp.plugin.detect\", {\n attributes: { \"mcp.endpoint\": url },\n }),\n ),\n\n // Honour upstream destructiveHint from MCP ToolAnnotations using the stamp\n // persisted in each tool row's annotations.\n resolveAnnotations: ({ toolRows }) =>\n Effect.sync(() => {\n const out: Record<string, ToolAnnotations> = {};\n for (const row of toolRows) {\n const stamp = readStamp(row.annotations);\n const ann = stamp?.upstream;\n if (ann?.destructiveHint === true) {\n out[String(row.name)] = {\n requiresApproval: true,\n approvalDescription: ann.title ?? stamp?.toolName ?? String(row.name),\n };\n } else {\n out[String(row.name)] = { requiresApproval: false };\n }\n }\n return out;\n }),\n\n describeAuthMethods: describeMcpAuthMethods,\n describeIntegrationDisplay: describeMcpIntegrationDisplay,\n\n integrationConfigure: {\n type: \"mcp\",\n configure: ({ ctx, integration, config }) =>\n Effect.gen(function* () {\n const next = parseMcpIntegrationConfig(config);\n if (!next) return;\n yield* ctx.core.integrations.update(integration, { config: next });\n }),\n },\n\n staticSources: (self) => [\n {\n id: \"mcp\",\n kind: \"executor\",\n name: \"MCP\",\n tools: [\n tool({\n name: \"probeEndpoint\",\n description:\n \"Probe a remote MCP endpoint before adding it. If the result requires OAuth, run the core OAuth handoff (`oauth.probe`, `oauth.start`) to mint a connection; otherwise create a connection with `connections.create` carrying the API key or header value.\",\n inputSchema: McpProbeEndpointInputStandardSchema,\n outputSchema: McpProbeEndpointOutputStandardSchema,\n execute: (input) =>\n self.probeEndpoint(input as McpProbeEndpointInput).pipe(\n Effect.map(ToolResult.ok),\n Effect.catchTag(\"McpConnectionError\", ({ message, transport }) =>\n Effect.succeed(mcpToolFailure(\"mcp_connection_failed\", message, { transport })),\n ),\n ),\n }),\n tool({\n name: \"getServer\",\n description:\n \"Inspect a registered MCP integration, including transport, endpoint/command, and auth template. Use this before creating a connection (`connections.create` / `oauth.start`).\",\n inputSchema: McpGetServerInputStandardSchema,\n outputSchema: McpGetServerOutputStandardSchema,\n execute: (input) => {\n const args = input as typeof McpGetServerInputSchema.Type;\n return Effect.map(self.getServer(args.slug), (integration) =>\n ToolResult.ok({ integration }),\n );\n },\n }),\n tool({\n name: \"addServer\",\n description:\n \"Register an MCP server in the catalog as an integration. Returns its `slug`. Then create a connection against it: for header/API-key auth call `connections.create` with the value; for OAuth-protected servers run `oauth.probe` + `oauth.start`. Tools are produced per-connection at connection create / refresh.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Add an MCP server\",\n },\n inputSchema: McpAddServerInputStandardSchema,\n outputSchema: McpAddServerOutputStandardSchema,\n execute: (rawInput) => {\n const input = rawInput as typeof McpAddServerInputSchema.Type;\n return self.addServer(input as McpServerInput).pipe(\n Effect.map(ToolResult.ok),\n Effect.catchTag(\n \"IntegrationAlreadyExistsError\",\n ({ slug }: IntegrationAlreadyExistsError) =>\n Effect.succeed(\n mcpToolFailure(\n \"integration_already_exists\",\n `Integration ${slug} already exists; update it instead of re-adding.`,\n ),\n ),\n ),\n );\n },\n }),\n ],\n },\n ],\n };\n});\n\n// ---------------------------------------------------------------------------\n// McpPluginExtension — shape of `executor.mcp` for consumers (api/, react/).\n// ---------------------------------------------------------------------------\n\nexport type McpExtensionFailure = McpConnectionError | McpToolDiscoveryError | StorageFailure;\n\nexport interface McpPluginExtension {\n readonly probeEndpoint: (\n input: string | McpProbeEndpointInput,\n ) => Effect.Effect<McpProbeResult, McpExtensionFailure>;\n readonly addServer: (\n input: McpServerInput,\n ) => Effect.Effect<\n { readonly slug: string },\n McpExtensionFailure | IntegrationAlreadyExistsError\n >;\n readonly removeServer: (slug: string) => Effect.Effect<void, McpExtensionFailure>;\n readonly getServer: (\n slug: string,\n ) => Effect.Effect<\n (Integration & { readonly config: IntegrationConfig }) | null,\n McpExtensionFailure\n >;\n readonly configureServer: (\n slug: string,\n config: McpIntegrationConfigType,\n ) => Effect.Effect<void, McpExtensionFailure>;\n readonly configureAuth: (\n slug: string,\n input: McpConfigureAuthInput,\n ) => Effect.Effect<readonly McpAuthMethod[], McpExtensionFailure>;\n}\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/sdk/validation/cfworker\";\nimport { Effect } from \"effect\";\n\n// NOTE: `StdioClientTransport` is NOT imported eagerly. The upstream module\n// (`@modelcontextprotocol/sdk/client/stdio.js`) touches `node:child_process`\n// at evaluation time, which crashes workerd (incl. vitest-pool-workers) at\n// SIGSEGV on module instantiation. Cloud callers set\n// `dangerouslyAllowStdioMCP: false` and never reach the stdio branch below;\n// prod bundles that DO use stdio load it via a dynamic import inside the\n// stdio branch of `createMcpConnector`.\n\nimport type { McpRemoteIntegrationConfig, McpStdioIntegrationConfig } from \"./types\";\nimport { McpConnectionError } from \"./errors\";\n\n// ---------------------------------------------------------------------------\n// Connection type\n// ---------------------------------------------------------------------------\n\nexport type McpConnection = {\n readonly client: Client;\n readonly close: () => Promise<void>;\n};\n\nexport type McpConnector = Effect.Effect<McpConnection, McpConnectionError>;\n\n// ---------------------------------------------------------------------------\n// Connector input — extends stored source data with resolved auth\n// ---------------------------------------------------------------------------\n\nexport type RemoteConnectorInput = Omit<\n McpRemoteIntegrationConfig,\n \"authenticationTemplate\" | \"remoteTransport\" | \"headers\" | \"queryParams\"\n> & {\n readonly remoteTransport?: McpRemoteIntegrationConfig[\"remoteTransport\"];\n readonly headers?: Record<string, string>;\n readonly queryParams?: Record<string, string>;\n readonly authProvider?: OAuthClientProvider;\n};\n\nexport type StdioConnectorInput = McpStdioIntegrationConfig;\n\nexport type ConnectorInput = RemoteConnectorInput | StdioConnectorInput;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst buildEndpointUrl = (endpoint: string, queryParams: Record<string, string>): URL => {\n const url = new URL(endpoint);\n for (const [key, value] of Object.entries(queryParams)) {\n url.searchParams.set(key, value);\n }\n return url;\n};\n\n// Use the cfworker JSON Schema validator instead of the SDK's default\n// (Ajv). Ajv compiles schemas via `new Function(...)`, which throws\n// `Code generation from strings disallowed for this context` when the\n// MCP plugin runs inside a Cloudflare Worker (executor.sh). The\n// cfworker validator does not use code generation and works in every\n// runtime we ship to.\nconst createClient = (): Client =>\n new Client(\n { name: \"executor-mcp\", version: \"0.1.0\" },\n {\n capabilities: { elicitation: { form: {}, url: {} } },\n jsonSchemaValidator: new CfWorkerJsonSchemaValidator(),\n },\n );\n\nconst connectionFromClient = (client: Client): McpConnection => ({\n client,\n close: () => client.close(),\n});\n\nconst connectClient = (input: {\n transport: string;\n createTransport: () => Parameters<Client[\"connect\"]>[0];\n}): Effect.Effect<McpConnection, McpConnectionError> =>\n Effect.gen(function* () {\n const client = createClient();\n const transportInstance = input.createTransport();\n\n yield* Effect.tryPromise({\n try: () => client.connect(transportInstance),\n catch: () =>\n new McpConnectionError({\n transport: input.transport,\n message: `Failed connecting via ${input.transport}`,\n }),\n }).pipe(\n Effect.withSpan(\"plugin.mcp.connection.handshake\", {\n attributes: { \"plugin.mcp.transport\": input.transport },\n }),\n );\n\n return connectionFromClient(client);\n });\n\n// ---------------------------------------------------------------------------\n// Public factory\n// ---------------------------------------------------------------------------\n\nexport const createMcpConnector = (input: ConnectorInput): McpConnector => {\n if (input.transport === \"stdio\") {\n const command = input.command.trim();\n if (!command) {\n return Effect.fail(\n new McpConnectionError({\n transport: \"stdio\",\n message: \"MCP stdio transport requires a command\",\n }),\n );\n }\n\n return Effect.gen(function* () {\n // Dynamic import so the underlying module (which evaluates\n // `node:child_process`) is only loaded when stdio is actually used.\n const { createStdioTransport } = yield* Effect.tryPromise({\n try: () => import(\"./stdio-connector\"),\n catch: () =>\n new McpConnectionError({\n transport: \"stdio\",\n message: \"Failed to load stdio transport module\",\n }),\n });\n\n return yield* connectClient({\n transport: \"stdio\",\n createTransport: () =>\n createStdioTransport({\n command,\n args: input.args,\n env: input.env,\n cwd: input.cwd?.trim().length ? input.cwd.trim() : undefined,\n }),\n });\n });\n }\n\n // Remote transport\n const headers = input.headers ?? {};\n const remoteTransport = input.remoteTransport ?? \"auto\";\n const requestInit = Object.keys(headers).length > 0 ? { headers } : undefined;\n\n const endpoint = buildEndpointUrl(input.endpoint, input.queryParams ?? {});\n\n const connectStreamableHttp = connectClient({\n transport: \"streamable-http\",\n createTransport: () =>\n new StreamableHTTPClientTransport(endpoint, {\n requestInit,\n authProvider: input.authProvider,\n }),\n });\n\n const connectSse = connectClient({\n transport: \"sse\",\n createTransport: () =>\n new SSEClientTransport(endpoint, {\n requestInit,\n authProvider: input.authProvider,\n }),\n });\n\n if (remoteTransport === \"streamable-http\") return connectStreamableHttp;\n if (remoteTransport === \"sse\") return connectSse;\n\n // auto — try streamable-http first, fall back to SSE\n return connectStreamableHttp.pipe(Effect.catch(() => connectSse));\n};\n","// ---------------------------------------------------------------------------\n// MCP tool discovery — connect to an MCP server and list its tools\n// ---------------------------------------------------------------------------\n\nimport { Effect } from \"effect\";\n\nimport type { McpConnector } from \"./connection\";\nimport { McpToolDiscoveryError } from \"./errors\";\nimport {\n extractManifestFromListToolsResult,\n isListToolsResult,\n type McpToolManifest,\n} from \"./manifest\";\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Connect to an MCP server and discover all available tools.\n * Returns the parsed manifest containing server metadata and tool entries.\n */\nexport const discoverTools = (\n connector: McpConnector,\n): Effect.Effect<McpToolManifest, McpToolDiscoveryError> =>\n Effect.gen(function* () {\n // Acquire connection\n const connection = yield* connector.pipe(\n Effect.mapError(\n ({ message }) =>\n new McpToolDiscoveryError({\n stage: \"connect\",\n message: `Failed connecting to MCP server: ${message}`,\n }),\n ),\n );\n\n // List tools\n const listResult = yield* Effect.tryPromise({\n try: () => connection.client.listTools(),\n catch: () =>\n new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: \"Failed listing MCP tools\",\n }),\n });\n\n if (!isListToolsResult(listResult)) {\n yield* closeConnection(connection);\n return yield* new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: \"MCP listTools response did not match the expected schema\",\n });\n }\n\n const manifest = extractManifestFromListToolsResult(listResult, {\n serverInfo: connection.client.getServerVersion?.(),\n });\n\n // Close the connection after discovery\n yield* closeConnection(connection);\n\n return manifest;\n });\n\nconst closeConnection = (connection: {\n readonly close: () => Promise<void>;\n}): Effect.Effect<void, never> =>\n Effect.ignore(\n Effect.tryPromise({\n try: () => connection.close(),\n catch: () =>\n new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: \"Failed closing MCP connection\",\n }),\n }),\n );\n","// ---------------------------------------------------------------------------\n// MCP tool invocation — shared helper called from plugin.invokeTool.\n//\n// Responsible for:\n// 1. Dialing a fresh MCP client connection for the call (no DB-connection\n// caching — request-scoped per the Hyperdrive rule; each invoke acquires\n// and releases its own connection).\n// 2. Installing a per-invocation `ElicitRequestSchema` handler that bridges\n// MCP's elicit capability into the host's elicit function threaded via\n// `InvokeToolInput.elicit`.\n// 3. Calling `client.callTool({ name, arguments })`.\n// ---------------------------------------------------------------------------\n\nimport { Cause, Effect, Exit, Option, Predicate, Schema } from \"effect\";\n\nimport { ElicitRequestSchema } from \"@modelcontextprotocol/sdk/types.js\";\n\nimport {\n ElicitationId,\n FormElicitation,\n UrlElicitation,\n type Elicit,\n type ElicitationRequest,\n} from \"@executor-js/sdk\";\n\nimport { McpConnectionError, McpInvocationError } from \"./errors\";\nimport type { McpConnection, McpConnector } from \"./connection\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst ArgsRecord = Schema.Record(Schema.String, Schema.Unknown);\nconst decodeArgsRecord = Schema.decodeUnknownOption(ArgsRecord);\n\nconst argsRecord = (value: unknown): Record<string, unknown> =>\n Option.getOrElse(decodeArgsRecord(value), () => ({}));\n\n// ---------------------------------------------------------------------------\n// Elicitation bridge — decode incoming MCP ElicitRequest, route through\n// the host's elicit function, marshal the response back to MCP shape.\n// ---------------------------------------------------------------------------\n\nconst McpElicitParams = Schema.Union([\n Schema.Struct({\n mode: Schema.Literal(\"url\"),\n message: Schema.String,\n url: Schema.String,\n elicitationId: Schema.optional(Schema.String),\n id: Schema.optional(Schema.String),\n }),\n Schema.Struct({\n mode: Schema.optional(Schema.Literal(\"form\")),\n message: Schema.String,\n requestedSchema: Schema.Record(Schema.String, Schema.Unknown),\n }),\n]);\ntype McpElicitParams = typeof McpElicitParams.Type;\n\nconst decodeElicitParams = Schema.decodeUnknownSync(McpElicitParams);\n\nconst toElicitationRequest = (params: McpElicitParams): ElicitationRequest =>\n params.mode === \"url\"\n ? UrlElicitation.make({\n message: params.message,\n url: params.url,\n elicitationId: ElicitationId.make(params.elicitationId ?? params.id ?? \"\"),\n })\n : FormElicitation.make({\n message: params.message,\n requestedSchema: params.requestedSchema,\n });\n\nconst installElicitationHandler = (client: McpConnection[\"client\"], elicit: Elicit): void => {\n client.setRequestHandler(ElicitRequestSchema, async (request: { params: unknown }) => {\n const params = decodeElicitParams(request.params);\n const req = toElicitationRequest(params);\n // Use runPromiseExit so we can inspect typed failures — `elicit`\n // fails with `ElicitationDeclinedError` on decline/cancel, which\n // we translate into the equivalent MCP elicit response instead of\n // surfacing as a JSON-RPC error.\n const exit = await Effect.runPromiseExit(elicit(req));\n if (Exit.isSuccess(exit)) {\n const response = exit.value;\n return {\n action: response.action,\n ...(response.action === \"accept\" && response.content ? { content: response.content } : {}),\n };\n }\n const failure = exit.cause.reasons.find(Cause.isFailReason);\n if (failure) {\n const err = failure.error;\n if (Predicate.isTagged(err, \"ElicitationDeclinedError\")) {\n const action =\n Predicate.hasProperty(err, \"action\") && err.action === \"cancel\" ? \"cancel\" : \"decline\";\n return { action };\n }\n }\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: MCP SDK async request handlers signal unexpected failures by rejecting\n throw Cause.squash(exit.cause);\n });\n};\n\n// ---------------------------------------------------------------------------\n// Single tool call — install handler, callTool, return raw result\n// ---------------------------------------------------------------------------\n\nconst useConnection = (\n connection: McpConnection,\n toolName: string,\n args: Record<string, unknown>,\n elicit: Elicit,\n): Effect.Effect<unknown, McpInvocationError> =>\n Effect.gen(function* () {\n installElicitationHandler(connection.client, elicit);\n return yield* Effect.tryPromise({\n try: () => connection.client.callTool({ name: toolName, arguments: args }),\n catch: () =>\n new McpInvocationError({\n toolName,\n message: `MCP tool call failed for ${toolName}`,\n }),\n }).pipe(\n Effect.withSpan(\"plugin.mcp.client.call_tool\", {\n attributes: { \"mcp.tool.name\": toolName },\n }),\n );\n });\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface InvokeMcpToolInput {\n readonly toolId: string;\n /** The real MCP tool name advertised by the server. */\n readonly toolName: string;\n readonly args: unknown;\n readonly transport: string;\n /** Dials a fresh connection. The connection is closed after the call. */\n readonly connector: McpConnector;\n readonly elicit: Elicit;\n}\n\nexport const invokeMcpTool = (\n input: InvokeMcpToolInput,\n): Effect.Effect<unknown, McpConnectionError | McpInvocationError> =>\n Effect.gen(function* () {\n const args = argsRecord(input.args);\n\n const connection = yield* Effect.acquireRelease(\n input.connector.pipe(\n Effect.withSpan(\"plugin.mcp.connection.acquire\", {\n attributes: { \"plugin.mcp.transport\": input.transport },\n }),\n ),\n (conn) =>\n Effect.ignore(\n Effect.tryPromise({\n try: () => conn.close(),\n catch: () =>\n new McpConnectionError({\n transport: input.transport,\n message: \"Failed to close MCP connection\",\n }),\n }),\n ),\n );\n\n return yield* useConnection(connection, input.toolName, args, input.elicit);\n }).pipe(\n Effect.scoped,\n Effect.withSpan(\"plugin.mcp.invoke\", {\n attributes: {\n \"mcp.tool.name\": input.toolName,\n \"plugin.mcp.tool_id\": input.toolId,\n \"plugin.mcp.transport\": input.transport,\n },\n }),\n );\n","// ---------------------------------------------------------------------------\n// MCP endpoint shape probe — decide whether an unknown HTTP endpoint is\n// actually speaking MCP before we try to classify it as such.\n//\n// Background:\n//\n// `discoverTools` (via the MCP SDK's StreamableHTTP / SSE transport)\n// fails for every non-MCP endpoint too — 200-with-HTML, 400-GraphQL,\n// 404, etc. all surface as the same opaque transport error. We need\n// our own classifier that distinguishes \"real MCP\" from\n// \"OAuth-protected non-MCP service\" without relying on RFC 9728/8414\n// metadata, since (a) plenty of non-MCP APIs publish that metadata,\n// and (b) plenty of real MCP servers authenticate with static API\n// keys and publish no OAuth metadata at all (e.g. cubic.dev).\n//\n// The probe issues an unauth JSON-RPC `initialize` POST and accepts\n// only the wire shapes a real MCP server can return:\n//\n// - 2xx with `Content-Type: text/event-stream` — streamable HTTP\n// transport, body is an SSE stream we don't consume.\n// - 2xx with `Content-Type: application/json` whose body parses as a\n// JSON-RPC 2.0 envelope (`{jsonrpc:\"2.0\", result|error|method,...}`).\n// - 401 with `WWW-Authenticate: Bearer` AND a JSON-RPC error envelope\n// in the body. The body shape is what separates a real MCP server\n// from an unrelated OAuth-protected API: GraphQL/REST/HTML 401s\n// don't shape themselves as JSON-RPC.\n//\n// When POST returns 404/405/406/415 we retry with GET + `Accept:\n// text/event-stream` to support legacy SSE-only servers; that path\n// only accepts 2xx with `text/event-stream` or the same 401+Bearer\n// shape.\n//\n// One `fetch` (occasionally two), no MCP-SDK session state, no OAuth\n// round-trip, no DCR — every non-MCP endpoint exits here.\n// ---------------------------------------------------------------------------\n\nimport { Data, Duration, Effect, Layer, Option, Schema } from \"effect\";\nimport { FetchHttpClient, HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\n/** MCP initialize request body used as the shape probe. Any real MCP\n * server either answers it (unauth-OK server) or returns the spec-\n * mandated 401 + WWW-Authenticate pair. A non-MCP endpoint hit with\n * this body will respond with whatever it does for unknown JSON\n * payloads — 400, 404, HTML, a GraphQL error envelope, etc. — none of\n * which match the gate below. */\nconst INITIALIZE_BODY = JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"initialize\",\n params: {\n protocolVersion: \"2025-06-18\",\n capabilities: {},\n clientInfo: { name: \"executor-probe\", version: \"0\" },\n },\n});\n\n/** Header-name lookup is case-insensitive per RFC 7230. `fetch`'s\n * `Response.headers` already lower-cases, but we normalise explicitly\n * to stay robust against test mocks that construct `Headers` loosely. */\nconst readHeader = (headers: Readonly<Record<string, string>>, name: string): string | null => {\n const direct = headers[name];\n if (direct !== undefined) return direct;\n const lower = name.toLowerCase();\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === lower) return v;\n }\n return null;\n};\n\nclass ProbeTransportError extends Data.TaggedError(\"ProbeTransportError\")<{\n readonly reason: string;\n readonly cause: unknown;\n}> {}\n\nconst decodeJsonString = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));\n\nconst asObject = (body: string): Record<string, unknown> | null => {\n if (!body) return null;\n const parsed = decodeJsonString(body);\n if (Option.isNone(parsed)) return null;\n const value = parsed.value;\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n return value as Record<string, unknown>;\n};\n\n/** Quick check that a body parses as a JSON-RPC 2.0 envelope. The MCP wire\n * protocol is JSON-RPC 2.0, so a real MCP server's response to `initialize`\n * (whether 2xx with the result, or a 401 error envelope) carries this\n * shape. Non-MCP services don't — GraphQL APIs return `{errors:[...]}`,\n * REST APIs return their own envelope, marketing pages return HTML. */\nconst isJsonRpcEnvelope = (body: string): boolean => {\n const obj = asObject(body);\n if (!obj) return false;\n if (obj.jsonrpc !== \"2.0\") return false;\n return \"result\" in obj || \"error\" in obj || \"method\" in obj;\n};\n\n/** Quick check that a body parses as an RFC 6750 OAuth Bearer error\n * envelope (`{error: \"invalid_token\", error_description?: ..., ...}`).\n * Real MCP servers like Atlassian return this shape on unauth requests\n * even when their WWW-Authenticate omits `resource_metadata=`. The\n * GraphQL `{errors: [...]}` envelope, which a non-MCP OAuth-protected\n * GraphQL API would return, is explicitly excluded. */\nconst isOAuthErrorBody = (body: string): boolean => {\n const obj = asObject(body);\n if (!obj) return false;\n if (Array.isArray(obj.errors)) return false;\n return typeof obj.error === \"string\";\n};\n\n/** RFC 9728 protected-resource-metadata document. We only need the two\n * fields that prove the document genuinely describes an OAuth-protected\n * resource: `resource` (the resource identifier) and a non-empty\n * `authorization_servers` list. */\nconst ProtectedResourceMetadata = Schema.Struct({\n resource: Schema.String,\n authorization_servers: Schema.Array(Schema.String),\n});\nconst decodeProtectedResourceMetadata = Schema.decodeUnknownOption(\n Schema.fromJsonString(ProtectedResourceMetadata),\n);\n\n/** RFC 9728 §3.1 path-scoped well-known URL: insert\n * `/.well-known/oauth-protected-resource` before the resource's path\n * component. `https://host/api/mcp` → `https://host/.well-known/oauth-\n * protected-resource/api/mcp`. This is exactly the URL the MCP\n * authorization spec tells clients to construct. */\nconst protectedResourceMetadataUrl = (endpoint: URL): string => {\n const path = endpoint.pathname === \"/\" ? \"\" : endpoint.pathname;\n return `${endpoint.origin}/.well-known/oauth-protected-resource${path}`;\n};\n\n/** The RFC 9728 `resource` value must actually describe this endpoint\n * before we trust the document — an exact URL match, or a same-origin\n * parent whose path is a prefix of the endpoint's. Guards against a\n * shared host serving protected-resource metadata for some unrelated\n * resource. */\nconst resourceMatchesEndpoint = (resource: string, endpoint: URL): boolean => {\n if (!URL.canParse(resource)) return false;\n const parsed = new URL(resource);\n if (parsed.origin !== endpoint.origin) return false;\n const resourcePath = parsed.pathname.replace(/\\/+$/, \"\");\n const endpointPath = endpoint.pathname.replace(/\\/+$/, \"\");\n return endpointPath === resourcePath || endpointPath.startsWith(`${resourcePath}/`);\n};\n\n/** Workaround for MCP servers that omit (or under-specify) the\n * `WWW-Authenticate` challenge on their 401 — e.g. Datadog's\n * `mcp.datadoghq.com` returns a bare `401 {\"errors\":[\"Unauthorized\"]}`\n * with no header at all, so the wire-shape gate above can't tell it\n * apart from an unrelated OAuth-protected API and the user lands on the\n * manual-credentials prompt instead of an OAuth sign-in.\n *\n * The MCP authorization spec still requires such servers to publish\n * RFC 9728 metadata at the path-scoped well-known URL. A document there\n * whose `resource` matches this endpoint is a deliberate, MCP-spec-\n * specific signal a generic OAuth API would not emit — strong enough to\n * classify the endpoint as MCP so the OAuth flow can start. */\nconst probeProtectedResourceMetadata = (\n client: HttpClient.HttpClient,\n endpoint: URL,\n timeoutMs: number,\n): Effect.Effect<boolean> =>\n Effect.gen(function* () {\n const response = yield* client\n .execute(\n HttpClientRequest.get(protectedResourceMetadataUrl(endpoint)).pipe(\n HttpClientRequest.setHeader(\"accept\", \"application/json\"),\n ),\n )\n .pipe(Effect.timeout(Duration.millis(timeoutMs)));\n if (response.status < 200 || response.status >= 300) return false;\n const body = yield* response.text.pipe(\n Effect.timeout(Duration.millis(timeoutMs)),\n Effect.catch(() => Effect.succeed(\"\")),\n );\n const metadata = decodeProtectedResourceMetadata(body);\n if (Option.isNone(metadata)) return false;\n if (metadata.value.authorization_servers.length === 0) return false;\n return resourceMatchesEndpoint(metadata.value.resource, endpoint);\n }).pipe(Effect.catch(() => Effect.succeed(false)));\n\nconst ErrorMessageShape = Schema.Struct({ message: Schema.String });\nconst decodeErrorMessageShape = Schema.decodeUnknownOption(ErrorMessageShape);\n\nconst reasonFromBoundaryCause = (cause: unknown): string => {\n const messageShape = decodeErrorMessageShape(cause);\n if (Option.isSome(messageShape)) return messageShape.value.message;\n if (typeof cause === \"string\") return cause;\n if (typeof cause === \"number\" || typeof cause === \"boolean\" || typeof cause === \"bigint\") {\n return `${cause}`;\n }\n if (typeof cause === \"symbol\") return cause.description ?? \"symbol\";\n if (cause === null) return \"null\";\n if (typeof cause === \"undefined\") return \"undefined\";\n return \"fetch failed\";\n};\n\n/** Why the probe rejected an endpoint as not-MCP.\n *\n * - `auth-required` — server returned 401. We don't know for sure it's\n * an MCP server (no spec-compliant Bearer challenge or the body\n * isn't JSON-RPC), but the right next step for the user is the same\n * either way: provide credentials and retry. This is what\n * misclassifies real MCP servers like cubic.dev (no\n * resource_metadata) or ref.tools (no WWW-Authenticate at all)\n * without the URL-token fallback at the detect layer.\n * - `wrong-shape` — endpoint responded but with a body or status that\n * doesn't match any MCP shape (200 HTML, 400 GraphQL, 404 from a\n * static host, etc.). User action: this URL probably isn't MCP. */\nexport type McpProbeRejectCategory = \"auth-required\" | \"wrong-shape\";\n\nexport type McpShapeProbeResult =\n /** Server answered initialize successfully — either a 2xx with a\n * JSON-RPC payload, or a 401 + WWW-Authenticate: Bearer (RFC 6750\n * challenge) that the MCP auth spec requires. */\n | { readonly kind: \"mcp\"; readonly requiresAuth: boolean }\n /** Endpoint is reachable but the response does not look like MCP. */\n | {\n readonly kind: \"not-mcp\";\n readonly reason: string;\n readonly category: McpProbeRejectCategory;\n }\n /** Transport-level failure (DNS, TLS, timeout, abort, ...). */\n | { readonly kind: \"unreachable\"; readonly reason: string };\n\nexport interface ProbeOptions {\n /** Abort the request after this many ms. Default 8000. */\n readonly timeoutMs?: number;\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n readonly headers?: Record<string, string>;\n readonly queryParams?: Record<string, string>;\n}\n\n/**\n * Hit `endpoint` with a JSON-RPC `initialize` POST and classify the\n * response according to the MCP authorization spec.\n *\n * Returns `{kind: \"mcp\"}` only when the endpoint either:\n * - answers with 2xx (unauth-OK MCP server), or\n * - responds 401 with a `Bearer` WWW-Authenticate challenge.\n *\n * Anything else (400, 404, 200-with-HTML, 200-with-GraphQL-errors, ...)\n * is classified `not-mcp`. Transport errors surface as `unreachable`.\n */\nexport const probeMcpEndpointShape = (\n endpoint: string,\n options: ProbeOptions = {},\n): Effect.Effect<McpShapeProbeResult> =>\n Effect.gen(function* () {\n const timeoutMs = options.timeoutMs ?? 8_000;\n const outcome = yield* Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient;\n\n const readBody = (response: {\n readonly text: Effect.Effect<string, unknown>;\n }): Effect.Effect<string> =>\n response.text.pipe(\n Effect.timeout(Duration.millis(timeoutMs)),\n Effect.catch(() => Effect.succeed(\"\")),\n );\n\n const classify = (\n response: {\n readonly status: number;\n readonly headers: Readonly<Record<string, string>>;\n readonly text: Effect.Effect<string, unknown>;\n },\n method: \"GET\" | \"POST\",\n ): Effect.Effect<McpShapeProbeResult | null> =>\n Effect.gen(function* () {\n const contentType = readHeader(response.headers, \"content-type\") ?? \"\";\n const isSse = /^\\s*text\\/event-stream\\b/i.test(contentType);\n\n if (response.status === 401) {\n const wwwAuth = readHeader(response.headers, \"www-authenticate\");\n if (!wwwAuth || !/^\\s*bearer\\b/i.test(wwwAuth)) {\n // Spec-non-compliant 401 (no `Bearer` challenge). Before\n // giving up, check whether the server still publishes\n // RFC 9728 protected-resource metadata for this path —\n // some real MCP servers (Datadog) do exactly this.\n if (yield* probeProtectedResourceMetadata(client, url, timeoutMs)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n return {\n kind: \"not-mcp\",\n category: \"auth-required\",\n reason: \"401 without Bearer WWW-Authenticate — not an MCP auth challenge\",\n } as const;\n }\n // Spec-compliant MCP signal: the auth spec mandates a\n // `resource_metadata=` attribute pointing at the server's\n // RFC 9728 document. Real OAuth-protected MCP servers\n // (sentry.dev, etc.) include it. This attribute is rare on\n // unrelated OAuth services and is the cleanest accept signal\n // we have when the 401 body is RFC 6750 OAuth-shape rather\n // than JSON-RPC.\n if (/(?:^|[\\s,])resource_metadata\\s*=/i.test(wwwAuth)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n // Looser RFC 6750 §3.1 signal: the Bearer challenge carries\n // `error=` / `error_description=` auth-params. Real MCP\n // servers (Supabase, GitHub Copilot, Vercel, Neon, Tavily,\n // Replicate, ...) include this even when they omit\n // `resource_metadata=`. The body alone isn't enough for\n // those — Supabase, e.g., returns `{\"message\":\"Unauthorized\"}`\n // which is neither JSON-RPC nor RFC 6750. The `error=`\n // auth-param is the tiebreaker.\n if (/(?:^|[\\s,])error\\s*=/i.test(wwwAuth)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n // SSE responses can't carry a JSON-RPC error envelope; accept the\n // Bearer challenge alone in that case (rare but spec-permissible).\n if (isSse) return { kind: \"mcp\", requiresAuth: true } as const;\n // Fallback for MCP servers whose 401 omits\n // `resource_metadata=`. Two body shapes count:\n // - JSON-RPC error (cubic.dev: API-key auth, JSON-RPC\n // errors end-to-end).\n // - RFC 6750 OAuth Bearer error envelope `{error:\n // \"invalid_token\", ...}` without GraphQL `{errors:[...]}`\n // (Atlassian).\n // Non-MCP OAuth-protected services that issue bare Bearer\n // challenges (Railway-style GraphQL, etc.) return `errors`\n // arrays or other shapes that fail both checks.\n const body = yield* readBody(response);\n if (!isJsonRpcEnvelope(body) && !isOAuthErrorBody(body)) {\n // Bearer challenge with no usable accept signal. Same\n // RFC 9728 fallback as the no-`Bearer` case above.\n if (yield* probeProtectedResourceMetadata(client, url, timeoutMs)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n return {\n kind: \"not-mcp\",\n category: \"auth-required\",\n reason:\n \"401 + Bearer without resource_metadata, JSON-RPC body, or OAuth error body\",\n } as const;\n }\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n\n if (response.status >= 200 && response.status < 300) {\n if (method === \"GET\") {\n if (!isSse) {\n return {\n kind: \"not-mcp\",\n category: \"wrong-shape\",\n reason: \"GET response is not an SSE stream\",\n } as const;\n }\n return { kind: \"mcp\", requiresAuth: false } as const;\n }\n // POST 2xx: SSE body is opaque to us; otherwise require a\n // JSON-RPC envelope so we don't accept HTML/REST 200 responses.\n if (isSse) return { kind: \"mcp\", requiresAuth: false } as const;\n const body = yield* readBody(response);\n if (!isJsonRpcEnvelope(body)) {\n return {\n kind: \"not-mcp\",\n category: \"wrong-shape\",\n reason: \"2xx POST body is not a JSON-RPC envelope\",\n } as const;\n }\n return { kind: \"mcp\", requiresAuth: false } as const;\n }\n\n return null;\n });\n\n const url = new URL(endpoint);\n for (const [key, value] of Object.entries(options.queryParams ?? {})) {\n url.searchParams.set(key, value);\n }\n\n let postRequest = HttpClientRequest.post(url.toString()).pipe(\n HttpClientRequest.setHeader(\"content-type\", \"application/json\"),\n HttpClientRequest.setHeader(\"accept\", \"application/json, text/event-stream\"),\n HttpClientRequest.bodyText(INITIALIZE_BODY, \"application/json\"),\n );\n for (const [name, value] of Object.entries(options.headers ?? {})) {\n postRequest = HttpClientRequest.setHeader(postRequest, name, value);\n }\n\n const postResponse = yield* client\n .execute(postRequest)\n .pipe(Effect.timeout(Duration.millis(timeoutMs)));\n\n const postResult = yield* classify(postResponse, \"POST\");\n if (postResult) return postResult;\n\n if ([404, 405, 406, 415].includes(postResponse.status)) {\n let getRequest = HttpClientRequest.get(url.toString()).pipe(\n HttpClientRequest.setHeader(\"accept\", \"text/event-stream\"),\n );\n for (const [name, value] of Object.entries(options.headers ?? {})) {\n getRequest = HttpClientRequest.setHeader(getRequest, name, value);\n }\n const getResponse = yield* client\n .execute(getRequest)\n .pipe(Effect.timeout(Duration.millis(timeoutMs)));\n const getResult = yield* classify(getResponse, \"GET\");\n if (getResult) return getResult;\n }\n\n return {\n kind: \"not-mcp\",\n category: \"wrong-shape\",\n reason: `unexpected status ${postResponse.status} for initialize`,\n } as const;\n }).pipe(\n Effect.provide(options.httpClientLayer ?? FetchHttpClient.layer),\n Effect.mapError(\n (cause) =>\n new ProbeTransportError({\n reason: reasonFromBoundaryCause(cause),\n cause,\n }),\n ),\n Effect.catch((cause) =>\n Effect.succeed<McpShapeProbeResult>({\n kind: \"unreachable\",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AAAA,YACF,aAAa;AAAA,YACb,cAAc;AAAA,YACd,SAAS,CAAC,UACR,KAAK,cAAc,KAA8B,EAAE;AAAA,cACjDA,QAAO,IAAI,WAAW,EAAE;AAAA,cACxBA,QAAO;AAAA,gBAAS;AAAA,gBAAsB,CAAC,EAAE,SAAS,UAAU,MAC1DA,QAAO,QAAQ,eAAe,yBAAyB,SAAS,EAAE,UAAU,CAAC,CAAC;AAAA,cAChF;AAAA,YACF;AAAA,UACJ,CAAC;AAAA,UACD,KAAK;AAAA,YACH,MAAM;AAAA,YACN,aACE;AAAA,YACF,aAAa;AAAA,YACb,cAAc;AAAA,YACd,SAAS,CAAC,UAAU;AAClB,oBAAM,OAAO;AACb,qBAAOA,QAAO;AAAA,gBAAI,KAAK,UAAU,KAAK,IAAI;AAAA,gBAAG,CAAC,gBAC5C,WAAW,GAAG,EAAE,YAAY,CAAC;AAAA,cAC/B;AAAA,YACF;AAAA,UACF,CAAC;AAAA,UACD,KAAK;AAAA,YACH,MAAM;AAAA,YACN,aACE;AAAA,YACF,aAAa;AAAA,cACX,kBAAkB;AAAA,cAClB,qBAAqB;AAAA,YACvB;AAAA,YACA,aAAa;AAAA,YACb,cAAc;AAAA,YACd,SAAS,CAAC,aAAa;AACrB,oBAAM,QAAQ;AACd,qBAAO,KAAK,UAAU,KAAuB,EAAE;AAAA,gBAC7CA,QAAO,IAAI,WAAW,EAAE;AAAA,gBACxBA,QAAO;AAAA,kBACL;AAAA,kBACA,CAAC,EAAE,KAAK,MACNA,QAAO;AAAA,oBACL;AAAA,sBACE;AAAA,sBACA,eAAe,IAAI;AAAA,oBACrB;AAAA,kBACF;AAAA,gBACJ;AAAA,cACF;AAAA,YACF;AAAA,UACF,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF,CAAC;","names":["tool","Effect","Option","Schema","Effect","Effect","Effect","Option","Schema","Schema","Option","Effect","Effect","Option","Schema","Schema","Option","Effect"]}
|
|
File without changes
|