@executor-js/plugin-mcp 1.5.6 → 1.5.8

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.
Files changed (40) hide show
  1. package/dist/{AddMcpSource-4LLERUW5.js → AddMcpSource-ZDNQ7F6I.js} +70 -97
  2. package/dist/AddMcpSource-ZDNQ7F6I.js.map +1 -0
  3. package/dist/EditMcpSource-75NJRWZR.js +178 -0
  4. package/dist/EditMcpSource-75NJRWZR.js.map +1 -0
  5. package/dist/McpAccountsPanel-QBCSCJE7.js +83 -0
  6. package/dist/McpAccountsPanel-QBCSCJE7.js.map +1 -0
  7. package/dist/api/group.d.ts +106 -15
  8. package/dist/api/index.d.ts +121 -15
  9. package/dist/{chunk-N4EAF5CA.js → chunk-3AOD4VAW.js} +74 -5
  10. package/dist/chunk-3AOD4VAW.js.map +1 -0
  11. package/dist/{chunk-6OEQZ72N.js → chunk-3H5Y7JCQ.js} +65 -11
  12. package/dist/chunk-3H5Y7JCQ.js.map +1 -0
  13. package/dist/{chunk-HSJWIVME.js → chunk-6BJ6MZF7.js} +110 -52
  14. package/dist/chunk-6BJ6MZF7.js.map +1 -0
  15. package/dist/client.js +3 -3
  16. package/dist/core.js +152 -5
  17. package/dist/core.js.map +1 -1
  18. package/dist/index.js +2 -2
  19. package/dist/react/atoms.d.ts +128 -26
  20. package/dist/react/auth-method-config.d.ts +22 -7
  21. package/dist/react/client.d.ts +103 -15
  22. package/dist/sdk/connection.d.ts +1 -1
  23. package/dist/sdk/index.d.ts +3 -1
  24. package/dist/sdk/invoke.d.ts +1 -1
  25. package/dist/sdk/migrate-config.d.ts +6 -0
  26. package/dist/sdk/migrate-config.test.d.ts +1 -0
  27. package/dist/sdk/multi-placement-auth.test.d.ts +1 -0
  28. package/dist/sdk/plugin.d.ts +92 -5
  29. package/dist/sdk/types.d.ts +105 -15
  30. package/package.json +4 -4
  31. package/dist/AddMcpSource-4LLERUW5.js.map +0 -1
  32. package/dist/EditMcpSource-GKJRP75X.js +0 -313
  33. package/dist/EditMcpSource-GKJRP75X.js.map +0 -1
  34. package/dist/McpAccountsPanel-UX7MHEIG.js +0 -132
  35. package/dist/McpAccountsPanel-UX7MHEIG.js.map +0 -1
  36. package/dist/chunk-6OEQZ72N.js.map +0 -1
  37. package/dist/chunk-7FJ3PUUL.js +0 -21
  38. package/dist/chunk-7FJ3PUUL.js.map +0 -1
  39. package/dist/chunk-HSJWIVME.js.map +0 -1
  40. package/dist/chunk-N4EAF5CA.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/react/EditMcpSource.tsx"],"sourcesContent":["import { useCallback, useEffect, 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 { AuthTemplateSlug, IntegrationSlug } from \"@executor-js/sdk/shared\";\nimport { createConnection } from \"@executor-js/react/api/atoms\";\nimport { connectionWriteKeys, integrationWriteKeys } from \"@executor-js/react/api/reactivity-keys\";\nimport { connectionIdentifier } from \"@executor-js/react/lib/connection-name\";\nimport {\n AuthTemplateEditor,\n type AuthTemplateEditorValue,\n} from \"@executor-js/react/components/auth-template-editor\";\nimport {\n CredentialControlField,\n ConnectionOwnerUsageRow,\n useConnectionOwner,\n} from \"@executor-js/react/plugins/connection-owner\";\nimport { OAuthSignInButton } from \"@executor-js/react/plugins/oauth-sign-in\";\nimport { Button } from \"@executor-js/react/components/button\";\nimport { AddAccountModal } from \"@executor-js/react/components/add-account-modal\";\nimport {\n CardStack,\n CardStackContent,\n CardStackEntry,\n CardStackEntryContent,\n CardStackEntryDescription,\n CardStackEntryTitle,\n} from \"@executor-js/react/components/card-stack\";\nimport { Input } from \"@executor-js/react/components/input\";\nimport { Badge } from \"@executor-js/react/components/badge\";\nimport type { AuthMethod } from \"@executor-js/react/lib/auth-placements\";\n\nimport { configureMcpServer, mcpServerAtom } from \"./atoms\";\nimport type { McpAuthTemplate, McpIntegrationConfig } from \"../sdk/types\";\nimport { mcpAuthTemplateFromEditorValue } from \"./auth-method-config\";\n\nconst HEADER_TEMPLATE = AuthTemplateSlug.make(\"header\");\nconst OAUTH_TEMPLATE = AuthTemplateSlug.make(\"oauth2\");\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\nconst authTemplateToEditorValue = (auth: McpRemoteConfig[\"auth\"]): AuthTemplateEditorValue => {\n if (auth.kind === \"none\") return { kind: \"none\" };\n if (auth.kind === \"oauth2\")\n return { kind: \"oauth\", authorizationUrl: \"\", tokenUrl: \"\", scopes: [] };\n return {\n kind: \"apikey\",\n placements: [\n {\n carrier: \"header\",\n name: auth.headerName,\n prefix: auth.prefix ?? \"\",\n },\n ],\n };\n};\n\nconst authTemplatesEqual = (left: McpAuthTemplate, right: McpAuthTemplate): boolean => {\n if (left.kind !== right.kind) return false;\n if (left.kind === \"header\" && right.kind === \"header\") {\n return left.headerName === right.headerName && (left.prefix ?? \"\") === (right.prefix ?? \"\");\n }\n return true;\n};\n\n// ---------------------------------------------------------------------------\n// Remote edit — v2: the integration's endpoint + auth template are part of its\n// identity (opaque-to-core config). The editable surface is the connection: an\n// API-key header value, or an OAuth sign-in, both owner-scoped.\n// ---------------------------------------------------------------------------\n\nfunction RemoteEdit(props: {\n server: McpServer & { config: McpRemoteConfig };\n onSave: () => void;\n}) {\n const { server } = props;\n const auth = server.config.auth;\n const { connectionOwner, setConnectionOwner, connectionOwnerOptions } = useConnectionOwner();\n const doCreate = useAtomSet(createConnection, { mode: \"promiseExit\" });\n const doConfigure = useAtomSet(configureMcpServer, { mode: \"promiseExit\" });\n\n const [authValue, setAuthValue] = useState<AuthTemplateEditorValue>(() =>\n authTemplateToEditorValue(auth),\n );\n const [apiKey, setApiKey] = useState(\"\");\n const [saving, setSaving] = useState(false);\n const [authSaving, setAuthSaving] = useState(false);\n const [error, setError] = useState<string | null>(null);\n const [connected, setConnected] = useState(false);\n const [oauthModalOpen, setOauthModalOpen] = useState(false);\n\n const editedAuth = mcpAuthTemplateFromEditorValue(authValue);\n const authChanged = !authTemplatesEqual(editedAuth, auth);\n\n useEffect(() => {\n setAuthValue(authTemplateToEditorValue(auth));\n }, [auth]);\n\n const handleSaveAuth = useCallback(async () => {\n setAuthSaving(true);\n setError(null);\n const nextConfig: McpRemoteConfig = {\n ...server.config,\n auth: mcpAuthTemplateFromEditorValue(authValue),\n };\n const exit = await doConfigure({\n params: { slug: server.slug },\n payload: { config: nextConfig },\n reactivityKeys: integrationWriteKeys,\n });\n if (Exit.isFailure(exit)) {\n setError(\"Failed to update authentication method\");\n setAuthSaving(false);\n return;\n }\n setAuthSaving(false);\n }, [authValue, doConfigure, server.config, server.slug]);\n\n const handleSaveKey = useCallback(async () => {\n if (apiKey.trim() === \"\") return;\n setSaving(true);\n setError(null);\n const exit = await doCreate({\n payload: {\n owner: connectionOwner,\n name: connectionIdentifier(`${server.slug} key`),\n integration: server.slug,\n template: HEADER_TEMPLATE,\n identityLabel: server.description || String(server.slug),\n value: apiKey.trim(),\n },\n reactivityKeys: connectionWriteKeys,\n });\n if (Exit.isFailure(exit)) {\n setError(\"Failed to save credential\");\n setSaving(false);\n return;\n }\n setSaving(false);\n setConnected(true);\n props.onSave();\n }, [apiKey, connectionOwner, doCreate, server, props]);\n\n const handleOAuth = useCallback(() => {\n setError(null);\n setOauthModalOpen(true);\n }, []);\n\n const oauthMethods = useMemo<readonly AuthMethod[]>(\n () =>\n auth.kind === \"oauth2\"\n ? [\n {\n id: \"oauth2\",\n label: \"OAuth\",\n kind: \"oauth\",\n source: \"spec\",\n template: OAUTH_TEMPLATE,\n placements: [],\n oauth: { discoveryUrl: server.config.endpoint, supportsDynamicRegistration: true },\n },\n ]\n : [],\n [auth.kind, server.config.endpoint],\n );\n const oauthInitialState = useMemo(\n () =>\n oauthModalOpen && auth.kind === \"oauth2\"\n ? {\n key: `${String(server.slug)}:${connectionOwner}:oauth`,\n owner: connectionOwner,\n template: String(OAUTH_TEMPLATE),\n label: `${server.description || String(server.slug)} OAuth`,\n }\n : null,\n [auth.kind, connectionOwner, oauthModalOpen, server],\n );\n\n return (\n <div className=\"space-y-6\">\n <div>\n <h1 className=\"text-xl font-semibold text-foreground\">Edit MCP Source</h1>\n <p className=\"mt-1 text-sm text-muted-foreground\">\n Manage the connection for this MCP server. The endpoint is part of the server's identity —\n remove and re-add to change it.\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 <div className=\"space-y-3 rounded-lg border border-border bg-card p-4\">\n <div>\n <p className=\"text-sm font-medium text-card-foreground\">Authentication method</p>\n <p className=\"mt-0.5 text-xs text-muted-foreground\">\n Choose how a connection credential is sent to this MCP server.\n </p>\n </div>\n <AuthTemplateEditor\n value={authValue}\n onChange={setAuthValue}\n allowedKinds={[\"none\", \"apikey\", \"oauth\"]}\n oauthMetadata=\"discovered\"\n />\n {authChanged ? (\n <div className=\"flex justify-end\">\n <Button\n type=\"button\"\n size=\"sm\"\n onClick={() => void handleSaveAuth()}\n disabled={authSaving}\n >\n {authSaving ? \"Saving…\" : \"Save authentication method\"}\n </Button>\n </div>\n ) : null}\n </div>\n\n {authChanged ? (\n <div className=\"rounded-md border border-border bg-muted/30 px-3 py-2 text-xs text-muted-foreground\">\n Save the authentication method before adding a connection.\n </div>\n ) : null}\n\n {!authChanged && auth.kind === \"header\" && (\n <ConnectionOwnerUsageRow\n value={connectionOwner}\n options={connectionOwnerOptions}\n onChange={setConnectionOwner}\n label=\"Connection saved to\"\n help=\"Choose who can use this credential.\"\n >\n <CredentialControlField label={`${auth.headerName} value`} help=\"Saved as a connection.\">\n <Input\n type=\"password\"\n value={apiKey}\n onChange={(e) => setApiKey((e.target as HTMLInputElement).value)}\n placeholder=\"sk-…\"\n className=\"font-mono text-sm\"\n autoComplete=\"new-password\"\n />\n <div className=\"mt-2 flex justify-end\">\n <Button\n type=\"button\"\n size=\"sm\"\n onClick={() => void handleSaveKey()}\n disabled={apiKey.trim() === \"\" || saving}\n >\n {saving ? \"Saving…\" : connected ? \"Saved\" : \"Save connection\"}\n </Button>\n </div>\n </CredentialControlField>\n </ConnectionOwnerUsageRow>\n )}\n\n {!authChanged && auth.kind === \"oauth2\" && (\n <ConnectionOwnerUsageRow\n value={connectionOwner}\n options={connectionOwnerOptions}\n onChange={setConnectionOwner}\n label=\"Connection saved to\"\n help=\"Choose who can use the OAuth connection.\"\n >\n <CredentialControlField label=\"Connect via OAuth\" help=\"Start the provider OAuth flow.\">\n <OAuthSignInButton\n busy={false}\n error={error}\n isConnected={connected}\n onSignIn={handleOAuth}\n signingInLabel=\"Signing in…\"\n reconnectingLabel=\"Reconnecting…\"\n />\n <AddAccountModal\n integration={server.slug}\n integrationName={server.description || String(server.slug)}\n methods={oauthMethods}\n open={oauthModalOpen}\n onOpenChange={setOauthModalOpen}\n initialState={oauthInitialState}\n />\n </CredentialControlField>\n </ConnectionOwnerUsageRow>\n )}\n\n {!authChanged && auth.kind === \"none\" && (\n <div className=\"rounded-md border border-border bg-muted/30 px-3 py-2 text-xs text-muted-foreground\">\n This server does not require a credential.\n </div>\n )}\n\n {error && (\n <div className=\"rounded-lg border border-destructive/30 bg-destructive/5 px-3 py-2\">\n <p className=\"text-sm text-destructive\">{error}</p>\n </div>\n )}\n\n <div className=\"flex items-center justify-end border-t border-border pt-4\">\n <Button onClick={props.onSave}>Done</Button>\n </div>\n </div>\n );\n}\n\ntype McpRemoteConfig = Extract<McpIntegrationConfig, { transport: \"remote\" }>;\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,WAAW,SAAS,gBAAgB;AAC1D,SAAS,cAAc,kBAAkB;AACzC,YAAY,iBAAiB;AAC7B,YAAY,UAAU;AAEtB,SAAS,kBAAkB,uBAAuB;AAClD,SAAS,wBAAwB;AACjC,SAAS,qBAAqB,4BAA4B;AAC1D,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,OAEK;AACP;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,yBAAyB;AAClC,SAAS,cAAc;AACvB,SAAS,uBAAuB;AAChC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AACP,SAAS,aAAa;AACtB,SAAS,aAAa;AA8JhB,SACE,KADF;AAvJN,IAAM,kBAAkB,iBAAiB,KAAK,QAAQ;AACtD,IAAM,iBAAiB,iBAAiB,KAAK,QAAQ;AAWrD,IAAM,4BAA4B,CAAC,SAA2D;AAC5F,MAAI,KAAK,SAAS,OAAQ,QAAO,EAAE,MAAM,OAAO;AAChD,MAAI,KAAK,SAAS;AAChB,WAAO,EAAE,MAAM,SAAS,kBAAkB,IAAI,UAAU,IAAI,QAAQ,CAAC,EAAE;AACzE,SAAO;AAAA,IACL,MAAM;AAAA,IACN,YAAY;AAAA,MACV;AAAA,QACE,SAAS;AAAA,QACT,MAAM,KAAK;AAAA,QACX,QAAQ,KAAK,UAAU;AAAA,MACzB;AAAA,IACF;AAAA,EACF;AACF;AAEA,IAAM,qBAAqB,CAAC,MAAuB,UAAoC;AACrF,MAAI,KAAK,SAAS,MAAM,KAAM,QAAO;AACrC,MAAI,KAAK,SAAS,YAAY,MAAM,SAAS,UAAU;AACrD,WAAO,KAAK,eAAe,MAAM,eAAe,KAAK,UAAU,SAAS,MAAM,UAAU;AAAA,EAC1F;AACA,SAAO;AACT;AAQA,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I,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,132 +0,0 @@
1
- import {
2
- configureMcpServer,
3
- mcpServerAtom
4
- } from "./chunk-N4EAF5CA.js";
5
- import "./chunk-6OEQZ72N.js";
6
-
7
- // src/react/McpAccountsPanel.tsx
8
- import { useCallback, useMemo } from "react";
9
- import { useAtomSet, useAtomValue } from "@effect/atom-react";
10
- import * as AsyncResult from "effect/unstable/reactivity/AsyncResult";
11
- import * as Exit from "effect/Exit";
12
- import { AuthTemplateSlug, IntegrationSlug } from "@executor-js/sdk/shared";
13
- import { AccountsSection } from "@executor-js/react/components/accounts-section";
14
- import { integrationWriteKeys } from "@executor-js/react/api/reactivity-keys";
15
- import { jsx } from "react/jsx-runtime";
16
- var NONE_TEMPLATE = AuthTemplateSlug.make("none");
17
- var HEADER_TEMPLATE = AuthTemplateSlug.make("header");
18
- var OAUTH_TEMPLATE = AuthTemplateSlug.make("oauth2");
19
- var NO_AUTH_METHOD = {
20
- id: "none",
21
- label: "No authentication",
22
- kind: "none",
23
- source: "spec",
24
- template: NONE_TEMPLATE,
25
- placements: []
26
- };
27
- var authMethodFromConfig = (config) => {
28
- if (config.transport === "stdio") return null;
29
- const auth = config.auth;
30
- if (auth.kind === "none") return NO_AUTH_METHOD;
31
- if (auth.kind === "oauth2") {
32
- return {
33
- id: "oauth2",
34
- label: "OAuth2",
35
- kind: "oauth",
36
- source: "spec",
37
- template: OAUTH_TEMPLATE,
38
- placements: [],
39
- oauth: { discoveryUrl: config.endpoint, supportsDynamicRegistration: true }
40
- };
41
- }
42
- return {
43
- id: "header",
44
- label: `API key (${auth.headerName})`,
45
- kind: "apikey",
46
- source: "custom",
47
- template: HEADER_TEMPLATE,
48
- placements: [
49
- {
50
- carrier: "header",
51
- name: auth.headerName,
52
- prefix: auth.prefix ?? ""
53
- }
54
- ]
55
- };
56
- };
57
- var headerAuthFromPlacements = (placements) => {
58
- const header = placements.find(
59
- (placement) => placement.carrier === "header" && placement.name.trim().length > 0
60
- );
61
- if (!header) return null;
62
- return {
63
- headerName: header.name.trim(),
64
- ...header.prefix ? { prefix: header.prefix } : {}
65
- };
66
- };
67
- function McpAccountsPanel(props) {
68
- const { sourceId, integrationName, accountHandoff } = props;
69
- const slug = IntegrationSlug.make(sourceId);
70
- const serverResult = useAtomValue(mcpServerAtom(slug));
71
- const doConfigure = useAtomSet(configureMcpServer, { mode: "promiseExit" });
72
- const server = AsyncResult.isSuccess(serverResult) ? serverResult.value : null;
73
- const config = server?.config ?? null;
74
- const method = config ? authMethodFromConfig(config) : null;
75
- const methods = method ? [method] : [];
76
- const createCustomMethod = useCallback(
77
- async (input) => {
78
- if (config === null || config.transport !== "remote") return null;
79
- const header = headerAuthFromPlacements(input.placements);
80
- if (header === null) return null;
81
- const nextConfig = {
82
- ...config,
83
- auth: { kind: "header", ...header }
84
- };
85
- const exit = await doConfigure({
86
- params: { slug },
87
- payload: { config: nextConfig },
88
- reactivityKeys: integrationWriteKeys
89
- });
90
- if (Exit.isFailure(exit)) return null;
91
- return authMethodFromConfig(exit.value.config);
92
- },
93
- [config, doConfigure, slug]
94
- );
95
- const removeCustomMethod = useCallback(
96
- async (methodToRemove) => {
97
- if (config === null || config.transport !== "remote" || methodToRemove.template !== HEADER_TEMPLATE) {
98
- return false;
99
- }
100
- const nextConfig = {
101
- ...config,
102
- auth: { kind: "none" }
103
- };
104
- const exit = await doConfigure({
105
- params: { slug },
106
- payload: { config: nextConfig },
107
- reactivityKeys: integrationWriteKeys
108
- });
109
- return Exit.isSuccess(exit);
110
- },
111
- [config, doConfigure, slug]
112
- );
113
- const canConfigureAuth = useMemo(
114
- () => config !== null && config.transport === "remote",
115
- [config]
116
- );
117
- return /* @__PURE__ */ jsx("div", { className: "mx-auto max-w-3xl space-y-8 px-6 py-8", children: /* @__PURE__ */ jsx(
118
- AccountsSection,
119
- {
120
- integration: slug,
121
- integrationName,
122
- methods,
123
- accountHandoff,
124
- createCustomMethod: canConfigureAuth ? createCustomMethod : void 0,
125
- removeCustomMethod: canConfigureAuth ? removeCustomMethod : void 0
126
- }
127
- ) });
128
- }
129
- export {
130
- McpAccountsPanel as default
131
- };
132
- //# sourceMappingURL=McpAccountsPanel-UX7MHEIG.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/react/McpAccountsPanel.tsx"],"sourcesContent":["import { useCallback, useMemo } from \"react\";\nimport { useAtomSet, useAtomValue } from \"@effect/atom-react\";\nimport * as AsyncResult from \"effect/unstable/reactivity/AsyncResult\";\nimport * as Exit from \"effect/Exit\";\n\nimport { AuthTemplateSlug, IntegrationSlug } from \"@executor-js/sdk/shared\";\nimport type { IntegrationAccountHandoff } from \"@executor-js/sdk/client\";\nimport { AccountsSection } from \"@executor-js/react/components/accounts-section\";\nimport type { CreateCustomMethod } from \"@executor-js/react/components/add-custom-method-modal\";\nimport type { AuthMethod, Placement } from \"@executor-js/react/lib/auth-placements\";\nimport { integrationWriteKeys } from \"@executor-js/react/api/reactivity-keys\";\n\nimport { configureMcpServer, mcpServerAtom } from \"./atoms\";\nimport type { McpIntegrationConfig } from \"../sdk/types\";\n\nconst NONE_TEMPLATE = AuthTemplateSlug.make(\"none\");\nconst HEADER_TEMPLATE = AuthTemplateSlug.make(\"header\");\nconst OAUTH_TEMPLATE = AuthTemplateSlug.make(\"oauth2\");\n\nconst NO_AUTH_METHOD: AuthMethod = {\n id: \"none\",\n label: \"No authentication\",\n kind: \"none\",\n source: \"spec\",\n template: NONE_TEMPLATE,\n placements: [],\n};\n\nconst authMethodFromConfig = (config: McpIntegrationConfig): AuthMethod | null => {\n if (config.transport === \"stdio\") return null;\n const auth = config.auth;\n if (auth.kind === \"none\") return NO_AUTH_METHOD;\n if (auth.kind === \"oauth2\") {\n return {\n id: \"oauth2\",\n label: \"OAuth2\",\n kind: \"oauth\",\n source: \"spec\",\n template: OAUTH_TEMPLATE,\n placements: [],\n oauth: { discoveryUrl: config.endpoint, supportsDynamicRegistration: true },\n };\n }\n return {\n id: \"header\",\n label: `API key (${auth.headerName})`,\n kind: \"apikey\",\n source: \"custom\",\n template: HEADER_TEMPLATE,\n placements: [\n {\n carrier: \"header\",\n name: auth.headerName,\n prefix: auth.prefix ?? \"\",\n },\n ],\n };\n};\n\nconst headerAuthFromPlacements = (\n placements: readonly Placement[],\n): { readonly headerName: string; readonly prefix?: string } | null => {\n const header = placements.find(\n (placement: Placement) => placement.carrier === \"header\" && placement.name.trim().length > 0,\n );\n if (!header) return null;\n return {\n headerName: header.name.trim(),\n ...(header.prefix ? { prefix: header.prefix } : {}),\n };\n};\n\nexport default function McpAccountsPanel(props: {\n readonly sourceId: string;\n readonly integrationName: string;\n readonly accountHandoff?: IntegrationAccountHandoff | null;\n}) {\n const { sourceId, integrationName, accountHandoff } = props;\n const slug = IntegrationSlug.make(sourceId);\n const serverResult = useAtomValue(mcpServerAtom(slug));\n const doConfigure = useAtomSet(configureMcpServer, { mode: \"promiseExit\" });\n\n const server = AsyncResult.isSuccess(serverResult) ? serverResult.value : null;\n const config = server?.config ?? null;\n const method = config ? authMethodFromConfig(config) : null;\n const methods = method ? [method] : [];\n\n const createCustomMethod = useCallback<CreateCustomMethod>(\n async (input: { readonly label: string; readonly placements: readonly Placement[] }) => {\n if (config === null || config.transport !== \"remote\") return null;\n const header = headerAuthFromPlacements(input.placements);\n if (header === null) return null;\n const nextConfig: McpIntegrationConfig = {\n ...config,\n auth: { kind: \"header\", ...header },\n };\n const exit = await doConfigure({\n params: { slug },\n payload: { config: nextConfig },\n reactivityKeys: integrationWriteKeys,\n });\n if (Exit.isFailure(exit)) return null;\n return authMethodFromConfig(exit.value.config);\n },\n [config, doConfigure, slug],\n );\n\n const removeCustomMethod = useCallback(\n async (methodToRemove: AuthMethod): Promise<boolean> => {\n if (\n config === null ||\n config.transport !== \"remote\" ||\n methodToRemove.template !== HEADER_TEMPLATE\n ) {\n return false;\n }\n const nextConfig: McpIntegrationConfig = {\n ...config,\n auth: { kind: \"none\" },\n };\n const exit = await doConfigure({\n params: { slug },\n payload: { config: nextConfig },\n reactivityKeys: integrationWriteKeys,\n });\n return Exit.isSuccess(exit);\n },\n [config, doConfigure, slug],\n );\n\n const canConfigureAuth = useMemo(\n () => config !== null && config.transport === \"remote\",\n [config],\n );\n\n return (\n <div className=\"mx-auto max-w-3xl space-y-8 px-6 py-8\">\n <AccountsSection\n integration={slug}\n integrationName={integrationName}\n methods={methods}\n accountHandoff={accountHandoff}\n createCustomMethod={canConfigureAuth ? createCustomMethod : undefined}\n removeCustomMethod={canConfigureAuth ? removeCustomMethod : undefined}\n />\n </div>\n );\n}\n"],"mappings":";;;;;;;AAAA,SAAS,aAAa,eAAe;AACrC,SAAS,YAAY,oBAAoB;AACzC,YAAY,iBAAiB;AAC7B,YAAY,UAAU;AAEtB,SAAS,kBAAkB,uBAAuB;AAElD,SAAS,uBAAuB;AAGhC,SAAS,4BAA4B;AA+H/B;AA1HN,IAAM,gBAAgB,iBAAiB,KAAK,MAAM;AAClD,IAAM,kBAAkB,iBAAiB,KAAK,QAAQ;AACtD,IAAM,iBAAiB,iBAAiB,KAAK,QAAQ;AAErD,IAAM,iBAA6B;AAAA,EACjC,IAAI;AAAA,EACJ,OAAO;AAAA,EACP,MAAM;AAAA,EACN,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,YAAY,CAAC;AACf;AAEA,IAAM,uBAAuB,CAAC,WAAoD;AAChF,MAAI,OAAO,cAAc,QAAS,QAAO;AACzC,QAAM,OAAO,OAAO;AACpB,MAAI,KAAK,SAAS,OAAQ,QAAO;AACjC,MAAI,KAAK,SAAS,UAAU;AAC1B,WAAO;AAAA,MACL,IAAI;AAAA,MACJ,OAAO;AAAA,MACP,MAAM;AAAA,MACN,QAAQ;AAAA,MACR,UAAU;AAAA,MACV,YAAY,CAAC;AAAA,MACb,OAAO,EAAE,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AM,UAAU,GAAG,OAAO;AAAA,MACpC;AACA,YAAM,OAAO,MAAM,YAAY;AAAA,QAC7B,QAAQ,EAAE,KAAK;AAAA,QACf,SAAS,EAAE,QAAQ,WAAW;AAAA,QAC9B,gBAAgB;AAAA,MAClB,CAAC;AACD,UAAS,eAAU,IAAI,EAAG,QAAO;AACjC,aAAO,qBAAqB,KAAK,MAAM,MAAM;AAAA,IAC/C;AAAA,IACA,CAAC,QAAQ,aAAa,IAAI;AAAA,EAC5B;AAEA,QAAM,qBAAqB;AAAA,IACzB,OAAO,mBAAiD;AACtD,UACE,WAAW,QACX,OAAO,cAAc,YACrB,eAAe,aAAa,iBAC5B;AACA,eAAO;AAAA,MACT;AACA,YAAM,aAAmC;AAAA,QACvC,GAAG;AAAA,QACH,MAAM,EAAE,MAAM,OAAO;AAAA,MACvB;AACA,YAAM,OAAO,MAAM,YAAY;AAAA,QAC7B,QAAQ,EAAE,KAAK;AAAA,QACf,SAAS,EAAE,QAAQ,WAAW;AAAA,QAC9B,gBAAgB;AAAA,MAClB,CAAC;AACD,aAAY,eAAU,IAAI;AAAA,IAC5B;AAAA,IACA,CAAC,QAAQ,aAAa,IAAI;AAAA,EAC5B;AAEA,QAAM,mBAAmB;AAAA,IACvB,MAAM,WAAW,QAAQ,OAAO,cAAc;AAAA,IAC9C,CAAC,MAAM;AAAA,EACT;AAEA,SACE,oBAAC,SAAI,WAAU,yCACb;AAAA,IAAC;AAAA;AAAA,MACC,aAAa;AAAA,MACb;AAAA,MACA;AAAA,MACA;AAAA,MACA,oBAAoB,mBAAmB,qBAAqB;AAAA,MAC5D,oBAAoB,mBAAmB,qBAAqB;AAAA;AAAA,EAC9D,GACF;AAEJ;","names":[]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/sdk/errors.ts","../src/sdk/types.ts"],"sourcesContent":["// MCP plugin tagged errors. Each carries an `HttpApiSchema` annotation so\n// it can be `.addError(...)` directly on the API group — handlers return\n// these and HttpApi encodes them as 4xx responses with a typed body. No\n// per-handler sanitisation step.\n\nimport { Schema } from \"effect\";\n\nexport class McpConnectionError extends Schema.TaggedErrorClass<McpConnectionError>()(\n \"McpConnectionError\",\n {\n transport: Schema.String,\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class McpToolDiscoveryError extends Schema.TaggedErrorClass<McpToolDiscoveryError>()(\n \"McpToolDiscoveryError\",\n {\n stage: Schema.Literals([\"connect\", \"list_tools\"]),\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class McpInvocationError extends Schema.TaggedErrorClass<McpInvocationError>()(\n \"McpInvocationError\",\n {\n toolName: Schema.String,\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n\nexport class McpOAuthError extends Schema.TaggedErrorClass<McpOAuthError>()(\n \"McpOAuthError\",\n {\n message: Schema.String,\n },\n { httpApiStatus: 400 },\n) {}\n","import { Effect, Option, Schema } from \"effect\";\n\n// ---------------------------------------------------------------------------\n// MCP plugin v2 data model.\n//\n// An MCP integration is one server. Its `config` blob (opaque to core, stored\n// on the integration row) carries everything needed to dial the server plus an\n// `auth` *template* describing how a connection's resolved value is applied to\n// the request. A connection IS the credential: at execute time core resolves\n// the connection's value through its provider (refreshing OAuth tokens), and\n// the plugin renders it onto the request per the template (D11). The same path\n// covers an API key bearer and an OAuth access token — both resolve to a value\n// and render through their template.\n// ---------------------------------------------------------------------------\n\n// ---------------------------------------------------------------------------\n// Transport / remote transport\n// ---------------------------------------------------------------------------\n\nexport const McpRemoteTransport = Schema.Literals([\"streamable-http\", \"sse\", \"auto\"]);\nexport type McpRemoteTransport = typeof McpRemoteTransport.Type;\n\n/** All transport types (used in the connector layer) */\nexport const McpTransport = Schema.Literals([\"streamable-http\", \"sse\", \"stdio\", \"auto\"]);\nexport type McpTransport = typeof McpTransport.Type;\n\n// ---------------------------------------------------------------------------\n// Auth template — how a connection's resolved value is applied to the request.\n//\n// none — no credential (open server)\n// header — render the value into a request header (e.g. `Authorization:\n// Bearer <value>`); `prefix` is prepended to the value\n// oauth2 — the value is an OAuth access token, applied as a Bearer header\n// via the MCP SDK's OAuthClientProvider\n// ---------------------------------------------------------------------------\n\nexport const McpAuthTemplate = Schema.Union([\n Schema.Struct({ kind: Schema.Literal(\"none\") }),\n Schema.Struct({\n kind: Schema.Literal(\"header\"),\n headerName: Schema.String,\n prefix: Schema.optional(Schema.String),\n }),\n Schema.Struct({ kind: Schema.Literal(\"oauth2\") }),\n]);\nexport type McpAuthTemplate = typeof McpAuthTemplate.Type;\n\n// ---------------------------------------------------------------------------\n// Integration config — the opaque blob stored on the integration row. A\n// discriminated union on transport.\n// ---------------------------------------------------------------------------\n\nconst StringMap = Schema.Record(Schema.String, Schema.String);\n\nexport const McpRemoteIntegrationConfig = Schema.Struct({\n transport: Schema.Literal(\"remote\"),\n /** The MCP server endpoint URL */\n endpoint: Schema.String,\n /** Transport preference for this remote server */\n remoteTransport: McpRemoteTransport.pipe(\n Schema.optionalKey,\n Schema.withConstructorDefault(Effect.succeed(\"auto\" as const)),\n ),\n /** Static query params appended to the endpoint URL (non-credential) */\n queryParams: Schema.optional(StringMap),\n /** Static headers sent on every request (non-credential) */\n headers: Schema.optional(StringMap),\n /** Auth template — how the connection's value is rendered onto requests */\n auth: McpAuthTemplate,\n});\nexport type McpRemoteIntegrationConfig = typeof McpRemoteIntegrationConfig.Type;\n\nexport const McpStdioIntegrationConfig = Schema.Struct({\n transport: Schema.Literal(\"stdio\"),\n /** The command to run */\n command: Schema.String,\n /** Arguments to the command */\n args: Schema.optional(Schema.Array(Schema.String)),\n /** Environment variables */\n env: Schema.optional(StringMap),\n /** Working directory */\n cwd: Schema.optional(Schema.String),\n});\nexport type McpStdioIntegrationConfig = typeof McpStdioIntegrationConfig.Type;\n\nexport const McpIntegrationConfig = Schema.Union([\n McpRemoteIntegrationConfig,\n McpStdioIntegrationConfig,\n]);\nexport type McpIntegrationConfig = typeof McpIntegrationConfig.Type;\n\nconst decodeIntegrationConfig = Schema.decodeUnknownOption(McpIntegrationConfig);\n\n/** Parse an opaque integration `config` blob into a typed MCP config, or null\n * if it isn't this plugin's shape. */\nexport const parseMcpIntegrationConfig = (config: unknown): McpIntegrationConfig | null => {\n if (\n typeof config === \"object\" &&\n config !== null &&\n \"transport\" in config &&\n config.transport === \"remote\" &&\n !(\"auth\" in config)\n ) {\n return Option.getOrNull(decodeIntegrationConfig({ ...config, auth: { kind: \"none\" } }));\n }\n return Option.getOrNull(decodeIntegrationConfig(config));\n};\n\n// ---------------------------------------------------------------------------\n// Tool annotations — upstream MCP ToolAnnotations we honour (destructiveHint\n// drives requiresApproval).\n// ---------------------------------------------------------------------------\n\nexport const McpToolAnnotations = Schema.Struct({\n title: Schema.optional(Schema.String),\n readOnlyHint: Schema.optional(Schema.Boolean),\n destructiveHint: Schema.optional(Schema.Boolean),\n idempotentHint: Schema.optional(Schema.Boolean),\n openWorldHint: Schema.optional(Schema.Boolean),\n});\nexport type McpToolAnnotations = typeof McpToolAnnotations.Type;\n\n// ---------------------------------------------------------------------------\n// Tool binding — maps a persisted (sanitized) tool name back to its real MCP\n// tool name and upstream annotations, persisted per-connection so invokeTool\n// can dial the server with the correct name.\n// ---------------------------------------------------------------------------\n\nexport const McpToolBinding = Schema.Struct({\n /** Sanitized, address-safe tool name (the `<tool>` address segment). */\n toolId: Schema.String,\n /** The real MCP tool name as advertised by the server. */\n toolName: Schema.String,\n description: Schema.NullOr(Schema.String),\n inputSchema: Schema.optional(Schema.Unknown),\n outputSchema: Schema.optional(Schema.Unknown),\n annotations: Schema.optional(McpToolAnnotations),\n});\nexport type McpToolBinding = typeof McpToolBinding.Type;\n"],"mappings":";AAKA,SAAS,cAAc;AAEhB,IAAM,qBAAN,cAAiC,OAAO,iBAAqC;AAAA,EAClF;AAAA,EACA;AAAA,IACE,WAAW,OAAO;AAAA,IAClB,SAAS,OAAO;AAAA,EAClB;AAAA,EACA,EAAE,eAAe,IAAI;AACvB,EAAE;AAAC;AAEI,IAAM,wBAAN,cAAoC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jB,aAAaA,QAAO,OAAOA,QAAO,MAAM;AAAA,EACxC,aAAaA,QAAO,SAASA,QAAO,OAAO;AAAA,EAC3C,cAAcA,QAAO,SAASA,QAAO,OAAO;AAAA,EAC5C,aAAaA,QAAO,SAAS,kBAAkB;AACjD,CAAC;","names":["Schema"]}
@@ -1,21 +0,0 @@
1
- // src/react/auth-method-config.ts
2
- function mcpAuthTemplateFromEditorValue(value) {
3
- if (value.kind === "oauth") return { kind: "oauth2" };
4
- if (value.kind === "apikey") {
5
- const header = value.placements.find(
6
- (placement) => placement.carrier === "header" && placement.name.trim().length > 0
7
- );
8
- if (!header) return { kind: "none" };
9
- return {
10
- kind: "header",
11
- headerName: header.name.trim(),
12
- ...header.prefix ? { prefix: header.prefix } : {}
13
- };
14
- }
15
- return { kind: "none" };
16
- }
17
-
18
- export {
19
- mcpAuthTemplateFromEditorValue
20
- };
21
- //# sourceMappingURL=chunk-7FJ3PUUL.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/react/auth-method-config.ts"],"sourcesContent":["// ---------------------------------------------------------------------------\n// MCP ↔ generic auth-template converter.\n//\n// The shared add-time `AuthTemplateEditor` speaks the plugin-agnostic\n// `AuthTemplateEditorValue`. MCP's stored auth is a single `McpAuthTemplate`\n// (`none` / `header` / `oauth2`) — one method, not an array. This converts the\n// editor value to that shape and lives with the MCP plugin because it touches\n// the transport-specific `McpAuthTemplate` type.\n// ---------------------------------------------------------------------------\n\nimport type { AuthTemplateEditorValue } from \"@executor-js/react/components/auth-template-editor\";\n\nimport type { McpAuthTemplate } from \"../sdk/types\";\n\n/** Convert a generic editor value into MCP's single `McpAuthTemplate`. An\n * apiKey method maps to a `header` template using its FIRST header placement\n * (MCP carries a single header, not an array); a header placement's prefix is\n * preserved. OAuth maps to `oauth2`; `none` to `none`. An apiKey value with no\n * usable header placement falls back to `none`. */\nexport function mcpAuthTemplateFromEditorValue(value: AuthTemplateEditorValue): McpAuthTemplate {\n if (value.kind === \"oauth\") return { kind: \"oauth2\" };\n if (value.kind === \"apikey\") {\n const header = value.placements.find(\n (placement) => placement.carrier === \"header\" && placement.name.trim().length > 0,\n );\n if (!header) return { kind: \"none\" };\n return {\n kind: \"header\",\n headerName: header.name.trim(),\n ...(header.prefix ? { prefix: header.prefix } : {}),\n };\n }\n return { kind: \"none\" };\n}\n"],"mappings":";AAmBO,SAAS,+BAA+B,OAAiD;AAC9F,MAAI,MAAM,SAAS,QAAS,QAAO,EAAE,MAAM,SAAS;AACpD,MAAI,MAAM,SAAS,UAAU;AAC3B,UAAM,SAAS,MAAM,WAAW;AAAA,MAC9B,CAAC,cAAc,UAAU,YAAY,YAAY,UAAU,KAAK,KAAK,EAAE,SAAS;AAAA,IAClF;AACA,QAAI,CAAC,OAAQ,QAAO,EAAE,MAAM,OAAO;AACnC,WAAO;AAAA,MACL,MAAM;AAAA,MACN,YAAY,OAAO,KAAK,KAAK;AAAA,MAC7B,GAAI,OAAO,SAAS,EAAE,QAAQ,OAAO,OAAO,IAAI,CAAC;AAAA,IACnD;AAAA,EACF;AACA,SAAO,EAAE,MAAM,OAAO;AACxB;","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 OAuthClientSlug,\n tool,\n ToolResult,\n type AuthMethodDescriptor,\n type Integration,\n type IntegrationConfig,\n type IntegrationRecord,\n type OAuthClientSummary,\n type Owner,\n type PluginCtx,\n type StaticToolSchema,\n type StorageFailure,\n type ToolAnnotations,\n type ToolDef,\n ToolName,\n} from \"@executor-js/sdk/core\";\n\nimport { createMcpConnector, type ConnectorInput, type McpConnector } from \"./connection\";\nimport { discoverTools } from \"./discover\";\nimport { McpConnectionError, McpToolDiscoveryError } from \"./errors\";\nimport { invokeMcpTool } from \"./invoke\";\nimport { deriveMcpNamespace, type McpToolManifestEntry } from \"./manifest\";\nimport { mcpPresets } from \"./presets\";\nimport { probeMcpEndpointShape, type McpShapeProbeResult } from \"./probe-shape\";\nimport {\n McpAuthTemplate,\n McpRemoteTransport,\n type McpToolAnnotations,\n parseMcpIntegrationConfig,\n type McpIntegrationConfig as McpIntegrationConfigType,\n type McpStdioIntegrationConfig,\n} from \"./types\";\n\nconst MCP_PLUGIN_ID = \"mcp\" as const;\n\nconst legacyOAuthClientSlugCandidate = (value: string): string | null => {\n const slug = value\n .trim()\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, \"-\")\n .replace(/^-+|-+$/g, \"\");\n return slug.length > 0 ? slug : null;\n};\n\nconst legacyOAuthClientSlugCandidates = (\n slug: string,\n integration: (Integration & { readonly config: IntegrationConfig }) | null,\n): ReadonlySet<string> => {\n const candidates = new Set<string>();\n const fromSlug = legacyOAuthClientSlugCandidate(slug);\n if (fromSlug) candidates.add(fromSlug);\n const fromDescription =\n integration == null ? null : legacyOAuthClientSlugCandidate(integration.description);\n if (fromDescription) candidates.add(fromDescription);\n return candidates;\n};\n\nconst oauthClientKey = (owner: Owner, slug: OAuthClientSlug): string => `${owner}:${String(slug)}`;\n\nconst legacyMcpClientMatches = (\n client: OAuthClientSummary,\n candidates: ReadonlySet<string>,\n config: McpIntegrationConfigType | null,\n): boolean => {\n if (!candidates.has(String(client.slug))) return false;\n if (!config || config.transport !== \"remote\" || config.auth.kind !== \"oauth2\") return false;\n return client.grant === \"authorization_code\" && (client.resource ?? null) === config.endpoint;\n};\n\n// ---------------------------------------------------------------------------\n// Tool annotations carry an `mcp` envelope alongside the executor's policy\n// hints. The executor persists `ToolDef.annotations` verbatim into the tool\n// row's JSON column, so the real MCP tool name + upstream annotations survive\n// to `invokeTool` / `resolveAnnotations` with no plugin-side store (resolveTools\n// has no ctx to write one anyway). The envelope is opaque to core.\n// ---------------------------------------------------------------------------\n\ninterface McpToolStamp {\n readonly toolName: string;\n readonly upstream?: McpToolAnnotations;\n}\n\ntype StampedAnnotations = ToolAnnotations & { readonly mcp: McpToolStamp };\n\nconst McpStampSchema = Schema.Struct({\n toolName: Schema.String,\n upstream: Schema.optional(\n Schema.Struct({\n title: Schema.optional(Schema.String),\n readOnlyHint: Schema.optional(Schema.Boolean),\n destructiveHint: Schema.optional(Schema.Boolean),\n idempotentHint: Schema.optional(Schema.Boolean),\n openWorldHint: Schema.optional(Schema.Boolean),\n }),\n ),\n});\nconst AnnotationsWithStamp = Schema.Struct({ mcp: McpStampSchema });\nconst decodeStamp = Schema.decodeUnknownOption(AnnotationsWithStamp);\n\nconst readStamp = (annotations: unknown): McpToolStamp | null =>\n Option.match(decodeStamp(annotations), {\n onNone: () => null,\n onSome: (decoded) => decoded.mcp,\n });\n\n// ---------------------------------------------------------------------------\n// Extension input shapes — `addServer` registers an MCP integration. A\n// connection (the credential) is then created against it via\n// `executor.connections.create` / `oauth.start`.\n// ---------------------------------------------------------------------------\n\nconst McpRemoteServerInputSchema = Schema.Struct({\n transport: Schema.optional(Schema.Literal(\"remote\")),\n name: Schema.String,\n endpoint: Schema.String,\n remoteTransport: Schema.optional(McpRemoteTransport),\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n slug: Schema.optional(Schema.String),\n /** How a connection's value is applied to requests. Defaults to none. */\n auth: Schema.optional(McpAuthTemplate),\n});\n\nconst McpStdioServerInputSchema = Schema.Struct({\n transport: Schema.Literal(\"stdio\"),\n name: Schema.String,\n command: Schema.String,\n args: Schema.optional(Schema.Array(Schema.String)),\n env: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n cwd: Schema.optional(Schema.String),\n slug: Schema.optional(Schema.String),\n});\n\nconst McpAddServerInputSchema = Schema.Union([\n McpRemoteServerInputSchema,\n McpStdioServerInputSchema,\n]);\n\nconst McpAddServerOutputSchema = Schema.Struct({\n slug: Schema.String,\n});\n\nconst McpProbeEndpointInputSchema = Schema.Struct({\n endpoint: Schema.String,\n headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),\n});\n\nconst McpProbeEndpointOutputSchema = Schema.Struct({\n connected: Schema.Boolean,\n requiresAuthentication: Schema.Boolean,\n requiresOAuth: Schema.Boolean,\n supportsDynamicRegistration: Schema.Boolean,\n name: Schema.String,\n slug: Schema.String,\n toolCount: Schema.NullOr(Schema.Number),\n serverName: Schema.NullOr(Schema.String),\n});\n\n// ---------------------------------------------------------------------------\n// Extension input/output shapes — `addServer` registers an MCP integration. A\n// connection (the credential) is then created against it via\n// `executor.connections.create` / `oauth.start`. Types are inferred from the\n// schemas above so the wire shape and the TS surface can't drift.\n// ---------------------------------------------------------------------------\n\nexport type McpRemoteServerInput = typeof McpRemoteServerInputSchema.Type;\nexport type McpStdioServerInput = typeof McpStdioServerInputSchema.Type;\nexport type McpServerInput = typeof McpAddServerInputSchema.Type;\nexport type McpProbeResult = typeof McpProbeEndpointOutputSchema.Type;\nexport type McpProbeEndpointInput = typeof McpProbeEndpointInputSchema.Type;\n\nconst McpGetServerInputSchema = Schema.Struct({\n slug: Schema.String,\n});\n\nconst McpGetServerOutputSchema = Schema.Struct({\n integration: Schema.NullOr(Schema.Unknown),\n});\n\nconst schemaToStaticToolSchema = <A, I>(schema: Schema.Decoder<A, I>): StaticToolSchema<A, I> =>\n Schema.toStandardSchemaV1(Schema.toStandardJSONSchemaV1(schema) as never) as StaticToolSchema<\n A,\n I\n >;\n\nconst McpAddServerInputStandardSchema = schemaToStaticToolSchema(McpAddServerInputSchema);\nconst McpAddServerOutputStandardSchema = schemaToStaticToolSchema(McpAddServerOutputSchema);\nconst McpProbeEndpointInputStandardSchema = schemaToStaticToolSchema(McpProbeEndpointInputSchema);\nconst McpProbeEndpointOutputStandardSchema = schemaToStaticToolSchema(McpProbeEndpointOutputSchema);\nconst McpGetServerInputStandardSchema = schemaToStaticToolSchema(McpGetServerInputSchema);\nconst McpGetServerOutputStandardSchema = schemaToStaticToolSchema(McpGetServerOutputSchema);\n\nconst mcpToolFailure = (code: string, message: string, details?: unknown) =>\n ToolResult.fail({\n code,\n message,\n ...(details === undefined ? {} : { details }),\n });\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst slugFrom = (slug: string): IntegrationSlug => IntegrationSlug.make(slug);\n\nconst normalizeSlug = (input: McpServerInput): string =>\n input.slug ??\n deriveMcpNamespace({\n name: input.name,\n endpoint: input.transport === \"stdio\" ? undefined : input.endpoint,\n command: input.transport === \"stdio\" ? input.command : undefined,\n });\n\nconst toIntegrationConfig = (input: McpServerInput): McpIntegrationConfigType => {\n if (input.transport === \"stdio\") {\n return {\n transport: \"stdio\",\n command: input.command,\n args: input.args ? [...input.args] : undefined,\n env: input.env,\n cwd: input.cwd,\n };\n }\n return {\n transport: \"remote\",\n endpoint: input.endpoint,\n remoteTransport: input.remoteTransport ?? \"auto\",\n queryParams: input.queryParams,\n headers: input.headers,\n auth: input.auth ?? { kind: \"none\" },\n };\n};\n\ntype JsonSchemaObject = Record<string, unknown> & {\n readonly properties?: Record<string, unknown>;\n};\n\nconst McpCallToolResultJsonSchema = z.toJSONSchema(CallToolResultSchema) as JsonSchemaObject;\n\nconst mcpCallToolResultOutputSchema = (structuredContentSchema?: unknown): JsonSchemaObject => {\n const defaultStructuredContentSchema =\n McpCallToolResultJsonSchema.properties?.structuredContent ?? {};\n\n return {\n ...McpCallToolResultJsonSchema,\n properties: {\n ...McpCallToolResultJsonSchema.properties,\n structuredContent:\n structuredContentSchema === undefined\n ? defaultStructuredContentSchema\n : structuredContentSchema,\n isError: { const: false },\n },\n required:\n structuredContentSchema === undefined ? [\"content\"] : [\"content\", \"structuredContent\"],\n };\n};\n\n/** Build the executor-facing ToolDef for one discovered MCP tool, stamping the\n * real MCP tool name + upstream annotations into the persisted annotations so\n * they survive to invokeTool with no plugin-side store. */\nconst toToolDef = (entry: McpToolManifestEntry): ToolDef => {\n const destructive = entry.annotations?.destructiveHint === true;\n const stamp: McpToolStamp = {\n toolName: entry.toolName,\n ...(entry.annotations ? { upstream: entry.annotations } : {}),\n };\n const annotations: StampedAnnotations = {\n requiresApproval: destructive,\n ...(destructive ? { approvalDescription: entry.annotations?.title ?? entry.toolName } : {}),\n mcp: stamp,\n };\n return {\n name: ToolName.make(entry.toolId),\n description: entry.description ?? `MCP tool: ${entry.toolName}`,\n inputSchema: entry.inputSchema,\n outputSchema: mcpCallToolResultOutputSchema(entry.outputSchema),\n annotations: annotations as ToolAnnotations,\n };\n};\n\nconst McpTextContent = Schema.Struct({ type: Schema.Literal(\"text\"), text: Schema.String });\nconst McpToolCallEnvelope = Schema.Struct({\n isError: Schema.optional(Schema.Boolean),\n content: Schema.optional(Schema.Array(Schema.Unknown)),\n});\n\nconst decodeMcpTextContent = Schema.decodeUnknownOption(McpTextContent);\nconst decodeMcpToolCallEnvelope = Schema.decodeUnknownOption(McpToolCallEnvelope);\n\nconst extractMcpErrorMessage = (content: unknown): string => {\n if (Array.isArray(content)) {\n for (const item of content) {\n const decoded = Option.getOrUndefined(decodeMcpTextContent(item));\n if (decoded !== undefined && decoded.text.length > 0) return decoded.text;\n }\n }\n return \"MCP tool returned an error\";\n};\n\n/** Match `token` as a separator-bounded run inside a URL hostname or path,\n * used as a low-confidence detection hint when wire-shape detection fails. */\nconst urlMatchesToken = (url: URL, token: string): boolean => {\n const re = new RegExp(`(?:^|[^a-z0-9])${token}(?:$|[^a-z0-9])`, \"i\");\n return re.test(url.hostname) || re.test(url.pathname);\n};\n\n/** Translate a non-MCP probe outcome into a message a user can act on.\n * Exported for tests. */\nexport const userFacingProbeMessage = (\n shape: Extract<McpShapeProbeResult, { kind: \"not-mcp\" } | { kind: \"unreachable\" }>,\n): string => {\n if (shape.kind === \"unreachable\") {\n return \"Couldn't reach this URL. Check the address, your network, and that the server is running.\";\n }\n return Match.value(shape.category).pipe(\n Match.when(\n \"auth-required\",\n () =>\n \"This server requires authentication. Add credentials (Authorization header, query parameter, or API key) below and retry.\",\n ),\n Match.when(\n \"wrong-shape\",\n () =>\n \"This URL doesn't appear to host an MCP server. Double-check the address, including the path.\",\n ),\n Match.exhaustive,\n );\n};\n\n// ---------------------------------------------------------------------------\n// MCP-SDK OAuth provider adapter — wraps a pre-resolved access token so the\n// transport sends it as a Bearer header. Refresh is core's responsibility\n// (the connection row carries the OAuth grant); this adapter never initiates\n// a new flow and fails loudly if the SDK tries to.\n// ---------------------------------------------------------------------------\n\nconst makeOAuthProvider = (accessToken: string): OAuthClientProvider => ({\n get redirectUrl() {\n return \"http://localhost/oauth/callback\";\n },\n get clientMetadata() {\n return {\n redirect_uris: [\"http://localhost/oauth/callback\"],\n grant_types: [\"authorization_code\", \"refresh_token\"] as string[],\n response_types: [\"code\"] as string[],\n token_endpoint_auth_method: \"none\" as const,\n client_name: \"Executor\",\n };\n },\n clientInformation: () => undefined,\n saveClientInformation: () => undefined,\n tokens: () => ({ access_token: accessToken, token_type: \"Bearer\" }),\n saveTokens: () => undefined,\n redirectToAuthorization: async () => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- boundary: MCP SDK OAuthClientProvider callback can only signal reauthorization by throwing\n throw new Error(\"MCP OAuth re-authorization required\");\n },\n saveCodeVerifier: () => undefined,\n codeVerifier: () => {\n // oxlint-disable-next-line executor/no-try-catch-or-throw, executor/no-error-constructor -- boundary: MCP SDK OAuthClientProvider callback requires a thrown verifier failure\n throw new Error(\"No active PKCE verifier\");\n },\n saveDiscoveryState: () => undefined,\n discoveryState: () => undefined,\n});\n\n// ---------------------------------------------------------------------------\n// Connector input — render the integration config + the connection's resolved\n// value through the auth template into a live `ConnectorInput`.\n// ---------------------------------------------------------------------------\n\nconst buildConnectorInput = (\n config: McpIntegrationConfigType,\n value: string | null,\n allowStdio: boolean,\n): Effect.Effect<ConnectorInput, McpConnectionError> => {\n if (config.transport === \"stdio\") {\n if (!allowStdio) {\n return Effect.fail(\n new McpConnectionError({\n transport: \"stdio\",\n message:\n \"MCP stdio transport is disabled. Enable it by passing `dangerouslyAllowStdioMCP: true` to mcpPlugin() — only safe for trusted local contexts.\",\n }),\n );\n }\n return Effect.succeed({\n transport: \"stdio\" as const,\n command: config.command,\n args: config.args,\n env: config.env,\n cwd: config.cwd,\n } satisfies McpStdioIntegrationConfig);\n }\n\n const headers: Record<string, string> = { ...(config.headers ?? {}) };\n let authProvider: OAuthClientProvider | undefined;\n\n const auth = config.auth;\n if (auth.kind === \"header\" && value !== null) {\n headers[auth.headerName] = auth.prefix ? `${auth.prefix}${value}` : value;\n } else if (auth.kind === \"oauth2\" && value !== null) {\n authProvider = makeOAuthProvider(value);\n }\n\n return Effect.succeed({\n transport: \"remote\" as const,\n endpoint: config.endpoint,\n remoteTransport: config.remoteTransport ?? \"auto\",\n queryParams:\n config.queryParams && Object.keys(config.queryParams).length > 0\n ? config.queryParams\n : undefined,\n headers: Object.keys(headers).length > 0 ? headers : undefined,\n authProvider,\n });\n};\n\n// ---------------------------------------------------------------------------\n// Declared auth methods — project the stored MCP config into the catalog's\n// plugin-agnostic `AuthMethodDescriptor[]`. Pure and tolerant of a malformed or\n// foreign config blob (returns `[]`). Exported for tests.\n//\n// open (`none`) → one none method carrying no credential inputs\n// stdio → [] (no remote connection to configure)\n// header → one apikey method carrying the header placement\n// oauth2 → one oauth method carrying the MCP endpoint to probe\n// (`discoveryUrl`); endpoints are discovered live at\n// connect time, so they are NOT pre-resolved here. We\n// mark `supportsDynamicRegistration: true` because MCP\n// OAuth servers are expected to support RFC 7591 DCR;\n// the connect flow probes to confirm and falls back.\n// ---------------------------------------------------------------------------\n\nexport const describeMcpAuthMethods = (\n record: IntegrationRecord,\n): readonly AuthMethodDescriptor[] => {\n const config = parseMcpIntegrationConfig(record.config);\n if (!config || config.transport === \"stdio\") return [];\n\n const auth = config.auth;\n if (auth.kind === \"none\") {\n return [\n {\n id: \"none\",\n label: \"No authentication\",\n kind: \"none\",\n template: \"none\",\n },\n ];\n }\n if (auth.kind === \"header\") {\n return [\n {\n id: \"header\",\n label: \"API key (header)\",\n kind: \"apikey\",\n template: \"header\",\n placements: [{ carrier: \"header\", name: auth.headerName, prefix: auth.prefix ?? \"\" }],\n },\n ];\n }\n if (auth.kind === \"oauth2\") {\n return [\n {\n id: \"oauth2\",\n label: \"OAuth\",\n kind: \"oauth\",\n template: \"oauth2\",\n oauth: { discoveryUrl: config.endpoint, supportsDynamicRegistration: true },\n },\n ];\n }\n return [];\n};\n\nexport const describeMcpIntegrationDisplay = (\n record: IntegrationRecord,\n): { readonly url?: string } => {\n const config = parseMcpIntegrationConfig(record.config);\n if (!config || config.transport === \"stdio\") return {};\n return { url: config.endpoint };\n};\n\n// ---------------------------------------------------------------------------\n// Plugin factory\n// ---------------------------------------------------------------------------\n\nexport interface McpPluginOptions {\n /**\n * Allow configuring stdio-transport MCP servers. Off by default.\n *\n * Stdio servers spawn a local subprocess that inherits the parent\n * `process.env`. Only enable for trusted single-user contexts.\n */\n readonly dangerouslyAllowStdioMCP?: boolean;\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n}\n\nexport const mcpPlugin = definePlugin((options?: McpPluginOptions) => {\n const allowStdio = options?.dangerouslyAllowStdioMCP ?? false;\n\n const presetEntries = (\n allowStdio\n ? mcpPresets\n : mcpPresets.filter((preset) => !(\"transport\" in preset && preset.transport === \"stdio\"))\n ).map((preset) => ({\n id: preset.id,\n name: preset.name,\n summary: preset.summary,\n ...(\"url\" in preset && preset.url ? { url: preset.url } : {}),\n ...(\"endpoint\" in preset && preset.endpoint ? { endpoint: preset.endpoint } : {}),\n ...(preset.icon ? { icon: preset.icon } : {}),\n ...(preset.featured ? { featured: preset.featured } : {}),\n transport: (\"transport\" in preset && preset.transport === \"stdio\" ? \"stdio\" : \"remote\") as\n | \"stdio\"\n | \"remote\",\n ...(\"command\" in preset ? { command: preset.command } : {}),\n ...(\"args\" in preset && preset.args ? { args: [...preset.args] } : {}),\n ...(\"env\" in preset && preset.env ? { env: preset.env } : {}),\n }));\n\n return {\n id: MCP_PLUGIN_ID,\n packageName: \"@executor-js/plugin-mcp\",\n integrationPresets: presetEntries,\n // Surfaced to the client bundle via the Vite plugin. The MCP `./client`\n // factory reads `allowStdio` and gates the stdio tab + presets.\n clientConfig: { allowStdio },\n storage: () => ({}),\n\n extension: (ctx: PluginCtx) => {\n const httpClientLayer = options?.httpClientLayer ?? ctx.httpClientLayer;\n\n const probeEndpoint = (input: string | McpProbeEndpointInput) =>\n Effect.gen(function* () {\n const endpoint = typeof input === \"string\" ? input : input.endpoint;\n const trimmed = endpoint.trim();\n if (!trimmed) {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: \"Endpoint URL is required\",\n });\n }\n\n const name = yield* Effect.try({\n try: () => new URL(trimmed).hostname,\n catch: () => \"mcp\",\n }).pipe(Effect.orElseSucceed(() => \"mcp\"));\n const slug = deriveMcpNamespace({ endpoint: trimmed });\n\n const probeHeaders = typeof input === \"string\" ? undefined : input.headers;\n const probeQueryParams = typeof input === \"string\" ? undefined : input.queryParams;\n\n const connector = createMcpConnector({\n transport: \"remote\",\n endpoint: trimmed,\n headers: probeHeaders,\n queryParams: probeQueryParams,\n });\n\n const result = yield* discoverTools(connector).pipe(\n Effect.map((m) => ({ ok: true as const, manifest: m })),\n Effect.catch(() => Effect.succeed({ ok: false as const, manifest: null })),\n Effect.withSpan(\"mcp.plugin.discover_tools\"),\n );\n\n if (result.ok && result.manifest) {\n return {\n connected: true,\n requiresAuthentication: false,\n requiresOAuth: false,\n supportsDynamicRegistration: false,\n name: result.manifest.server?.name ?? name,\n slug,\n toolCount: result.manifest.tools.length,\n serverName: result.manifest.server?.name ?? null,\n } satisfies McpProbeResult;\n }\n\n // Confirm the endpoint actually speaks MCP before classifying it as\n // OAuth-protected (an OAuth-protected non-MCP service would\n // otherwise be misclassified).\n const shape = yield* probeMcpEndpointShape(trimmed, {\n httpClientLayer,\n headers: probeHeaders,\n queryParams: probeQueryParams,\n });\n if (shape.kind !== \"mcp\") {\n return yield* new McpConnectionError({\n transport: \"remote\",\n message: userFacingProbeMessage(shape),\n });\n }\n\n const probeResult = yield* ctx.oauth.probe({ url: trimmed }).pipe(\n Effect.map((oauth) => ({ ok: true as const, oauth })),\n Effect.catch(() => Effect.succeed({ ok: false as const, oauth: null })),\n Effect.withSpan(\"mcp.plugin.probe_oauth\"),\n );\n\n if (probeResult.ok) {\n return {\n connected: false,\n requiresAuthentication: true,\n requiresOAuth: true,\n supportsDynamicRegistration: probeResult.oauth.registrationEndpoint != null,\n name,\n slug,\n toolCount: null,\n serverName: null,\n } satisfies McpProbeResult;\n }\n\n if (shape.requiresAuth) {\n return {\n connected: false,\n requiresAuthentication: true,\n requiresOAuth: false,\n supportsDynamicRegistration: false,\n name,\n slug,\n toolCount: null,\n serverName: null,\n } satisfies McpProbeResult;\n }\n\n return yield* new McpConnectionError({\n transport: \"remote\",\n message:\n \"This endpoint looks like MCP, but Executor couldn't discover tools from it. Check the URL and try again.\",\n });\n }).pipe(\n Effect.withSpan(\"mcp.plugin.probe_endpoint\", {\n attributes: { \"mcp.endpoint\": typeof input === \"string\" ? input : input.endpoint },\n }),\n );\n\n const addServer = (input: McpServerInput) =>\n Effect.gen(function* () {\n const slug = normalizeSlug(input);\n const config = toIntegrationConfig(input);\n\n // Block re-adding an existing slug. The core `integrations.register`\n // primitive upserts (so boot re-registration is idempotent), but an\n // explicit add must NOT silently clobber an existing integration's\n // tools, connections, and policies. To add more auth, update the\n // existing integration instead.\n const existing = yield* ctx.core.integrations.get(slugFrom(slug));\n if (existing) {\n return yield* new IntegrationAlreadyExistsError({ slug: slugFrom(slug) });\n }\n\n yield* ctx.core.integrations\n .register({\n slug: slugFrom(slug),\n description: input.name,\n config,\n canRemove: true,\n canRefresh: true,\n })\n .pipe(\n Effect.withSpan(\"mcp.plugin.register_integration\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n return { slug };\n }).pipe(\n Effect.withSpan(\"mcp.plugin.add_server\", {\n attributes: {\n \"mcp.server.transport\": input.transport ?? \"remote\",\n \"mcp.server.name\": input.name,\n },\n }),\n );\n\n const removeServer = (slug: string) =>\n Effect.gen(function* () {\n const integration = slugFrom(slug);\n const record = yield* ctx.core.integrations.get(integration);\n const config = record ? parseMcpIntegrationConfig(record.config) : null;\n const legacyCandidates = legacyOAuthClientSlugCandidates(slug, record);\n const connections = yield* ctx.connections.list({ integration });\n const allConnections = yield* ctx.connections.list();\n const oauthClientSummaries = yield* ctx.oauth.listClients();\n const usedElsewhere = new Set(\n allConnections\n .filter((connection) => String(connection.integration) !== String(integration))\n .flatMap((connection) =>\n connection.oauthClient == null\n ? []\n : [\n oauthClientKey(\n connection.oauthClientOwner ?? connection.owner,\n connection.oauthClient,\n ),\n ],\n ),\n );\n const oauthClientsByKey = new Map(\n oauthClientSummaries.map((client) => [\n oauthClientKey(client.owner, client.slug),\n client,\n ]),\n );\n const clientsToRemove = new Map<\n string,\n { readonly owner: Owner; readonly slug: OAuthClientSlug }\n >();\n\n for (const connection of connections) {\n if (connection.oauthClient == null) continue;\n const owner = connection.oauthClientOwner ?? connection.owner;\n const key = oauthClientKey(owner, connection.oauthClient);\n const client = oauthClientsByKey.get(key);\n if (client?.origin.kind !== \"dynamic_client_registration\") continue;\n clientsToRemove.set(key, {\n owner,\n slug: connection.oauthClient,\n });\n }\n for (const client of oauthClientSummaries) {\n const key = oauthClientKey(client.owner, client.slug);\n if (usedElsewhere.has(key)) continue;\n if (\n client.origin.kind === \"dynamic_client_registration\" &&\n (client.origin.integration == null || String(client.origin.integration) === slug)\n ) {\n clientsToRemove.set(key, { owner: client.owner, slug: client.slug });\n continue;\n }\n if (legacyMcpClientMatches(client, legacyCandidates, config)) {\n clientsToRemove.set(key, { owner: client.owner, slug: client.slug });\n }\n }\n\n yield* ctx.core.integrations\n .remove(integration)\n .pipe(Effect.catchTag(\"IntegrationRemovalNotAllowedError\", () => Effect.void));\n\n yield* Effect.forEach(\n clientsToRemove.values(),\n (client) => ctx.oauth.removeClient(client.owner, client.slug),\n { discard: true },\n );\n }).pipe(\n Effect.withSpan(\"mcp.plugin.remove_server\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n\n const getServer = (slug: string) =>\n ctx.core.integrations.get(slugFrom(slug)).pipe(\n Effect.withSpan(\"mcp.plugin.get_server\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n\n const configureServer = (slug: string, config: McpIntegrationConfigType) =>\n ctx.core.integrations.update(slugFrom(slug), { config }).pipe(\n Effect.withSpan(\"mcp.plugin.configure_server\", {\n attributes: { \"mcp.integration.slug\": slug },\n }),\n );\n\n return {\n probeEndpoint,\n addServer,\n removeServer,\n getServer,\n configureServer,\n };\n },\n\n // -----------------------------------------------------------------------\n // Per-connection tool production. Dial the server using the connection's\n // resolved value (rendered through the integration's auth template) and\n // list its tools. The real MCP tool name + upstream annotations are\n // stamped into each ToolDef's annotations so invokeTool can recover them.\n // Discovery failures (auth not ready, server down) yield an empty tool set\n // rather than failing — the connection still lands and can be refreshed.\n // -----------------------------------------------------------------------\n resolveTools: ({ config, connection, getValue }) =>\n Effect.gen(function* () {\n const parsed = parseMcpIntegrationConfig(config);\n if (!parsed) return { tools: [] as readonly ToolDef[] };\n\n const value = yield* getValue().pipe(Effect.orElseSucceed(() => null));\n\n const built = yield* buildConnectorInput(parsed, value, allowStdio).pipe(\n Effect.map((ci) => createMcpConnector(ci)),\n Effect.result,\n );\n\n const manifest = Result.isSuccess(built)\n ? yield* discoverTools(built.success).pipe(\n Effect.map((m) => ({ ok: true as const, manifest: m })),\n Effect.catch(() => Effect.succeed({ ok: false as const, manifest: null })),\n Effect.withSpan(\"mcp.plugin.discover_tools\", {\n attributes: { \"mcp.connection.name\": String(connection.name) },\n }),\n )\n : { ok: false as const, manifest: null };\n\n const entries = manifest.ok && manifest.manifest ? manifest.manifest.tools : [];\n return { tools: entries.map(toToolDef) };\n }).pipe(\n Effect.withSpan(\"mcp.plugin.resolve_tools\", {\n attributes: { \"mcp.connection.name\": String(connection.name) },\n }),\n ) as Effect.Effect<{ readonly tools: readonly ToolDef[] }, StorageFailure>,\n\n invokeTool: ({ toolRow, credential, args, elicit }) =>\n Effect.gen(function* () {\n const parsed = parseMcpIntegrationConfig(credential.config);\n if (!parsed) {\n return yield* new McpConnectionError({\n transport: \"auto\",\n message: `MCP integration \"${toolRow.integration}\" has no usable config`,\n });\n }\n\n const stamp = readStamp(toolRow.annotations);\n if (!stamp) {\n return yield* new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: `Tool \"${toolRow.name}\" is missing its MCP binding — refresh the connection`,\n });\n }\n\n const transport: string =\n parsed.transport === \"stdio\" ? \"stdio\" : (parsed.remoteTransport ?? \"auto\");\n\n const connector: McpConnector = yield* buildConnectorInput(\n parsed,\n credential.value,\n allowStdio,\n ).pipe(Effect.map((ci) => createMcpConnector(ci)));\n\n const raw = yield* invokeMcpTool({\n toolId: String(toolRow.name),\n toolName: stamp.toolName,\n args,\n transport,\n connector,\n elicit,\n });\n\n const envelope = Option.getOrUndefined(decodeMcpToolCallEnvelope(raw));\n if (envelope?.isError === true) {\n return ToolResult.fail({\n code: \"mcp_tool_error\",\n message: extractMcpErrorMessage(envelope.content),\n details: { content: envelope.content },\n });\n }\n return ToolResult.ok(raw);\n }).pipe(\n Effect.catchTag(\"McpConnectionError\", ({ message }) =>\n Effect.succeed(\n authToolFailure({\n code: \"connection_rejected\",\n message,\n source: { id: String(credential.integration) },\n credential: { kind: \"upstream\", label: String(credential.connection) },\n }),\n ),\n ),\n Effect.withSpan(\"mcp.plugin.invoke_tool\", {\n attributes: {\n \"mcp.tool.name\": String(toolRow.name),\n \"mcp.integration.slug\": String(toolRow.integration),\n },\n }),\n ),\n\n detect: ({ ctx, url }: { readonly ctx: PluginCtx; readonly url: string }) =>\n Effect.gen(function* () {\n const httpClientLayer = options?.httpClientLayer ?? ctx.httpClientLayer;\n const trimmed = url.trim();\n if (!trimmed) return null;\n\n const parsed = yield* Effect.try({\n try: () => new URL(trimmed),\n catch: (cause) => cause,\n }).pipe(Effect.option);\n if (Option.isNone(parsed)) return null;\n\n const name = parsed.value.hostname || \"mcp\";\n const slug = deriveMcpNamespace({ endpoint: trimmed });\n\n const connector = createMcpConnector({ transport: \"remote\", endpoint: trimmed });\n\n const connected = yield* discoverTools(connector).pipe(\n Effect.map(() => true),\n Effect.catch(() => Effect.succeed(false)),\n Effect.withSpan(\"mcp.plugin.discover_tools\"),\n );\n\n if (connected) {\n return {\n kind: MCP_PLUGIN_ID,\n confidence: \"high\" as const,\n endpoint: trimmed,\n name,\n slug,\n };\n }\n\n const shape = yield* probeMcpEndpointShape(trimmed, { httpClientLayer });\n if (shape.kind === \"mcp\") {\n return {\n kind: MCP_PLUGIN_ID,\n confidence: \"high\" as const,\n endpoint: trimmed,\n name,\n slug,\n };\n }\n\n // Low-confidence URL-token fallback when wire-shape detection can't\n // confirm MCP but the URL itself is a strong hint.\n if (urlMatchesToken(parsed.value, \"mcp\")) {\n return {\n kind: MCP_PLUGIN_ID,\n confidence: \"low\" as const,\n endpoint: trimmed,\n name,\n slug,\n };\n }\n\n return null;\n }).pipe(\n Effect.catch(() => Effect.succeed(null)),\n Effect.withSpan(\"mcp.plugin.detect\", {\n attributes: { \"mcp.endpoint\": url },\n }),\n ),\n\n // Honour upstream destructiveHint from MCP ToolAnnotations using the stamp\n // persisted in each tool row's annotations.\n resolveAnnotations: ({ toolRows }) =>\n Effect.sync(() => {\n const out: Record<string, ToolAnnotations> = {};\n for (const row of toolRows) {\n const stamp = readStamp(row.annotations);\n const ann = stamp?.upstream;\n if (ann?.destructiveHint === true) {\n out[String(row.name)] = {\n requiresApproval: true,\n approvalDescription: ann.title ?? stamp?.toolName ?? String(row.name),\n };\n } else {\n out[String(row.name)] = { requiresApproval: false };\n }\n }\n return out;\n }),\n\n describeAuthMethods: describeMcpAuthMethods,\n describeIntegrationDisplay: describeMcpIntegrationDisplay,\n\n integrationConfigure: {\n type: \"mcp\",\n configure: ({ ctx, integration, config }) =>\n Effect.gen(function* () {\n const next = parseMcpIntegrationConfig(config);\n if (!next) return;\n yield* ctx.core.integrations.update(integration, { config: next });\n }),\n },\n\n staticSources: (self) => [\n {\n id: \"mcp\",\n kind: \"executor\",\n name: \"MCP\",\n tools: [\n tool({\n name: \"probeEndpoint\",\n description:\n \"Probe a remote MCP endpoint before adding it. If the result requires OAuth, run the core OAuth handoff (`oauth.probe`, `oauth.start`) to mint a connection; otherwise create a connection with `connections.create` carrying the API key or header value.\",\n inputSchema: McpProbeEndpointInputStandardSchema,\n outputSchema: McpProbeEndpointOutputStandardSchema,\n execute: (input) =>\n self.probeEndpoint(input as McpProbeEndpointInput).pipe(\n Effect.map(ToolResult.ok),\n Effect.catchTag(\"McpConnectionError\", ({ message, transport }) =>\n Effect.succeed(mcpToolFailure(\"mcp_connection_failed\", message, { transport })),\n ),\n ),\n }),\n tool({\n name: \"getServer\",\n description:\n \"Inspect a registered MCP integration, including transport, endpoint/command, and auth template. Use this before creating a connection (`connections.create` / `oauth.start`).\",\n inputSchema: McpGetServerInputStandardSchema,\n outputSchema: McpGetServerOutputStandardSchema,\n execute: (input) => {\n const args = input as typeof McpGetServerInputSchema.Type;\n return Effect.map(self.getServer(args.slug), (integration) =>\n ToolResult.ok({ integration }),\n );\n },\n }),\n tool({\n name: \"addServer\",\n description:\n \"Register an MCP server in the catalog as an integration. Returns its `slug`. Then create a connection against it: for header/API-key auth call `connections.create` with the value; for OAuth-protected servers run `oauth.probe` + `oauth.start`. Tools are produced per-connection at connection create / refresh.\",\n annotations: {\n requiresApproval: true,\n approvalDescription: \"Add an MCP server\",\n },\n inputSchema: McpAddServerInputStandardSchema,\n outputSchema: McpAddServerOutputStandardSchema,\n execute: (rawInput) => {\n const input = rawInput as typeof McpAddServerInputSchema.Type;\n return self.addServer(input as McpServerInput).pipe(\n Effect.map(ToolResult.ok),\n Effect.catchTag(\n \"IntegrationAlreadyExistsError\",\n ({ slug }: IntegrationAlreadyExistsError) =>\n Effect.succeed(\n mcpToolFailure(\n \"integration_already_exists\",\n `Integration ${slug} already exists; update it instead of re-adding.`,\n ),\n ),\n ),\n );\n },\n }),\n ],\n },\n ],\n };\n});\n\n// ---------------------------------------------------------------------------\n// McpPluginExtension — shape of `executor.mcp` for consumers (api/, react/).\n// ---------------------------------------------------------------------------\n\nexport type McpExtensionFailure = McpConnectionError | McpToolDiscoveryError | StorageFailure;\n\nexport interface McpPluginExtension {\n readonly probeEndpoint: (\n input: string | McpProbeEndpointInput,\n ) => Effect.Effect<McpProbeResult, McpExtensionFailure>;\n readonly addServer: (\n input: McpServerInput,\n ) => Effect.Effect<\n { readonly slug: string },\n McpExtensionFailure | IntegrationAlreadyExistsError\n >;\n readonly removeServer: (slug: string) => Effect.Effect<void, McpExtensionFailure>;\n readonly getServer: (\n slug: string,\n ) => Effect.Effect<\n (Integration & { readonly config: IntegrationConfig }) | null,\n McpExtensionFailure\n >;\n readonly configureServer: (\n slug: string,\n config: McpIntegrationConfigType,\n ) => Effect.Effect<void, McpExtensionFailure>;\n}\n","import type { OAuthClientProvider } from \"@modelcontextprotocol/sdk/client/auth.js\";\nimport { Client } from \"@modelcontextprotocol/sdk/client/index.js\";\nimport { SSEClientTransport } from \"@modelcontextprotocol/sdk/client/sse.js\";\nimport { StreamableHTTPClientTransport } from \"@modelcontextprotocol/sdk/client/streamableHttp.js\";\nimport { CfWorkerJsonSchemaValidator } from \"@modelcontextprotocol/sdk/validation/cfworker\";\nimport { Effect } from \"effect\";\n\n// NOTE: `StdioClientTransport` is NOT imported eagerly. The upstream module\n// (`@modelcontextprotocol/sdk/client/stdio.js`) touches `node:child_process`\n// at evaluation time, which crashes workerd (incl. vitest-pool-workers) at\n// SIGSEGV on module instantiation. Cloud callers set\n// `dangerouslyAllowStdioMCP: false` and never reach the stdio branch below;\n// prod bundles that DO use stdio load it via a dynamic import inside the\n// stdio branch of `createMcpConnector`.\n\nimport type { McpRemoteIntegrationConfig, McpStdioIntegrationConfig } from \"./types\";\nimport { McpConnectionError } from \"./errors\";\n\n// ---------------------------------------------------------------------------\n// Connection type\n// ---------------------------------------------------------------------------\n\nexport type McpConnection = {\n readonly client: Client;\n readonly close: () => Promise<void>;\n};\n\nexport type McpConnector = Effect.Effect<McpConnection, McpConnectionError>;\n\n// ---------------------------------------------------------------------------\n// Connector input — extends stored source data with resolved auth\n// ---------------------------------------------------------------------------\n\nexport type RemoteConnectorInput = Omit<\n McpRemoteIntegrationConfig,\n \"auth\" | \"remoteTransport\" | \"headers\" | \"queryParams\"\n> & {\n readonly remoteTransport?: McpRemoteIntegrationConfig[\"remoteTransport\"];\n readonly headers?: Record<string, string>;\n readonly queryParams?: Record<string, string>;\n readonly authProvider?: OAuthClientProvider;\n};\n\nexport type StdioConnectorInput = McpStdioIntegrationConfig;\n\nexport type ConnectorInput = RemoteConnectorInput | StdioConnectorInput;\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst buildEndpointUrl = (endpoint: string, queryParams: Record<string, string>): URL => {\n const url = new URL(endpoint);\n for (const [key, value] of Object.entries(queryParams)) {\n url.searchParams.set(key, value);\n }\n return url;\n};\n\n// Use the cfworker JSON Schema validator instead of the SDK's default\n// (Ajv). Ajv compiles schemas via `new Function(...)`, which throws\n// `Code generation from strings disallowed for this context` when the\n// MCP plugin runs inside a Cloudflare Worker (executor.sh). The\n// cfworker validator does not use code generation and works in every\n// runtime we ship to.\nconst createClient = (): Client =>\n new Client(\n { name: \"executor-mcp\", version: \"0.1.0\" },\n {\n capabilities: { elicitation: { form: {}, url: {} } },\n jsonSchemaValidator: new CfWorkerJsonSchemaValidator(),\n },\n );\n\nconst connectionFromClient = (client: Client): McpConnection => ({\n client,\n close: () => client.close(),\n});\n\nconst connectClient = (input: {\n transport: string;\n createTransport: () => Parameters<Client[\"connect\"]>[0];\n}): Effect.Effect<McpConnection, McpConnectionError> =>\n Effect.gen(function* () {\n const client = createClient();\n const transportInstance = input.createTransport();\n\n yield* Effect.tryPromise({\n try: () => client.connect(transportInstance),\n catch: () =>\n new McpConnectionError({\n transport: input.transport,\n message: `Failed connecting via ${input.transport}`,\n }),\n }).pipe(\n Effect.withSpan(\"plugin.mcp.connection.handshake\", {\n attributes: { \"plugin.mcp.transport\": input.transport },\n }),\n );\n\n return connectionFromClient(client);\n });\n\n// ---------------------------------------------------------------------------\n// Public factory\n// ---------------------------------------------------------------------------\n\nexport const createMcpConnector = (input: ConnectorInput): McpConnector => {\n if (input.transport === \"stdio\") {\n const command = input.command.trim();\n if (!command) {\n return Effect.fail(\n new McpConnectionError({\n transport: \"stdio\",\n message: \"MCP stdio transport requires a command\",\n }),\n );\n }\n\n return Effect.gen(function* () {\n // Dynamic import so the underlying module (which evaluates\n // `node:child_process`) is only loaded when stdio is actually used.\n const { createStdioTransport } = yield* Effect.tryPromise({\n try: () => import(\"./stdio-connector\"),\n catch: () =>\n new McpConnectionError({\n transport: \"stdio\",\n message: \"Failed to load stdio transport module\",\n }),\n });\n\n return yield* connectClient({\n transport: \"stdio\",\n createTransport: () =>\n createStdioTransport({\n command,\n args: input.args,\n env: input.env,\n cwd: input.cwd?.trim().length ? input.cwd.trim() : undefined,\n }),\n });\n });\n }\n\n // Remote transport\n const headers = input.headers ?? {};\n const remoteTransport = input.remoteTransport ?? \"auto\";\n const requestInit = Object.keys(headers).length > 0 ? { headers } : undefined;\n\n const endpoint = buildEndpointUrl(input.endpoint, input.queryParams ?? {});\n\n const connectStreamableHttp = connectClient({\n transport: \"streamable-http\",\n createTransport: () =>\n new StreamableHTTPClientTransport(endpoint, {\n requestInit,\n authProvider: input.authProvider,\n }),\n });\n\n const connectSse = connectClient({\n transport: \"sse\",\n createTransport: () =>\n new SSEClientTransport(endpoint, {\n requestInit,\n authProvider: input.authProvider,\n }),\n });\n\n if (remoteTransport === \"streamable-http\") return connectStreamableHttp;\n if (remoteTransport === \"sse\") return connectSse;\n\n // auto — try streamable-http first, fall back to SSE\n return connectStreamableHttp.pipe(Effect.catch(() => connectSse));\n};\n","// ---------------------------------------------------------------------------\n// MCP tool discovery — connect to an MCP server and list its tools\n// ---------------------------------------------------------------------------\n\nimport { Effect } from \"effect\";\n\nimport type { McpConnector } from \"./connection\";\nimport { McpToolDiscoveryError } from \"./errors\";\nimport {\n extractManifestFromListToolsResult,\n isListToolsResult,\n type McpToolManifest,\n} from \"./manifest\";\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\n/**\n * Connect to an MCP server and discover all available tools.\n * Returns the parsed manifest containing server metadata and tool entries.\n */\nexport const discoverTools = (\n connector: McpConnector,\n): Effect.Effect<McpToolManifest, McpToolDiscoveryError> =>\n Effect.gen(function* () {\n // Acquire connection\n const connection = yield* connector.pipe(\n Effect.mapError(\n ({ message }) =>\n new McpToolDiscoveryError({\n stage: \"connect\",\n message: `Failed connecting to MCP server: ${message}`,\n }),\n ),\n );\n\n // List tools\n const listResult = yield* Effect.tryPromise({\n try: () => connection.client.listTools(),\n catch: () =>\n new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: \"Failed listing MCP tools\",\n }),\n });\n\n if (!isListToolsResult(listResult)) {\n yield* closeConnection(connection);\n return yield* new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: \"MCP listTools response did not match the expected schema\",\n });\n }\n\n const manifest = extractManifestFromListToolsResult(listResult, {\n serverInfo: connection.client.getServerVersion?.(),\n });\n\n // Close the connection after discovery\n yield* closeConnection(connection);\n\n return manifest;\n });\n\nconst closeConnection = (connection: {\n readonly close: () => Promise<void>;\n}): Effect.Effect<void, never> =>\n Effect.ignore(\n Effect.tryPromise({\n try: () => connection.close(),\n catch: () =>\n new McpToolDiscoveryError({\n stage: \"list_tools\",\n message: \"Failed closing MCP connection\",\n }),\n }),\n );\n","// ---------------------------------------------------------------------------\n// MCP tool invocation — shared helper called from plugin.invokeTool.\n//\n// Responsible for:\n// 1. Dialing a fresh MCP client connection for the call (no DB-connection\n// caching — request-scoped per the Hyperdrive rule; each invoke acquires\n// and releases its own connection).\n// 2. Installing a per-invocation `ElicitRequestSchema` handler that bridges\n// MCP's elicit capability into the host's elicit function threaded via\n// `InvokeToolInput.elicit`.\n// 3. Calling `client.callTool({ name, arguments })`.\n// ---------------------------------------------------------------------------\n\nimport { Cause, Effect, Exit, Option, Predicate, Schema } from \"effect\";\n\nimport { ElicitRequestSchema } from \"@modelcontextprotocol/sdk/types.js\";\n\nimport {\n ElicitationId,\n FormElicitation,\n UrlElicitation,\n type Elicit,\n type ElicitationRequest,\n} from \"@executor-js/sdk/core\";\n\nimport { McpConnectionError, McpInvocationError } from \"./errors\";\nimport type { McpConnection, McpConnector } from \"./connection\";\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nconst ArgsRecord = Schema.Record(Schema.String, Schema.Unknown);\nconst decodeArgsRecord = Schema.decodeUnknownOption(ArgsRecord);\n\nconst argsRecord = (value: unknown): Record<string, unknown> =>\n Option.getOrElse(decodeArgsRecord(value), () => ({}));\n\n// ---------------------------------------------------------------------------\n// Elicitation bridge — decode incoming MCP ElicitRequest, route through\n// the host's elicit function, marshal the response back to MCP shape.\n// ---------------------------------------------------------------------------\n\nconst McpElicitParams = Schema.Union([\n Schema.Struct({\n mode: Schema.Literal(\"url\"),\n message: Schema.String,\n url: Schema.String,\n elicitationId: Schema.optional(Schema.String),\n id: Schema.optional(Schema.String),\n }),\n Schema.Struct({\n mode: Schema.optional(Schema.Literal(\"form\")),\n message: Schema.String,\n requestedSchema: Schema.Record(Schema.String, Schema.Unknown),\n }),\n]);\ntype McpElicitParams = typeof McpElicitParams.Type;\n\nconst decodeElicitParams = Schema.decodeUnknownSync(McpElicitParams);\n\nconst toElicitationRequest = (params: McpElicitParams): ElicitationRequest =>\n params.mode === \"url\"\n ? UrlElicitation.make({\n message: params.message,\n url: params.url,\n elicitationId: ElicitationId.make(params.elicitationId ?? params.id ?? \"\"),\n })\n : FormElicitation.make({\n message: params.message,\n requestedSchema: params.requestedSchema,\n });\n\nconst installElicitationHandler = (client: McpConnection[\"client\"], elicit: Elicit): void => {\n client.setRequestHandler(ElicitRequestSchema, async (request: { params: unknown }) => {\n const params = decodeElicitParams(request.params);\n const req = toElicitationRequest(params);\n // Use runPromiseExit so we can inspect typed failures — `elicit`\n // fails with `ElicitationDeclinedError` on decline/cancel, which\n // we translate into the equivalent MCP elicit response instead of\n // surfacing as a JSON-RPC error.\n const exit = await Effect.runPromiseExit(elicit(req));\n if (Exit.isSuccess(exit)) {\n const response = exit.value;\n return {\n action: response.action,\n ...(response.action === \"accept\" && response.content ? { content: response.content } : {}),\n };\n }\n const failure = exit.cause.reasons.find(Cause.isFailReason);\n if (failure) {\n const err = failure.error;\n if (Predicate.isTagged(err, \"ElicitationDeclinedError\")) {\n const action =\n Predicate.hasProperty(err, \"action\") && err.action === \"cancel\" ? \"cancel\" : \"decline\";\n return { action };\n }\n }\n // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: MCP SDK async request handlers signal unexpected failures by rejecting\n throw Cause.squash(exit.cause);\n });\n};\n\n// ---------------------------------------------------------------------------\n// Single tool call — install handler, callTool, return raw result\n// ---------------------------------------------------------------------------\n\nconst useConnection = (\n connection: McpConnection,\n toolName: string,\n args: Record<string, unknown>,\n elicit: Elicit,\n): Effect.Effect<unknown, McpInvocationError> =>\n Effect.gen(function* () {\n installElicitationHandler(connection.client, elicit);\n return yield* Effect.tryPromise({\n try: () => connection.client.callTool({ name: toolName, arguments: args }),\n catch: () =>\n new McpInvocationError({\n toolName,\n message: `MCP tool call failed for ${toolName}`,\n }),\n }).pipe(\n Effect.withSpan(\"plugin.mcp.client.call_tool\", {\n attributes: { \"mcp.tool.name\": toolName },\n }),\n );\n });\n\n// ---------------------------------------------------------------------------\n// Public API\n// ---------------------------------------------------------------------------\n\nexport interface InvokeMcpToolInput {\n readonly toolId: string;\n /** The real MCP tool name advertised by the server. */\n readonly toolName: string;\n readonly args: unknown;\n readonly transport: string;\n /** Dials a fresh connection. The connection is closed after the call. */\n readonly connector: McpConnector;\n readonly elicit: Elicit;\n}\n\nexport const invokeMcpTool = (\n input: InvokeMcpToolInput,\n): Effect.Effect<unknown, McpConnectionError | McpInvocationError> =>\n Effect.gen(function* () {\n const args = argsRecord(input.args);\n\n const connection = yield* Effect.acquireRelease(\n input.connector.pipe(\n Effect.withSpan(\"plugin.mcp.connection.acquire\", {\n attributes: { \"plugin.mcp.transport\": input.transport },\n }),\n ),\n (conn) =>\n Effect.ignore(\n Effect.tryPromise({\n try: () => conn.close(),\n catch: () =>\n new McpConnectionError({\n transport: input.transport,\n message: \"Failed to close MCP connection\",\n }),\n }),\n ),\n );\n\n return yield* useConnection(connection, input.toolName, args, input.elicit);\n }).pipe(\n Effect.scoped,\n Effect.withSpan(\"plugin.mcp.invoke\", {\n attributes: {\n \"mcp.tool.name\": input.toolName,\n \"plugin.mcp.tool_id\": input.toolId,\n \"plugin.mcp.transport\": input.transport,\n },\n }),\n );\n","// ---------------------------------------------------------------------------\n// MCP endpoint shape probe — decide whether an unknown HTTP endpoint is\n// actually speaking MCP before we try to classify it as such.\n//\n// Background:\n//\n// `discoverTools` (via the MCP SDK's StreamableHTTP / SSE transport)\n// fails for every non-MCP endpoint too — 200-with-HTML, 400-GraphQL,\n// 404, etc. all surface as the same opaque transport error. We need\n// our own classifier that distinguishes \"real MCP\" from\n// \"OAuth-protected non-MCP service\" without relying on RFC 9728/8414\n// metadata, since (a) plenty of non-MCP APIs publish that metadata,\n// and (b) plenty of real MCP servers authenticate with static API\n// keys and publish no OAuth metadata at all (e.g. cubic.dev).\n//\n// The probe issues an unauth JSON-RPC `initialize` POST and accepts\n// only the wire shapes a real MCP server can return:\n//\n// - 2xx with `Content-Type: text/event-stream` — streamable HTTP\n// transport, body is an SSE stream we don't consume.\n// - 2xx with `Content-Type: application/json` whose body parses as a\n// JSON-RPC 2.0 envelope (`{jsonrpc:\"2.0\", result|error|method,...}`).\n// - 401 with `WWW-Authenticate: Bearer` AND a JSON-RPC error envelope\n// in the body. The body shape is what separates a real MCP server\n// from an unrelated OAuth-protected API: GraphQL/REST/HTML 401s\n// don't shape themselves as JSON-RPC.\n//\n// When POST returns 404/405/406/415 we retry with GET + `Accept:\n// text/event-stream` to support legacy SSE-only servers; that path\n// only accepts 2xx with `text/event-stream` or the same 401+Bearer\n// shape.\n//\n// One `fetch` (occasionally two), no MCP-SDK session state, no OAuth\n// round-trip, no DCR — every non-MCP endpoint exits here.\n// ---------------------------------------------------------------------------\n\nimport { Data, Duration, Effect, Layer, Option, Schema } from \"effect\";\nimport { FetchHttpClient, HttpClient, HttpClientRequest } from \"effect/unstable/http\";\n\n/** MCP initialize request body used as the shape probe. Any real MCP\n * server either answers it (unauth-OK server) or returns the spec-\n * mandated 401 + WWW-Authenticate pair. A non-MCP endpoint hit with\n * this body will respond with whatever it does for unknown JSON\n * payloads — 400, 404, HTML, a GraphQL error envelope, etc. — none of\n * which match the gate below. */\nconst INITIALIZE_BODY = JSON.stringify({\n jsonrpc: \"2.0\",\n id: 1,\n method: \"initialize\",\n params: {\n protocolVersion: \"2025-06-18\",\n capabilities: {},\n clientInfo: { name: \"executor-probe\", version: \"0\" },\n },\n});\n\n/** Header-name lookup is case-insensitive per RFC 7230. `fetch`'s\n * `Response.headers` already lower-cases, but we normalise explicitly\n * to stay robust against test mocks that construct `Headers` loosely. */\nconst readHeader = (headers: Readonly<Record<string, string>>, name: string): string | null => {\n const direct = headers[name];\n if (direct !== undefined) return direct;\n const lower = name.toLowerCase();\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === lower) return v;\n }\n return null;\n};\n\nclass ProbeTransportError extends Data.TaggedError(\"ProbeTransportError\")<{\n readonly reason: string;\n readonly cause: unknown;\n}> {}\n\nconst decodeJsonString = Schema.decodeUnknownOption(Schema.fromJsonString(Schema.Unknown));\n\nconst asObject = (body: string): Record<string, unknown> | null => {\n if (!body) return null;\n const parsed = decodeJsonString(body);\n if (Option.isNone(parsed)) return null;\n const value = parsed.value;\n if (typeof value !== \"object\" || value === null || Array.isArray(value)) return null;\n return value as Record<string, unknown>;\n};\n\n/** Quick check that a body parses as a JSON-RPC 2.0 envelope. The MCP wire\n * protocol is JSON-RPC 2.0, so a real MCP server's response to `initialize`\n * (whether 2xx with the result, or a 401 error envelope) carries this\n * shape. Non-MCP services don't — GraphQL APIs return `{errors:[...]}`,\n * REST APIs return their own envelope, marketing pages return HTML. */\nconst isJsonRpcEnvelope = (body: string): boolean => {\n const obj = asObject(body);\n if (!obj) return false;\n if (obj.jsonrpc !== \"2.0\") return false;\n return \"result\" in obj || \"error\" in obj || \"method\" in obj;\n};\n\n/** Quick check that a body parses as an RFC 6750 OAuth Bearer error\n * envelope (`{error: \"invalid_token\", error_description?: ..., ...}`).\n * Real MCP servers like Atlassian return this shape on unauth requests\n * even when their WWW-Authenticate omits `resource_metadata=`. The\n * GraphQL `{errors: [...]}` envelope, which a non-MCP OAuth-protected\n * GraphQL API would return, is explicitly excluded. */\nconst isOAuthErrorBody = (body: string): boolean => {\n const obj = asObject(body);\n if (!obj) return false;\n if (Array.isArray(obj.errors)) return false;\n return typeof obj.error === \"string\";\n};\n\n/** RFC 9728 protected-resource-metadata document. We only need the two\n * fields that prove the document genuinely describes an OAuth-protected\n * resource: `resource` (the resource identifier) and a non-empty\n * `authorization_servers` list. */\nconst ProtectedResourceMetadata = Schema.Struct({\n resource: Schema.String,\n authorization_servers: Schema.Array(Schema.String),\n});\nconst decodeProtectedResourceMetadata = Schema.decodeUnknownOption(\n Schema.fromJsonString(ProtectedResourceMetadata),\n);\n\n/** RFC 9728 §3.1 path-scoped well-known URL: insert\n * `/.well-known/oauth-protected-resource` before the resource's path\n * component. `https://host/api/mcp` → `https://host/.well-known/oauth-\n * protected-resource/api/mcp`. This is exactly the URL the MCP\n * authorization spec tells clients to construct. */\nconst protectedResourceMetadataUrl = (endpoint: URL): string => {\n const path = endpoint.pathname === \"/\" ? \"\" : endpoint.pathname;\n return `${endpoint.origin}/.well-known/oauth-protected-resource${path}`;\n};\n\n/** The RFC 9728 `resource` value must actually describe this endpoint\n * before we trust the document — an exact URL match, or a same-origin\n * parent whose path is a prefix of the endpoint's. Guards against a\n * shared host serving protected-resource metadata for some unrelated\n * resource. */\nconst resourceMatchesEndpoint = (resource: string, endpoint: URL): boolean => {\n if (!URL.canParse(resource)) return false;\n const parsed = new URL(resource);\n if (parsed.origin !== endpoint.origin) return false;\n const resourcePath = parsed.pathname.replace(/\\/+$/, \"\");\n const endpointPath = endpoint.pathname.replace(/\\/+$/, \"\");\n return endpointPath === resourcePath || endpointPath.startsWith(`${resourcePath}/`);\n};\n\n/** Workaround for MCP servers that omit (or under-specify) the\n * `WWW-Authenticate` challenge on their 401 — e.g. Datadog's\n * `mcp.datadoghq.com` returns a bare `401 {\"errors\":[\"Unauthorized\"]}`\n * with no header at all, so the wire-shape gate above can't tell it\n * apart from an unrelated OAuth-protected API and the user lands on the\n * manual-credentials prompt instead of an OAuth sign-in.\n *\n * The MCP authorization spec still requires such servers to publish\n * RFC 9728 metadata at the path-scoped well-known URL. A document there\n * whose `resource` matches this endpoint is a deliberate, MCP-spec-\n * specific signal a generic OAuth API would not emit — strong enough to\n * classify the endpoint as MCP so the OAuth flow can start. */\nconst probeProtectedResourceMetadata = (\n client: HttpClient.HttpClient,\n endpoint: URL,\n timeoutMs: number,\n): Effect.Effect<boolean> =>\n Effect.gen(function* () {\n const response = yield* client\n .execute(\n HttpClientRequest.get(protectedResourceMetadataUrl(endpoint)).pipe(\n HttpClientRequest.setHeader(\"accept\", \"application/json\"),\n ),\n )\n .pipe(Effect.timeout(Duration.millis(timeoutMs)));\n if (response.status < 200 || response.status >= 300) return false;\n const body = yield* response.text.pipe(\n Effect.timeout(Duration.millis(timeoutMs)),\n Effect.catch(() => Effect.succeed(\"\")),\n );\n const metadata = decodeProtectedResourceMetadata(body);\n if (Option.isNone(metadata)) return false;\n if (metadata.value.authorization_servers.length === 0) return false;\n return resourceMatchesEndpoint(metadata.value.resource, endpoint);\n }).pipe(Effect.catch(() => Effect.succeed(false)));\n\nconst ErrorMessageShape = Schema.Struct({ message: Schema.String });\nconst decodeErrorMessageShape = Schema.decodeUnknownOption(ErrorMessageShape);\n\nconst reasonFromBoundaryCause = (cause: unknown): string => {\n const messageShape = decodeErrorMessageShape(cause);\n if (Option.isSome(messageShape)) return messageShape.value.message;\n if (typeof cause === \"string\") return cause;\n if (typeof cause === \"number\" || typeof cause === \"boolean\" || typeof cause === \"bigint\") {\n return `${cause}`;\n }\n if (typeof cause === \"symbol\") return cause.description ?? \"symbol\";\n if (cause === null) return \"null\";\n if (typeof cause === \"undefined\") return \"undefined\";\n return \"fetch failed\";\n};\n\n/** Why the probe rejected an endpoint as not-MCP.\n *\n * - `auth-required` — server returned 401. We don't know for sure it's\n * an MCP server (no spec-compliant Bearer challenge or the body\n * isn't JSON-RPC), but the right next step for the user is the same\n * either way: provide credentials and retry. This is what\n * misclassifies real MCP servers like cubic.dev (no\n * resource_metadata) or ref.tools (no WWW-Authenticate at all)\n * without the URL-token fallback at the detect layer.\n * - `wrong-shape` — endpoint responded but with a body or status that\n * doesn't match any MCP shape (200 HTML, 400 GraphQL, 404 from a\n * static host, etc.). User action: this URL probably isn't MCP. */\nexport type McpProbeRejectCategory = \"auth-required\" | \"wrong-shape\";\n\nexport type McpShapeProbeResult =\n /** Server answered initialize successfully — either a 2xx with a\n * JSON-RPC payload, or a 401 + WWW-Authenticate: Bearer (RFC 6750\n * challenge) that the MCP auth spec requires. */\n | { readonly kind: \"mcp\"; readonly requiresAuth: boolean }\n /** Endpoint is reachable but the response does not look like MCP. */\n | {\n readonly kind: \"not-mcp\";\n readonly reason: string;\n readonly category: McpProbeRejectCategory;\n }\n /** Transport-level failure (DNS, TLS, timeout, abort, ...). */\n | { readonly kind: \"unreachable\"; readonly reason: string };\n\nexport interface ProbeOptions {\n /** Abort the request after this many ms. Default 8000. */\n readonly timeoutMs?: number;\n readonly httpClientLayer?: Layer.Layer<HttpClient.HttpClient>;\n readonly headers?: Record<string, string>;\n readonly queryParams?: Record<string, string>;\n}\n\n/**\n * Hit `endpoint` with a JSON-RPC `initialize` POST and classify the\n * response according to the MCP authorization spec.\n *\n * Returns `{kind: \"mcp\"}` only when the endpoint either:\n * - answers with 2xx (unauth-OK MCP server), or\n * - responds 401 with a `Bearer` WWW-Authenticate challenge.\n *\n * Anything else (400, 404, 200-with-HTML, 200-with-GraphQL-errors, ...)\n * is classified `not-mcp`. Transport errors surface as `unreachable`.\n */\nexport const probeMcpEndpointShape = (\n endpoint: string,\n options: ProbeOptions = {},\n): Effect.Effect<McpShapeProbeResult> =>\n Effect.gen(function* () {\n const timeoutMs = options.timeoutMs ?? 8_000;\n const outcome = yield* Effect.gen(function* () {\n const client = yield* HttpClient.HttpClient;\n\n const readBody = (response: {\n readonly text: Effect.Effect<string, unknown>;\n }): Effect.Effect<string> =>\n response.text.pipe(\n Effect.timeout(Duration.millis(timeoutMs)),\n Effect.catch(() => Effect.succeed(\"\")),\n );\n\n const classify = (\n response: {\n readonly status: number;\n readonly headers: Readonly<Record<string, string>>;\n readonly text: Effect.Effect<string, unknown>;\n },\n method: \"GET\" | \"POST\",\n ): Effect.Effect<McpShapeProbeResult | null> =>\n Effect.gen(function* () {\n const contentType = readHeader(response.headers, \"content-type\") ?? \"\";\n const isSse = /^\\s*text\\/event-stream\\b/i.test(contentType);\n\n if (response.status === 401) {\n const wwwAuth = readHeader(response.headers, \"www-authenticate\");\n if (!wwwAuth || !/^\\s*bearer\\b/i.test(wwwAuth)) {\n // Spec-non-compliant 401 (no `Bearer` challenge). Before\n // giving up, check whether the server still publishes\n // RFC 9728 protected-resource metadata for this path —\n // some real MCP servers (Datadog) do exactly this.\n if (yield* probeProtectedResourceMetadata(client, url, timeoutMs)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n return {\n kind: \"not-mcp\",\n category: \"auth-required\",\n reason: \"401 without Bearer WWW-Authenticate — not an MCP auth challenge\",\n } as const;\n }\n // Spec-compliant MCP signal: the auth spec mandates a\n // `resource_metadata=` attribute pointing at the server's\n // RFC 9728 document. Real OAuth-protected MCP servers\n // (sentry.dev, etc.) include it. This attribute is rare on\n // unrelated OAuth services and is the cleanest accept signal\n // we have when the 401 body is RFC 6750 OAuth-shape rather\n // than JSON-RPC.\n if (/(?:^|[\\s,])resource_metadata\\s*=/i.test(wwwAuth)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n // Looser RFC 6750 §3.1 signal: the Bearer challenge carries\n // `error=` / `error_description=` auth-params. Real MCP\n // servers (Supabase, GitHub Copilot, Vercel, Neon, Tavily,\n // Replicate, ...) include this even when they omit\n // `resource_metadata=`. The body alone isn't enough for\n // those — Supabase, e.g., returns `{\"message\":\"Unauthorized\"}`\n // which is neither JSON-RPC nor RFC 6750. The `error=`\n // auth-param is the tiebreaker.\n if (/(?:^|[\\s,])error\\s*=/i.test(wwwAuth)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n // SSE responses can't carry a JSON-RPC error envelope; accept the\n // Bearer challenge alone in that case (rare but spec-permissible).\n if (isSse) return { kind: \"mcp\", requiresAuth: true } as const;\n // Fallback for MCP servers whose 401 omits\n // `resource_metadata=`. Two body shapes count:\n // - JSON-RPC error (cubic.dev: API-key auth, JSON-RPC\n // errors end-to-end).\n // - RFC 6750 OAuth Bearer error envelope `{error:\n // \"invalid_token\", ...}` without GraphQL `{errors:[...]}`\n // (Atlassian).\n // Non-MCP OAuth-protected services that issue bare Bearer\n // challenges (Railway-style GraphQL, etc.) return `errors`\n // arrays or other shapes that fail both checks.\n const body = yield* readBody(response);\n if (!isJsonRpcEnvelope(body) && !isOAuthErrorBody(body)) {\n // Bearer challenge with no usable accept signal. Same\n // RFC 9728 fallback as the no-`Bearer` case above.\n if (yield* probeProtectedResourceMetadata(client, url, timeoutMs)) {\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n return {\n kind: \"not-mcp\",\n category: \"auth-required\",\n reason:\n \"401 + Bearer without resource_metadata, JSON-RPC body, or OAuth error body\",\n } as const;\n }\n return { kind: \"mcp\", requiresAuth: true } as const;\n }\n\n if (response.status >= 200 && response.status < 300) {\n if (method === \"GET\") {\n if (!isSse) {\n return {\n kind: \"not-mcp\",\n category: \"wrong-shape\",\n reason: \"GET response is not an SSE stream\",\n } as const;\n }\n return { kind: \"mcp\", requiresAuth: false } as const;\n }\n // POST 2xx: SSE body is opaque to us; otherwise require a\n // JSON-RPC envelope so we don't accept HTML/REST 200 responses.\n if (isSse) return { kind: \"mcp\", requiresAuth: false } as const;\n const body = yield* readBody(response);\n if (!isJsonRpcEnvelope(body)) {\n return {\n kind: \"not-mcp\",\n category: \"wrong-shape\",\n reason: \"2xx POST body is not a JSON-RPC envelope\",\n } as const;\n }\n return { kind: \"mcp\", requiresAuth: false } as const;\n }\n\n return null;\n });\n\n const url = new URL(endpoint);\n for (const [key, value] of Object.entries(options.queryParams ?? {})) {\n url.searchParams.set(key, value);\n }\n\n let postRequest = HttpClientRequest.post(url.toString()).pipe(\n HttpClientRequest.setHeader(\"content-type\", \"application/json\"),\n HttpClientRequest.setHeader(\"accept\", \"application/json, text/event-stream\"),\n HttpClientRequest.bodyText(INITIALIZE_BODY, \"application/json\"),\n );\n for (const [name, value] of Object.entries(options.headers ?? {})) {\n postRequest = HttpClientRequest.setHeader(postRequest, name, value);\n }\n\n const postResponse = yield* client\n .execute(postRequest)\n .pipe(Effect.timeout(Duration.millis(timeoutMs)));\n\n const postResult = yield* classify(postResponse, \"POST\");\n if (postResult) return postResult;\n\n if ([404, 405, 406, 415].includes(postResponse.status)) {\n let getRequest = HttpClientRequest.get(url.toString()).pipe(\n HttpClientRequest.setHeader(\"accept\", \"text/event-stream\"),\n );\n for (const [name, value] of Object.entries(options.headers ?? {})) {\n getRequest = HttpClientRequest.setHeader(getRequest, name, value);\n }\n const getResponse = yield* client\n .execute(getRequest)\n .pipe(Effect.timeout(Duration.millis(timeoutMs)));\n const getResult = yield* classify(getResponse, \"GET\");\n if (getResult) return getResult;\n }\n\n return {\n kind: \"not-mcp\",\n category: \"wrong-shape\",\n reason: `unexpected status ${postResponse.status} for initialize`,\n } as const;\n }).pipe(\n Effect.provide(options.httpClientLayer ?? FetchHttpClient.layer),\n Effect.mapError(\n (cause) =>\n new ProbeTransportError({\n reason: reasonFromBoundaryCause(cause),\n cause,\n }),\n ),\n Effect.catch((cause) =>\n Effect.succeed<McpShapeProbeResult>({\n kind: \"unreachable\",\n reason: cause.reason,\n }),\n ),\n );\n\n return outcome;\n }).pipe(Effect.withSpan(\"mcp.plugin.probe_shape\"));\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,QAAQ,cAAc;AA+B/B,IAAM,aAAa,OAAO,OAAO;AAAA,EAC/B,MAAM,OAAO;AAAA,EACb,aAAa,OAAO,SAAS,OAAO,OAAO,OAAO,MAAM,CAAC;AAAA,EACzD,aAAa,OAAO,SAAS,OAAO,OAAO;AAAA,EAC3C,YAAY,OAAO,SAAS,OAAO,OAAO;AAAA,EAC1C,cAAc,OAAO,SAAS,OAAO,OAAO;AAAA,EAC5C,aAAa,OAAO,SAAS,kBAAkB;AACjD,CAAC;AAED,IAAM,kBAAkB,OAAO,OAAO;AAAA,EACpC,OAAO,OAAO,MAAM,UAAU;AAChC,CAAC;AAED,IAAM,aAAa,OAAO,OAAO;AAAA,EAC/B,MAAM,OAAO,SAAS,OAAO,MAAM;AAAA,EACnC,SAAS,OAAO,SAAS,OAAO,MAAM;AACxC,CAAC;AAED,IAAM,wBAAwB,OAAO,oBAAoB,eAAe;AACxE,IAAM,mBAAmB,OAAO,oBAAoB,UAAU;AAEvD,IAAM,oBAAoB,CAAC,UAChC,OAAO,OAAO,sBAAsB,KAAK,CAAC;AAM5C,IAAM,WAAW,CAAC,UAA0B;AAC1C,QAAM,IAAI,MACP,KAAK,EACL,YAAY,EACZ,QAAQ,eAAe,GAAG,EAC1B,QAAQ,YAAY,EAAE;AACzB,SAAO,KAAK;AACd;AA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AAA,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"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/react/atoms.ts","../src/react/client.ts","../src/api/group.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","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 { McpAuthTemplate, McpIntegrationConfig } 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 auth: Schema.optional(McpAuthTemplate),\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\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"],"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;AASP,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,CAA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