History

Expand agent-facing Executor configuration tools (#841)

* feat(sdk): add built-in core-tools plugin with agent secret-create flow Introduces `coreToolsPlugin` in @executor-js/sdk exposing three static tools agents can call directly: - `scopes.list` — enumerate visible scopes by name; agents pick a scope by asking the user, not by guessing or defaulting. - `secrets.list` — visible secrets as `{id, name, provider}`; values never cross the agent boundary. - `secrets.create` — pre-allocates a secret id and returns a URL to the existing /secrets web form, pre-filled with name + id. The user enters the value in the browser; the agent confirms by re-listing. The plugin auto-registers when `coreTools: { webBaseUrl }` is set on ExecutorConfig, so hosts opt in with one line. apps/local wires it to the daemon's own port — same host as the API, no separate UI server. The /secrets web side reads the prefill params via TanStack Router `validateSearch`, opens the add modal pre-filled, and locks the id via a new `initialIdOverride` prop on SecretForm. URL prefilling works fully through the dev:cli vite proxy. * fix(sdk): use typed core tools errors * feat: expand agent executor configuration tools * feat: expose source presets to agents * fix: resolve agent source install scopes * fix: clarify secret creation for agents * fix: render open object schema previews * fix: expose typed source configure tools * fix: stabilize agent openapi preview flow * fix: let secret handoff choose scope * fix: explain secret handoff completion * fix: explain oauth handoff completion * fix: clarify oauth credential scope * fix: satisfy core tools ci * fix: clarify preset and resume guidance

Rhys Sullivan committed 6 months ago

Commit c93f9331 parent 365f70454 files · +3895 −156Browse files

Unified · Split

54 files
  1. .gitignore +1 −0
  2. apps/cli/src/main.ts +42 −12
  3. apps/cloud/src/mcp-miniflare.e2e.node.test.ts +1 −1
  4. apps/cloud/src/routes/secrets.tsx +23 −7
  5. apps/cloud/src/services/executor.ts +3 −0
  6. apps/desktop/scripts/smoke-sidecar.ts +2 −2
  7. apps/local/executor.config.ts +4 −1
  8. apps/local/package.json +1 −1
  9. apps/local/src/server/executor.ts +28 −3
  10. apps/local/vite.config.ts +2 −0
  11. notes/source-setup-sdk-flow.md +12 −0
  12. notes/todo +6 −0
  13. package.json +2 −1
  14. packages/app/src/routes/secrets.tsx +20 −1
  15. packages/app/vite.config.ts +2 −0
  16. packages/core/execution/src/engine.ts +19 −6
  17. packages/core/execution/src/tool-invoker.test.ts +52 −0
  18. packages/core/execution/src/tool-invoker.ts +16 −0
  19. packages/core/sdk/src/client.ts +3 −0
  20. packages/core/sdk/src/core-tools.ts +994 −0
  21. packages/core/sdk/src/executor.test.ts +419 −2
  22. packages/core/sdk/src/executor.ts +124 −18
  23. packages/core/sdk/src/index.ts +8 −1
  24. packages/core/sdk/src/plugin.ts +99 −3
  25. packages/core/sdk/src/schema-types.test.ts +29 −0
  26. packages/core/sdk/src/schema-types.ts +9 −1
  27. packages/core/sdk/src/scope.ts +13 −0
  28. packages/hosts/mcp/src/server.test.ts +29 −0
  29. packages/kernel/runtime-dynamic-worker/src/executor.ts +27 −6
  30. packages/kernel/runtime-dynamic-worker/src/invocation.test.ts +26 −0
  31. packages/kernel/runtime-dynamic-worker/src/module-template.ts +17 −6
  32. packages/plugins/desktop-settings/package.json +1 −0
  33. packages/plugins/desktop-settings/src/server.test.ts +28 −0
  34. packages/plugins/desktop-settings/src/server.ts +48 −5
  35. packages/plugins/desktop-settings/vitest.config.ts +7 −0
  36. packages/plugins/google-discovery/src/sdk/plugin.test.ts +18 −0
  37. packages/plugins/google-discovery/src/sdk/plugin.ts +216 −20
  38. packages/plugins/graphql/src/sdk/plugin.test.ts +50 −4
  39. packages/plugins/graphql/src/sdk/plugin.ts +120 −4
  40. packages/plugins/graphql/src/sdk/presets.ts +6 −0
  41. packages/plugins/mcp/src/sdk/plugin.test.ts +71 −4
  42. packages/plugins/mcp/src/sdk/plugin.ts +303 −6
  43. packages/plugins/mcp/src/sdk/presets.ts +12 −0
  44. packages/plugins/onepassword/src/sdk/plugin.test.ts +33 −0
  45. packages/plugins/onepassword/src/sdk/plugin.ts +124 −2
  46. packages/plugins/openapi/src/sdk/__snapshots__/real-specs.test.ts.snap +5 −5
  47. packages/plugins/openapi/src/sdk/plugin.test.ts +72 −7
  48. packages/plugins/openapi/src/sdk/plugin.ts +259 −7
  49. packages/react/src/components/mcp-install-card.test.ts +14 −0
  50. packages/react/src/components/mcp-install-card.tsx +9 −2
  51. packages/react/src/pages/secrets.test.ts +18 −0
  52. packages/react/src/pages/secrets.tsx +102 −17
  53. packages/react/src/plugins/secret-form.tsx +6 −1
  54. scripts/agent-config-smoke.ts +340 −0
.gitignore+1−0
@@ -45,6 +45,7 @@ personal-notes/ · 44 unmodified lines
4545 *.har.executor
4646 executor.har
4747 .executor/
48+apps/local/.executor-dev/
4849
4950 # desktop app build artifacts
5051 apps/desktop/resources/
apps/cli/src/main.ts+42−12
@@ -748,20 +748,50 @@ const withStdoutReroutedToStderr = async <A>(body: () => Promise<A>): Promise<A> · 747 unmodified lines
748748
749749 const runStdioMcpSession = (input: { readonly elicitationMode: "browser" | "model" }) =>
750750 Effect.gen(function* () {
751− const executor = yield* Effect.promise(() => withStdoutReroutedToStderr(() => getExecutor()));
752− yield* Effect.promise(() =>
753− runMcpStdioServer({
754− executor,
755− codeExecutor: makeQuickJsExecutor(),
756− elicitationMode:
757− input.elicitationMode === "browser"
758− ? {
759− mode: "browser" as const,
760− approvalUrl: (executionId) => `/resume/${encodeURIComponent(executionId)}`,
761− }
762− : { mode: input.elicitationMode },
751+ const web = yield* Effect.promise(() =>
752+ withStdoutReroutedToStderr(async () => {
753+ const host = "127.0.0.1";
754+ const port = await Effect.runPromise(
755+ chooseDaemonPort({ preferredPort: DEFAULT_PORT, hostname: host }),
756+ );
757+ const baseUrl = `http://localhost:${port}`;
758+ const restoreWebBaseUrl = installDefaultExecutorWebBaseUrl(baseUrl);
759+
760+ try {
761+ const executor = await getExecutor();
762+ const server = await startServer({
763+ port,
764+ hostname: host,
765+ embeddedWebUI,
766+ });
767+ const serverBaseUrl = `http://localhost:${server.port}`;
768+ return { executor, server, baseUrl: serverBaseUrl, restoreWebBaseUrl };
769+ } catch (cause) {
770+ restoreWebBaseUrl();
771+ throw cause;
772+ }
763773 }),
764774 );
775+
776+ try {
777+ yield* Effect.promise(() =>
778+ runMcpStdioServer({
779+ executor: web.executor,
780+ codeExecutor: makeQuickJsExecutor(),
781+ elicitationMode:
782+ input.elicitationMode === "browser"
783+ ? {
784+ mode: "browser" as const,
785+ approvalUrl: (executionId) =>
786+ `${web.baseUrl}/resume/${encodeURIComponent(executionId)}`,
787+ }
788+ : { mode: input.elicitationMode },
789+ }),
790+ );
791+ } finally {
792+ web.restoreWebBaseUrl();
793+ yield* Effect.promise(() => web.server.stop());
794+ }
765795 });
766796
767797 const scope = Options.string("scope").pipe(
apps/cloud/src/mcp-miniflare.e2e.node.test.ts+1−1
@@ -782,7 +782,7 @@ layer(TestEnv, { timeout: 60_000 })("cloud MCP over real HTTP (miniflare)", (it) · 781 unmodified lines
782782 // `HttpApiGroup` name ("approve") becomes part of the sandbox path,
783783 // so the invocation reads `tools.approveapi.approve.approveThing`.
784784 const code = [
785− `await tools.executor.openapi.addSource({ scope: ${JSON.stringify(orgId)}, name: "Approve API", baseUrl: ${JSON.stringify(upstreamBaseUrl)}, spec: { kind: "blob", value: ${JSON.stringify(specJson)} }, namespace: "approveapi" });`,
785+ `await tools.executor.openapi.addSource({ name: "Approve API", baseUrl: ${JSON.stringify(upstreamBaseUrl)}, spec: { kind: "blob", value: ${JSON.stringify(specJson)} }, namespace: "approveapi" });`,
786786 `return await tools.approveapi.approve.approveThing({});`,
787787 ].join("\n");
788788 const result = yield* Effect.promise(() =>
apps/cloud/src/routes/secrets.tsx+23−7
@@ -1,12 +1,28 @@
1+import { Schema } from "effect";
12 import { createFileRoute } from "@tanstack/react-router";
23 import { SecretsPage } from "@executor-js/react/pages/secrets";
34
5+const SearchParams = Schema.toStandardSchemaV1(
6+ Schema.Struct({
7+ name: Schema.optional(Schema.String),
8+ secretId: Schema.optional(Schema.String),
9+ provider: Schema.optional(Schema.String),
10+ scope: Schema.optional(Schema.String),
11+ }),
12+);
13+
414 export const Route = createFileRoute("/secrets")({
5− component: () => (
6− <SecretsPage
7− addSecretDescription="Store a credential or API key for this organization."
8− showProviderInfo={false}
9− storageOptions={[{ value: "workos-vault", label: "WorkOS Vault" }]}
10− />
11− ),
15+ validateSearch: SearchParams,
16+ component: () => {
17+ const { name, secretId, provider, scope } = Route.useSearch();
18+ const hasPrefill = name != null || secretId != null;
19+ return (
20+ <SecretsPage
21+ addSecretDescription="Store a credential or API key for this organization."
22+ showProviderInfo={false}
23+ storageOptions={[{ value: "workos-vault", label: "WorkOS Vault" }]}
24+ prefill={hasPrefill ? { name, secretId, provider, scope } : undefined}
25+ />
26+ );
27+ },
1228 });
apps/cloud/src/services/executor.ts+3−0
@@ -95,5 +95,8 @@ export const createScopedExecutor = ( · 94 unmodified lines
9595 plugins,
9696 httpClientLayer,
9797 onElicitation: "accept-all",
98+ coreTools: {
99+ webBaseUrl: env.VITE_PUBLIC_SITE_URL ?? "https://executor.sh",
100+ },
98101 });
99102 });
apps/desktop/scripts/smoke-sidecar.ts+2−2
@@ -234,8 +234,8 @@ const main = async () => { · 233 unmodified lines
234234 // inside QuickJS.
235235 const code = `
236236 await tools.executor.openapi.addSource({
237− scope: ${JSON.stringify(scopeDir)},
238− spec: ${JSON.stringify(`${openapi.origin}/openapi.json`)},
237+ spec: { kind: "url", url: ${JSON.stringify(`${openapi.origin}/openapi.json`)} },
238+ name: "Petstore Smoke API",
239239 baseUrl: ${JSON.stringify(openapi.origin)},
240240 namespace: "petstore",
241241 });
apps/local/executor.config.ts+4−1
@@ -27,6 +27,9 @@ export default defineExecutorConfig({ · 26 unmodified lines
2727 keychainPlugin(),
2828 fileSecretsPlugin(),
2929 onepasswordHttpPlugin(),
30− desktopSettingsPlugin(),
30+ desktopSettingsPlugin({
31+ webBaseUrl:
32+ process.env.EXECUTOR_WEB_BASE_URL ?? `http://localhost:${process.env.PORT ?? "4788"}`,
33+ }),
3134 ] as const,
3235 });
apps/local/package.json+1−1
@@ -9,7 +9,7 @@ · 8 unmodified lines
99 "scripts": {
1010 "dev": "bun run dev:proxy && bun run dev:vite",
1111 "dev:proxy": "portless proxy start --multiplex --port 1355 || true",
12− "dev:vite": "portless --name executor-local bunx --bun vite dev",
12+ "dev:vite": "EXECUTOR_DATA_DIR=${EXECUTOR_DATA_DIR:-.executor-dev} portless --name executor-local bunx --bun vite dev",
1313 "build": "turbo run build --filter @executor-js/vite-plugin && bunx --bun vite build",
1414 "start": "bun run src/serve.ts",
1515 "db:generate": "drizzle-kit generate",
apps/local/src/server/executor.ts+28−3
@@ -252,6 +252,12 @@ const removeSqliteFileSet = (path: string) => { · 251 unmodified lines
252252 }
253253 };
254254
255+const removeSqliteSidecars = (path: string) => {
256+ for (const suffix of ["-wal", "-shm"]) {
257+ fs.rmSync(`${path}${suffix}`, { force: true });
258+ }
259+};
260+
255261 const moveSqliteFileSet = (source: string, target: string) => {
256262 fs.renameSync(source, target);
257263 for (const suffix of ["-wal", "-shm"]) {
@@ -335,6 +341,7 @@ const replaceSqliteFileSetWithRollback = (input: { · 77 unmodified lines
335341 readonly targetPath: string;
336342 }): string => {
337343 const backupPath = moveSqliteFileSetToBackup(input.sourcePath);
344+ removeSqliteSidecars(backupPath);
338345 // oxlint-disable-next-line executor/no-try-catch-or-throw -- boundary: local DB replacement must restore the original file set if the swap fails halfway
339346 try {
340347 moveSqliteFileSet(input.targetPath, input.sourcePath);
@@ -401,6 +408,8 @@ const prepareLegacySqliteForFumaImport = (input: { · 60 unmodified lines
401408 `Skipping legacy Drizzle replay and importing the existing schema as-is.`,
402409 );
403410 }
411+ sqlite.exec("PRAGMA wal_checkpoint(TRUNCATE)");
412+ sqlite.exec("PRAGMA journal_mode = DELETE");
404413 return { legacySecrets: [] };
405414 } finally {
406415 sqlite.close();
@@ -446,8 +455,10 @@ const importMissingMarkedTables = async (input: { · 39 unmodified lines
446455 tables: pickedTables,
447456 scopeId: input.scopeId,
448457 });
449− target.sqlite.exec("PRAGMA wal_checkpoint(FULL)");
458+ target.sqlite.exec("PRAGMA wal_checkpoint(TRUNCATE)");
459+ target.sqlite.exec("PRAGMA journal_mode = DELETE");
450460 await target.close();
461+ removeSqliteSidecars(input.storage.sqlitePath);
451462
452463 if (result.imported) {
453464 const importedTables = [
@@ -511,9 +522,11 @@ export const importLegacySqliteIfNeeded = async (options: { · 57 unmodified lines
511522 await withQueryContext(target.db, {
512523 allowedScopeIds: new Set([scopeId]),
513524 }).createMany("secret", createLegacySecretRows(scopeId, prepared.legacySecrets));
514− target.sqlite.exec("PRAGMA wal_checkpoint(FULL)");
525+ target.sqlite.exec("PRAGMA wal_checkpoint(TRUNCATE)");
526+ target.sqlite.exec("PRAGMA journal_mode = DELETE");
515527 } finally {
516528 await target.close();
529+ removeSqliteSidecars(storage.sqlitePath);
517530 }
518531 }
519532 writeSqliteImportMarker(storage.importMarkerPath, {
@@ -576,8 +589,10 @@ export const importLegacySqliteIfNeeded = async (options: { · 56 unmodified lines
576589 tables,
577590 scopeId,
578591 });
579− target.sqlite.exec("PRAGMA wal_checkpoint(FULL)");
592+ target.sqlite.exec("PRAGMA wal_checkpoint(TRUNCATE)");
593+ target.sqlite.exec("PRAGMA journal_mode = DELETE");
580594 await target.close();
595+ removeSqliteSidecars(targetPath);
581596
582597 if (result.imported) {
583598 const backupPath = replaceSqliteFileSetWithRollback({
@@ -653,6 +668,16 @@ const createLocalExecutorLayer = () => { · 69 unmodified lines
653668 plugins,
654669 onElicitation: "accept-all",
655670 oauthEndpointUrlPolicy: { allowHttp: true },
671+ // Built-in agent-facing tools (scopes.list, secrets.list,
672+ // secrets.create). webBaseUrl is where the executor's web UI
673+ // listens — same port as the daemon API since the daemon serves
674+ // both. Mirrors serve.ts's port resolution so a custom $PORT
675+ // flows through. EXECUTOR_WEB_BASE_URL overrides entirely for
676+ // deployments where the UI is on a different host.
677+ coreTools: {
678+ webBaseUrl:
679+ process.env.EXECUTOR_WEB_BASE_URL ?? `http://localhost:${process.env.PORT ?? "4788"}`,
680+ },
656681 });
657682
658683 return { executor, plugins };
apps/local/vite.config.ts+2−0
@@ -27,6 +27,7 @@ const EXECUTOR_GITHUB_URL = ( · 26 unmodified lines
2727 .replace(/^git\+/, "")
2828 .replace(/\.git$/, "");
2929
30+const REPO_ROOT = fileURLToPath(new URL("../..", import.meta.url));
3031 const APP_ROOT = fileURLToPath(new URL("../../packages/app/", import.meta.url));
3132
3233 /**
@@ -113,6 +114,7 @@ export default defineConfig({ · 80 unmodified lines
113114 define: {
114115 "import.meta.env.VITE_APP_VERSION": JSON.stringify(EXECUTOR_VERSION),
115116 "import.meta.env.VITE_GITHUB_URL": JSON.stringify(EXECUTOR_GITHUB_URL),
117+ "import.meta.env.VITE_EXECUTOR_DEV_CLI_CWD": JSON.stringify(REPO_ROOT),
116118 "process.env.NODE_ENV": JSON.stringify(process.env.NODE_ENV ?? "development"),
117119 },
118120 resolve: {
notes/source-setup-sdk-flow.md+12−0
@@ -0,0 +1,12 @@
1+# Source setup orchestration
2+
3+The web source-add flow currently owns a lot of business logic that agents have
4+to rediscover through low-level tools: preset lookup, URL-to-endpoint mapping,
5+endpoint probing, OAuth strategy choice, connection id generation, browser
6+handoff, credential binding, and final source registration.
7+
8+Longer term, consider moving this into an SDK-level source setup service so the
9+frontend and agent tools share the same state machine. The frontend would render
10+steps from the service, while agent tools would return the same state with
11+model-facing `instructions` fields. Keep low-level plugin tools as escape
12+hatches, but make common preset flows first-class.
notes/todo+6−0
@@ -0,0 +1,6 @@
1+Improve agent-facing source configuration scope flow
2+
3+- Source add tools now hide raw source placement and resolve the install scope internally, but credential placement still exposes raw scope ids.
4+- Add a product-level credential target flow for agents, probably "personal" vs "organization", that maps to the right credential scope internally.
5+- Keep the main-branch separation intact: source tools declare shared source config and credential slots; credential tools create secrets/connections and bind them at the selected credential scope.
6+- Agent descriptions should explain when a credential target choice is needed and when local single-scope executors can default automatically.
package.json+2−1
@@ -31,7 +31,7 @@ · 30 unmodified lines
3131 "scripts": {
3232 "dev": "turbo run dev --filter='!@executor-js/desktop' --filter='!@executor-js/cloud'",
3333 "dev:desktop": "turbo run dev",
34− "dev:cli": "EXECUTOR_DEV=1 bun run apps/cli/src/main.ts",
34+ "dev:cli": "EXECUTOR_DEV=1 EXECUTOR_DATA_DIR=${EXECUTOR_DATA_DIR:-apps/local/.executor-dev} bun run apps/cli/src/main.ts",
3535 "test": "turbo run test",
3636 "test:release:bootstrap": "vitest run tests/release-bootstrap-smoke.test.ts",
3737 "build:packages": "bun run --filter='fumadb' build && bun run --filter='@executor-js/codemode-core' build && bun run --filter='@executor-js/runtime-quickjs' build && bun run --filter='@executor-js/sdk' build && bun run --filter='@executor-js/config' build && bun run --filter='@executor-js/execution' build && bun run --filter='@executor-js/cli' build && bun run --filter='@executor-js/plugin-*' build",
@@ -44,6 +44,7 @@ · 6 unmodified lines
4444 "lint:fix": "oxlint -c .oxlintrc.jsonc --fix .",
4545 "docs:snippets": "bun run scripts/generate-doc-snippets.ts",
4646 "docs:smoke:install": "bun run scripts/smoke-docs-install.ts",
47+ "smoke:agent-config": "bun run scripts/agent-config-smoke.ts",
4748 "format": "oxfmt .",
4849 "format:check": "oxfmt --check .",
4950 "pull:references": "bun run scripts/pull-references.ts",
packages/app/src/routes/secrets.tsx+20−1
@@ -1,6 +1,25 @@
1+import { Schema } from "effect";
12 import { createFileRoute } from "@tanstack/react-router";
23 import { SecretsPage } from "@executor-js/react/pages/secrets";
34
5+// Query params supported by the agent-facing `secrets.create` static tool:
6+// it builds a URL like `/secrets?name=…&scope=…&secretId=…` and hands
7+// it to the user. The page opens the add modal pre-filled when any
8+// prefill field is present so the user only has to type the value.
9+const SearchParams = Schema.toStandardSchemaV1(
10+ Schema.Struct({
11+ name: Schema.optional(Schema.String),
12+ secretId: Schema.optional(Schema.String),
13+ provider: Schema.optional(Schema.String),
14+ scope: Schema.optional(Schema.String),
15+ }),
16+);
17+
418 export const Route = createFileRoute("/secrets")({
5− component: SecretsPage,
19+ validateSearch: SearchParams,
20+ component: () => {
21+ const { name, secretId, provider, scope } = Route.useSearch();
22+ const hasPrefill = name != null || secretId != null;
23+ return <SecretsPage prefill={hasPrefill ? { name, secretId, provider, scope } : undefined} />;
24+ },
625 });
packages/app/vite.config.ts+2−0
@@ -7,11 +7,13 @@ import appPlugin from "./vite"; · 6 unmodified lines
77 // here unless a separate server is running.
88 const LOCAL_CONFIG = fileURLToPath(new URL("../../apps/local/executor.config.ts", import.meta.url));
99 const LOCAL_JSONC = fileURLToPath(new URL("../../apps/local/executor.jsonc", import.meta.url));
10+const REPO_ROOT = fileURLToPath(new URL("../..", import.meta.url));
1011
1112 export default defineConfig({
1213 plugins: [appPlugin({ executorConfigPath: LOCAL_CONFIG, executorJsoncPath: LOCAL_JSONC })],
1314 define: {
1415 "import.meta.env.VITE_APP_VERSION": JSON.stringify("0.0.0-dev"),
1516 "import.meta.env.VITE_GITHUB_URL": JSON.stringify("https://github.com/RhysSullivan/executor"),
17+ "import.meta.env.VITE_EXECUTOR_DEV_CLI_CWD": JSON.stringify(REPO_ROOT),
1618 },
1719 });
packages/core/execution/src/engine.ts+19−6
@@ -107,19 +107,31 @@ export const formatPausedExecution = ( · 106 unmodified lines
107107 const lines: string[] = [`Execution paused: ${req.message}`];
108108 const isUrlElicitation = Predicate.isTagged(req, "UrlElicitation");
109109 const isFormElicitation = Predicate.isTagged(req, "FormElicitation");
110+ const requestedSchema = isFormElicitation ? req.requestedSchema : undefined;
111+ const hasRequestedSchema =
112+ requestedSchema !== undefined && Object.keys(requestedSchema).length > 0;
113+ const instructions = isUrlElicitation
114+ ? `The user needs to open this URL in a browser and complete the flow. After the user finishes, call the resume tool with executionId "${paused.id}" and action "accept".`
115+ : hasRequestedSchema
116+ ? `Ask the user for values matching requestedSchema. Then call the resume tool with executionId "${paused.id}", action "accept", and content matching requestedSchema. If the user declines, call resume with action "decline" or "cancel".`
117+ : `This is a model-side confirmation gate; there is no browser form to open. Ask the user whether to approve the paused tool call. If the user approves, call the resume tool with executionId "${paused.id}" and action "accept". If the user declines, call resume with action "decline" or "cancel".`;
110118
111119 if (isUrlElicitation) {
112120 lines.push(`\nOpen this URL in a browser:\n${req.url}`);
113− lines.push("\nAfter the browser flow, resume with the executionId below:");
121+ lines.push('\nAfter the browser flow, call the resume tool with action "accept".');
122+ } else if (hasRequestedSchema) {
123+ lines.push(
124+ "\nAsk the user for a response matching the requested schema, then call the resume tool.",
125+ );
126+ lines.push(`\nRequested schema:\n${JSON.stringify(requestedSchema, null, 2)}`);
114127 } else {
115− lines.push("\nResume with the executionId below and a response matching the requested schema:");
116− const schema = req.requestedSchema;
117− if (schema && Object.keys(schema).length > 0) {
118− lines.push(`\nRequested schema:\n${JSON.stringify(schema, null, 2)}`);
119− }
128+ lines.push(
129+ '\nThis is a model-side confirmation gate; no browser form is waiting. Ask the user whether to approve, then call the resume tool with action "accept", "decline", or "cancel".',
130+ );
120131 }
121132
122133 lines.push(`\nexecutionId: ${paused.id}`);
134+ lines.push(`\ninstructions: ${instructions}`);
123135
124136 return {
125137 text: lines.join("\n"),
@@ -129,6 +141,7 @@ export const formatPausedExecution = ( · 3 unmodified lines
129141 interaction: {
130142 kind: isUrlElicitation ? "url" : "form",
131143 message: req.message,
144+ instructions,
132145 toolId: String(paused.elicitationContext.toolId),
133146 args: paused.elicitationContext.args,
134147 ...(isUrlElicitation ? { url: req.url } : {}),
packages/core/execution/src/tool-invoker.test.ts+52−0
@@ -8,6 +8,7 @@ import { · 7 unmodified lines
88 ToolResult,
99 createExecutor,
1010 definePlugin,
11+ tool,
1112 } from "@executor-js/sdk";
1213 import { makeTestConfig } from "@executor-js/sdk/testing";
1314 import { makeQuickJsExecutor } from "@executor-js/runtime-quickjs";
@@ -177,6 +178,27 @@ const errorPlugin = definePlugin(() => ({ · 163 unmodified lines
177178 ],
178179 }));
179180
181+const validatedInputPlugin = definePlugin(() => ({
182+ id: "validated-input-test" as const,
183+ storage: () => ({}),
184+ staticSources: () => [
185+ {
186+ id: "validated",
187+ kind: "in-memory",
188+ name: "Validated",
189+ tools: [
190+ tool({
191+ name: "getRepositoryDetails",
192+ description: "Get repository details including the default branch",
193+ inputSchema: RepoInputSchema,
194+ outputSchema: RepoDetailsOutputSchema,
195+ execute: () => Effect.succeed({ defaultBranch: "main" }),
196+ }),
197+ ],
198+ },
199+ ],
200+}));
201+
180202 const structuredFailurePlugin = definePlugin(() => ({
181203 id: "structured-failure-test" as const,
182204 storage: () => ({}),
@@ -661,6 +683,36 @@ describe("tool discovery", () => { · 478 unmodified lines
661683 }),
662684 );
663685
686+ it.effect("returns invalid static tool arguments as ToolResult.fail", () =>
687+ Effect.gen(function* () {
688+ const executor = yield* createExecutor(
689+ makeTestConfig({ plugins: [validatedInputPlugin()] as const }),
690+ );
691+ const invoker = makeExecutorToolInvoker(executor, {
692+ invokeOptions: { onElicitation: acceptAll },
693+ });
694+
695+ const result = yield* invoker.invoke({
696+ path: "validated.getRepositoryDetails",
697+ args: { url: "https://example.com/repo" },
698+ });
699+
700+ expect(result).toMatchObject({
701+ ok: false,
702+ error: {
703+ code: "invalid_tool_arguments",
704+ message: "Tool arguments did not match the input schema.",
705+ details: {
706+ issues: expect.arrayContaining([
707+ expect.objectContaining({ path: ["owner"], message: "Missing key" }),
708+ expect.objectContaining({ path: ["repo"], message: "Missing key" }),
709+ ]),
710+ },
711+ },
712+ });
713+ }),
714+ );
715+
664716 it.effect("preserves nested upstream error bodies through ToolResult.fail", () =>
665717 Effect.gen(function* () {
666718 const executor = yield* createExecutor(
packages/core/execution/src/tool-invoker.ts+16−0
@@ -34,6 +34,12 @@ const newCorrelationId = (): string => { · 33 unmodified lines
3434 .padStart(8, "0");
3535 };
3636
37+const validationIssues = (value: unknown): readonly unknown[] | null => {
38+ if (typeof value !== "object" || value === null) return null;
39+ const issues = (value as { readonly issues?: unknown }).issues;
40+ return Array.isArray(issues) ? issues : null;
41+};
42+
3743 const expectedToolFailure = (
3844 value: unknown,
3945 ): { readonly code: string; readonly message: string; readonly details?: unknown } | null => {
@@ -53,6 +59,16 @@ const expectedToolFailure = ( · 13 unmodified lines
5359 details: value,
5460 };
5561 }
62+ if (Predicate.isTagged(value, "ToolInvocationError")) {
63+ const issues = validationIssues((value as { readonly cause?: unknown }).cause);
64+ if (issues) {
65+ return {
66+ code: "invalid_tool_arguments",
67+ message: "Tool arguments did not match the input schema.",
68+ details: { issues },
69+ };
70+ }
71+ }
5672 return null;
5773 };
5874
packages/core/sdk/src/client.ts+3−0
@@ -96,6 +96,9 @@ export interface SourcePreset { · 95 unmodified lines
9696 /** URL passed as `initialUrl` to the add form. Omit for presets that
9797 * don't use a URL (e.g. stdio MCP presets). */
9898 readonly url?: string;
99+ /** Endpoint passed to agent-facing probe/add tools when their schema
100+ * uses `endpoint` instead of `url`. */
101+ readonly endpoint?: string;
99102 /** Optional icon URL (favicon, logo). */
100103 readonly icon?: string;
101104 /** Shown in the top-level grid on the sources page when true. */
packages/core/sdk/src/core-tools.ts+994−0
@@ -0,0 +1,994 @@
1+// ---------------------------------------------------------------------------
2+// core-tools plugin
3+//
4+// Built-in plugin that contributes agent-facing static tools for configuring
5+// executor-level primitives. The important boundary: sensitive values never
6+// travel through tool arguments. Agents create secret placeholders and OAuth
7+// sessions, then hand the returned browser URL to the user.
8+// ---------------------------------------------------------------------------
9+
10+import { Data, Effect, Schema } from "effect";
11+
12+import { ConnectionRef } from "./connections";
13+import { CredentialBindingRef, CredentialBindingValue } from "./credential-bindings";
14+import { ConnectionId, ScopeId, SecretId } from "./ids";
15+import { OAuthStrategy as OAuthStrategySchema } from "./oauth";
16+import { definePlugin, tool, type StaticToolSchema } from "./plugin";
17+import { ToolPolicyActionSchema } from "./policies";
18+import { ToolResult } from "./tool-result";
19+import { SourceDetectionResult } from "./types";
20+import { Usage } from "./usages";
21+
22+const schemaToStandard = <A, I>(schema: Schema.Decoder<A, I>): StaticToolSchema<A, I> =>
23+ Schema.toStandardSchemaV1(Schema.toStandardJSONSchemaV1(schema) as never) as StaticToolSchema<
24+ A,
25+ I
26+ >;
27+
28+const UnknownRecord = Schema.Record(Schema.String, Schema.Unknown);
29+
30+const ScopeName = Schema.String;
31+
32+const ScopesListOutput = Schema.Struct({
33+ scopes: Schema.Array(
34+ Schema.Struct({
35+ id: Schema.String,
36+ name: Schema.String,
37+ }),
38+ ),
39+});
40+
41+const SecretRefOutput = Schema.Struct({
42+ id: Schema.String,
43+ scopeId: Schema.String,
44+ name: Schema.String,
45+ provider: Schema.String,
46+});
47+
48+const SecretsListOutput = Schema.Struct({
49+ secrets: Schema.Array(SecretRefOutput),
50+});
51+
52+const SecretsCreateInput = Schema.Struct({
53+ name: Schema.String,
54+ scope: Schema.optional(ScopeName),
55+ provider: Schema.optional(Schema.String),
56+});
57+
58+const SecretsCreateOutput = Schema.Struct({
59+ id: Schema.String,
60+ url: Schema.String,
61+ instructions: Schema.String,
62+});
63+
64+const SecretPointerInput = Schema.Struct({
65+ id: Schema.String,
66+});
67+
68+const SecretScopedPointerInput = Schema.Struct({
69+ id: Schema.String,
70+ targetScope: Schema.String,
71+});
72+
73+const SecretStatusOutput = Schema.Struct({
74+ id: Schema.String,
75+ status: Schema.Literals(["resolved", "missing"]),
76+});
77+
78+const SecretUsagesOutput = Schema.Struct({
79+ usages: Schema.Array(Usage),
80+});
81+
82+const ProvidersOutput = Schema.Struct({
83+ providers: Schema.Array(Schema.String),
84+});
85+
86+const RemovedOutput = Schema.Struct({
87+ removed: Schema.Boolean,
88+});
89+
90+const RefreshedOutput = Schema.Struct({
91+ refreshed: Schema.Boolean,
92+});
93+
94+const SourceOutput = Schema.Struct({
95+ id: Schema.String,
96+ scopeId: Schema.optional(Schema.String),
97+ kind: Schema.String,
98+ name: Schema.String,
99+ url: Schema.optional(Schema.String),
100+ pluginId: Schema.String,
101+ canRemove: Schema.Boolean,
102+ canRefresh: Schema.Boolean,
103+ canEdit: Schema.Boolean,
104+ runtime: Schema.Boolean,
105+});
106+
107+const SourcesListOutput = Schema.Struct({
108+ sources: Schema.Array(SourceOutput),
109+});
110+
111+const SourcesDetectInput = Schema.Struct({
112+ url: Schema.String,
113+});
114+
115+const SourcesDetectOutput = Schema.Struct({
116+ results: Schema.Array(SourceDetectionResult),
117+});
118+
119+const SourcePresetOutput = Schema.Struct({
120+ pluginId: Schema.String,
121+ id: Schema.String,
122+ name: Schema.String,
123+ summary: Schema.String,
124+ url: Schema.optional(Schema.String),
125+ endpoint: Schema.optional(Schema.String),
126+ icon: Schema.optional(Schema.String),
127+ featured: Schema.optional(Schema.Boolean),
128+ transport: Schema.optional(Schema.Literals(["remote", "stdio"])),
129+ command: Schema.optional(Schema.String),
130+ args: Schema.optional(Schema.Array(Schema.String)),
131+ env: Schema.optional(Schema.Record(Schema.String, Schema.String)),
132+});
133+
134+const SourcesPresetsInput = Schema.Struct({
135+ query: Schema.optional(Schema.String),
136+ pluginId: Schema.optional(Schema.String),
137+ featuredOnly: Schema.optional(Schema.Boolean),
138+ limit: Schema.optional(Schema.Number),
139+});
140+
141+const SourcesPresetsOutput = Schema.Struct({
142+ presets: Schema.Array(SourcePresetOutput),
143+});
144+
145+const SourcePointer = Schema.Struct({
146+ id: Schema.String,
147+ scope: Schema.String,
148+});
149+
150+const SourcesConfigureInput = Schema.Struct({
151+ source: SourcePointer,
152+ scope: Schema.String,
153+ type: Schema.optional(Schema.String),
154+ config: Schema.Unknown,
155+});
156+
157+const SourcesConfigureOutput = Schema.Struct({
158+ result: Schema.Unknown,
159+});
160+
161+const SourceLifecycleInput = Schema.Struct({
162+ id: Schema.String,
163+ targetScope: Schema.String,
164+});
165+
166+const SourceBindingsListInput = Schema.Struct({
167+ source: SourcePointer,
168+});
169+
170+const SourceBindingsResolveInput = Schema.Struct({
171+ source: SourcePointer,
172+ slotKey: Schema.String,
173+});
174+
175+const SourceBindingsSetInput = Schema.Struct({
176+ scope: Schema.String,
177+ source: SourcePointer,
178+ slotKey: Schema.String,
179+ value: CredentialBindingValue,
180+});
181+
182+const SourceBindingsRemoveInput = Schema.Struct({
183+ scope: Schema.String,
184+ source: SourcePointer,
185+ slotKey: Schema.String,
186+});
187+
188+const SourceBindingsListOutput = Schema.Struct({
189+ bindings: Schema.Array(CredentialBindingRef),
190+});
191+
192+const SourceBindingsResolveOutput = Schema.Struct({
193+ binding: Schema.NullOr(CredentialBindingRef),
194+});
195+
196+const SourceBindingsSetOutput = Schema.Struct({
197+ binding: CredentialBindingRef,
198+});
199+
200+const ConnectionsListOutput = Schema.Struct({
201+ connections: Schema.Array(ConnectionRef),
202+});
203+
204+const ConnectionPointerInput = Schema.Struct({
205+ id: Schema.String,
206+});
207+
208+const ConnectionScopedPointerInput = Schema.Struct({
209+ id: Schema.String,
210+ targetScope: Schema.String,
211+});
212+
213+const ConnectionUsagesOutput = Schema.Struct({
214+ usages: Schema.Array(Usage),
215+});
216+
217+const PolicyOutput = Schema.Struct({
218+ id: Schema.String,
219+ scopeId: Schema.String,
220+ pattern: Schema.String,
221+ action: ToolPolicyActionSchema,
222+ position: Schema.String,
223+ createdAt: Schema.Number,
224+ updatedAt: Schema.Number,
225+});
226+
227+const PoliciesListOutput = Schema.Struct({
228+ policies: Schema.Array(PolicyOutput),
229+});
230+
231+const PolicyCreateInput = Schema.Struct({
232+ targetScope: Schema.String,
233+ pattern: Schema.String,
234+ action: ToolPolicyActionSchema,
235+ position: Schema.optional(Schema.String),
236+});
237+
238+const PolicyUpdateInput = Schema.Struct({
239+ id: Schema.String,
240+ targetScope: Schema.String,
241+ pattern: Schema.optional(Schema.String),
242+ action: Schema.optional(ToolPolicyActionSchema),
243+ position: Schema.optional(Schema.String),
244+});
245+
246+const PolicyRemoveInput = Schema.Struct({
247+ id: Schema.String,
248+ targetScope: Schema.String,
249+});
250+
251+const PolicyMutationOutput = Schema.Struct({
252+ policy: PolicyOutput,
253+});
254+
255+const OAuthProbeInput = Schema.Struct({
256+ endpoint: Schema.String,
257+ headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
258+ queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),
259+});
260+
261+const OAuthProbeOutput = Schema.Struct({
262+ resourceMetadata: Schema.NullOr(UnknownRecord),
263+ resourceMetadataUrl: Schema.NullOr(Schema.String),
264+ authorizationServerMetadata: Schema.NullOr(UnknownRecord),
265+ authorizationServerMetadataUrl: Schema.NullOr(Schema.String),
266+ authorizationServerUrl: Schema.NullOr(Schema.String),
267+ supportsDynamicRegistration: Schema.Boolean,
268+ isBearerChallengeEndpoint: Schema.Boolean,
269+});
270+
271+const OAuthStartInput = Schema.Struct({
272+ credentialScope: Schema.optional(Schema.String),
273+ endpoint: Schema.String,
274+ connectionId: Schema.String,
275+ pluginId: Schema.String,
276+ identityLabel: Schema.optional(Schema.String),
277+ redirectUrl: Schema.optional(Schema.String),
278+ headers: Schema.optional(Schema.Record(Schema.String, Schema.String)),
279+ queryParams: Schema.optional(Schema.Record(Schema.String, Schema.String)),
280+ strategy: OAuthStrategySchema,
281+});
282+
283+const OAuthStartOutput = Schema.Struct({
284+ sessionId: Schema.String,
285+ authorizationUrl: Schema.NullOr(Schema.String),
286+ completedConnection: Schema.NullOr(Schema.Struct({ connectionId: Schema.String })),
287+ instructions: Schema.String,
288+});
289+
290+const OAuthCancelInput = Schema.Struct({
291+ credentialScope: Schema.optional(Schema.String),
292+ sessionId: Schema.String,
293+});
294+
295+const OAuthCancelOutput = Schema.Struct({
296+ cancelled: Schema.Boolean,
297+});
298+
299+const ScopesListOutputStd = schemaToStandard(ScopesListOutput);
300+const SecretsListOutputStd = schemaToStandard(SecretsListOutput);
301+const SecretsCreateInputStd = schemaToStandard<
302+ typeof SecretsCreateInput.Type,
303+ typeof SecretsCreateInput.Encoded
304+>(SecretsCreateInput);
305+const SecretsCreateOutputStd = schemaToStandard(SecretsCreateOutput);
306+const SecretPointerInputStd = schemaToStandard<
307+ typeof SecretPointerInput.Type,
308+ typeof SecretPointerInput.Encoded
309+>(SecretPointerInput);
310+const SecretScopedPointerInputStd = schemaToStandard<
311+ typeof SecretScopedPointerInput.Type,
312+ typeof SecretScopedPointerInput.Encoded
313+>(SecretScopedPointerInput);
314+const SecretStatusOutputStd = schemaToStandard(SecretStatusOutput);
315+const SecretUsagesOutputStd = schemaToStandard(SecretUsagesOutput);
316+const ProvidersOutputStd = schemaToStandard(ProvidersOutput);
317+const RemovedOutputStd = schemaToStandard(RemovedOutput);
318+const RefreshedOutputStd = schemaToStandard(RefreshedOutput);
319+const SourcesListOutputStd = schemaToStandard(SourcesListOutput);
320+const SourcesDetectInputStd = schemaToStandard<
321+ typeof SourcesDetectInput.Type,
322+ typeof SourcesDetectInput.Encoded
323+>(SourcesDetectInput);
324+const SourcesDetectOutputStd = schemaToStandard(SourcesDetectOutput);
325+const SourcesPresetsInputStd = schemaToStandard<
326+ typeof SourcesPresetsInput.Type,
327+ typeof SourcesPresetsInput.Encoded
328+>(SourcesPresetsInput);
329+const SourcesPresetsOutputStd = schemaToStandard(SourcesPresetsOutput);
330+const SourcesConfigureInputStd = schemaToStandard<
331+ typeof SourcesConfigureInput.Type,
332+ typeof SourcesConfigureInput.Encoded
333+>(SourcesConfigureInput);
334+const SourcesConfigureOutputStd = schemaToStandard(SourcesConfigureOutput);
335+const SourceLifecycleInputStd = schemaToStandard<
336+ typeof SourceLifecycleInput.Type,
337+ typeof SourceLifecycleInput.Encoded
338+>(SourceLifecycleInput);
339+const SourceBindingsListInputStd = schemaToStandard<
340+ typeof SourceBindingsListInput.Type,
341+ typeof SourceBindingsListInput.Encoded
342+>(SourceBindingsListInput);
343+const SourceBindingsResolveInputStd = schemaToStandard<
344+ typeof SourceBindingsResolveInput.Type,
345+ typeof SourceBindingsResolveInput.Encoded
346+>(SourceBindingsResolveInput);
347+const SourceBindingsSetInputStd = schemaToStandard<
348+ typeof SourceBindingsSetInput.Type,
349+ typeof SourceBindingsSetInput.Encoded
350+>(SourceBindingsSetInput);
351+const SourceBindingsRemoveInputStd = schemaToStandard<
352+ typeof SourceBindingsRemoveInput.Type,
353+ typeof SourceBindingsRemoveInput.Encoded
354+>(SourceBindingsRemoveInput);
355+const SourceBindingsListOutputStd = schemaToStandard(SourceBindingsListOutput);
356+const SourceBindingsResolveOutputStd = schemaToStandard(SourceBindingsResolveOutput);
357+const SourceBindingsSetOutputStd = schemaToStandard(SourceBindingsSetOutput);
358+const ConnectionsListOutputStd = schemaToStandard(ConnectionsListOutput);
359+const ConnectionPointerInputStd = schemaToStandard<
360+ typeof ConnectionPointerInput.Type,
361+ typeof ConnectionPointerInput.Encoded
362+>(ConnectionPointerInput);
363+const ConnectionScopedPointerInputStd = schemaToStandard<
364+ typeof ConnectionScopedPointerInput.Type,
365+ typeof ConnectionScopedPointerInput.Encoded
366+>(ConnectionScopedPointerInput);
367+const ConnectionUsagesOutputStd = schemaToStandard(ConnectionUsagesOutput);
368+const PoliciesListOutputStd = schemaToStandard(PoliciesListOutput);
369+const PolicyCreateInputStd = schemaToStandard<
370+ typeof PolicyCreateInput.Type,
371+ typeof PolicyCreateInput.Encoded
372+>(PolicyCreateInput);
373+const PolicyUpdateInputStd = schemaToStandard<
374+ typeof PolicyUpdateInput.Type,
375+ typeof PolicyUpdateInput.Encoded
376+>(PolicyUpdateInput);
377+const PolicyRemoveInputStd = schemaToStandard<
378+ typeof PolicyRemoveInput.Type,
379+ typeof PolicyRemoveInput.Encoded
380+>(PolicyRemoveInput);
381+const PolicyMutationOutputStd = schemaToStandard(PolicyMutationOutput);
382+const OAuthProbeInputStd = schemaToStandard<
383+ typeof OAuthProbeInput.Type,
384+ typeof OAuthProbeInput.Encoded
385+>(OAuthProbeInput);
386+const OAuthProbeOutputStd = schemaToStandard(OAuthProbeOutput);
387+const OAuthStartInputStd = schemaToStandard<
388+ typeof OAuthStartInput.Type,
389+ typeof OAuthStartInput.Encoded
390+>(OAuthStartInput);
391+const OAuthStartOutputStd = schemaToStandard(OAuthStartOutput);
392+const OAuthCancelInputStd = schemaToStandard<
393+ typeof OAuthCancelInput.Type,
394+ typeof OAuthCancelInput.Encoded
395+>(OAuthCancelInput);
396+const OAuthCancelOutputStd = schemaToStandard(OAuthCancelOutput);
397+
398+export interface CoreToolsPluginOptions {
399+ readonly webBaseUrl?: string;
400+}
401+
402+class CoreToolsConfigurationError extends Data.TaggedError("CoreToolsConfigurationError")<{
403+ readonly message: string;
404+}> {}
405+
406+class CoreToolsScopeNotFoundError extends Data.TaggedError("CoreToolsScopeNotFoundError")<{
407+ readonly scope: string;
408+ readonly message: string;
409+}> {}
410+
411+const findScopeByNameOrId = (
412+ scopes: readonly { readonly id: ScopeId; readonly name: string }[],
413+ value: string,
414+) => scopes.find((scope) => scope.name === value || String(scope.id) === value);
415+
416+const resolveScopeInput = (
417+ scopes: readonly { readonly id: ScopeId; readonly name: string }[],
418+ value: string | undefined,
419+) => {
420+ if (value === undefined) {
421+ const [onlyScope] = scopes;
422+ return onlyScope && scopes.length === 1
423+ ? Effect.succeed(String(onlyScope.id))
424+ : Effect.fail(
425+ new CoreToolsScopeNotFoundError({
426+ scope: "",
427+ message:
428+ scopes.length === 0
429+ ? "No visible scopes are available."
430+ : "Multiple scopes are visible. Call scopes.list and pass the target scope id or name.",
431+ }),
432+ );
433+ }
434+
435+ const scope = findScopeByNameOrId(scopes, value);
436+ return scope
437+ ? Effect.succeed(String(scope.id))
438+ : Effect.fail(
439+ new CoreToolsScopeNotFoundError({
440+ scope: value,
441+ message: `Unknown scope "${value}". Call scopes.list to see valid scope ids and names.`,
442+ }),
443+ );
444+};
445+
446+const normalizeCredentialBindingValue = (
447+ value: typeof CredentialBindingValue.Encoded,
448+): CredentialBindingValue => {
449+ if (value.kind === "text") {
450+ return value;
451+ }
452+ if (value.kind === "secret") {
453+ return {
454+ kind: "secret",
455+ secretId: SecretId.make(value.secretId),
456+ ...(value.secretScopeId ? { secretScopeId: ScopeId.make(value.secretScopeId) } : {}),
457+ };
458+ }
459+ return {
460+ kind: "connection",
461+ connectionId: ConnectionId.make(value.connectionId),
462+ };
463+};
464+
465+const oauthToolFailure = (code: string, message: string, details?: unknown) =>
466+ ToolResult.fail({
467+ code,
468+ message,
469+ ...(details === undefined ? {} : { details }),
470+ });
471+
472+const requireWebBaseUrl = (value: string | undefined) =>
473+ value
474+ ? Effect.succeed(value.replace(/\/$/, ""))
475+ : Effect.fail(
476+ new CoreToolsConfigurationError({
477+ message: "This executor did not provide a webBaseUrl for browser handoff flows.",
478+ }),
479+ );
480+
481+const policyOutput = (policy: {
482+ readonly id: string;
483+ readonly scopeId: string;
484+ readonly pattern: string;
485+ readonly action: typeof ToolPolicyActionSchema.Type;
486+ readonly position: string;
487+ readonly createdAt: Date;
488+ readonly updatedAt: Date;
489+}) => ({
490+ id: String(policy.id),
491+ scopeId: String(policy.scopeId),
492+ pattern: policy.pattern,
493+ action: policy.action,
494+ position: policy.position,
495+ createdAt: policy.createdAt.getTime(),
496+ updatedAt: policy.updatedAt.getTime(),
497+});
498+
499+export const coreToolsPlugin = definePlugin((options: CoreToolsPluginOptions = {}) => ({
500+ id: "core-tools" as const,
501+ packageName: "@executor-js/sdk/core-tools",
502+ storage: () => ({}),
503+ extension: () => ({}),
504+
505+ staticSources: () => [
506+ {
507+ id: "coreTools",
508+ kind: "executor",
509+ name: "Executor",
510+ tools: [
511+ tool({
512+ name: "scopes.list",
513+ description:
514+ "List visible executor scopes. Call this before write tools when more than one scope is visible; single-scope local executors can usually omit scope inputs.",
515+ outputSchema: ScopesListOutputStd,
516+ execute: (_args, { ctx }) =>
517+ Effect.succeed({
518+ scopes: ctx.scopes.map((s) => ({ id: String(s.id), name: s.name })),
519+ }),
520+ }),
521+ tool({
522+ name: "secrets.list",
523+ description:
524+ "List visible secrets by id, name, and provider. This never returns values. Use returned ids in source configuration or OAuth client credential strategies.",
525+ outputSchema: SecretsListOutputStd,
526+ execute: (_args, { ctx }) =>
527+ Effect.map(ctx.secrets.list(), (refs) => ({
528+ secrets: refs.map((r) => ({
529+ id: String(r.id),
530+ scopeId: String(r.scopeId),
531+ name: r.name,
532+ provider: r.provider,
533+ })),
534+ })),
535+ }),
536+ tool({
537+ name: "secrets.create",
538+ description:
539+ "Create a secret placeholder and return a browser URL for the user to enter the sensitive value. Never ask the user to paste passwords, tokens, client secrets, or API keys into chat. In a single-scope local executor, omit `scope`; otherwise call `scopes.list` and pass the target credential scope id or name. The optional `provider` is the Executor secret storage backend, not the API vendor; omit it unless the user explicitly chose a value returned by `secrets.providers`.",
540+ inputSchema: SecretsCreateInputStd,
541+ outputSchema: SecretsCreateOutputStd,
542+ execute: (input, { ctx }) =>
543+ Effect.gen(function* () {
544+ const webBaseUrl = yield* requireWebBaseUrl(options.webBaseUrl);
545+ if (input.provider) {
546+ const providers = yield* ctx.secrets.providers();
547+ if (!providers.includes(input.provider)) {
548+ return oauthToolFailure(
549+ "secret_provider_not_found",
550+ `Unknown secret storage provider "${input.provider}". Omit provider unless the user chose one from secrets.providers.`,
551+ { providers },
552+ );
553+ }
554+ }
555+ const targetScope = yield* resolveScopeInput(ctx.scopes, input.scope);
556+
557+ const secretId = crypto.randomUUID();
558+ const url = new URL(`${webBaseUrl}/secrets`);
559+ url.searchParams.set("scope", targetScope);
560+ url.searchParams.set("name", input.name);
561+ url.searchParams.set("secretId", secretId);
562+ if (input.provider) url.searchParams.set("provider", input.provider);
563+ return {
564+ id: secretId,
565+ url: url.toString(),
566+ instructions:
567+ "The user needs to open this URL and set the secret value in the browser. Until the user saves the value there, this secret is only a placeholder and will not be available for binding. After the user saves it, call secrets.status for this id before using it in source configuration.",
568+ };
569+ }).pipe(
570+ Effect.catchTags({
571+ CoreToolsConfigurationError: ({ message }) =>
572+ Effect.succeed(oauthToolFailure("secret_handoff_not_configured", message)),
573+ CoreToolsScopeNotFoundError: ({ message, scope }) =>
574+ Effect.succeed(oauthToolFailure("scope_not_found", message, { scope })),
575+ }),
576+ ),
577+ }),
578+ tool({
579+ name: "secrets.status",
580+ description:
581+ "Check whether a user-visible secret id has a backing value without revealing that value. Use this after a browser handoff from `secrets.create` before wiring the secret into a source.",
582+ inputSchema: SecretPointerInputStd,
583+ outputSchema: SecretStatusOutputStd,
584+ execute: (input, { ctx }) =>
585+ Effect.map(ctx.secrets.status(input.id), (status) => ({ id: input.id, status })),
586+ }),
587+ tool({
588+ name: "secrets.usages",
589+ description:
590+ "List sources and credential slots that reference a secret. Call this before removing a secret so the user can detach it first if needed.",
591+ inputSchema: SecretPointerInputStd,
592+ outputSchema: SecretUsagesOutputStd,
593+ execute: (input, { ctx }) =>
594+ Effect.map(ctx.secrets.usages(input.id), (usages) => ({ usages })),
595+ }),
596+ tool({
597+ name: "secrets.providers",
598+ description:
599+ "List registered secret storage providers. Only use these exact values for the optional `provider` field in `secrets.create`; do not use API vendor names such as Vercel, GitHub, Stripe, or Google. Sensitive values still must be entered through the returned browser URL.",
600+ outputSchema: ProvidersOutputStd,
601+ execute: (_args, { ctx }) =>
602+ Effect.map(ctx.secrets.providers(), (providers) => ({ providers })),
603+ }),
604+ tool({
605+ name: "secrets.remove",
606+ description:
607+ "Remove a user-visible secret from a target scope. Call `secrets.usages` first; removal is refused while sources still reference the secret. Connection-owned token secrets cannot be removed here; remove the connection instead.",
608+ annotations: {
609+ requiresApproval: true,
610+ approvalDescription: "Remove an Executor secret",
611+ },
612+ inputSchema: SecretScopedPointerInputStd,
613+ outputSchema: RemovedOutputStd,
614+ execute: (input, { ctx }) =>
615+ Effect.gen(function* () {
616+ const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);
617+ return yield* Effect.as(
618+ ctx.secrets.remove({
619+ id: SecretId.make(input.id),
620+ targetScope: ScopeId.make(targetScope),
621+ }),
622+ { removed: true },
623+ );
624+ }),
625+ }),
626+ tool({
627+ name: "sources.list",
628+ description:
629+ "List configured and built-in sources. Use this to find source ids/scopes before calling plugin-specific configureSource tools, `sources.bindings.*`, refresh, remove, or tool discovery.",
630+ outputSchema: SourcesListOutputStd,
631+ execute: (_args, { ctx }) =>
632+ Effect.map(ctx.core.sources.list(), (sources) => ({ sources })),
633+ }),
634+ tool({
635+ name: "sources.detect",
636+ description:
637+ "Detect which plugin can add or configure a URL. This is the same URL auto-detection used by the Executor web Connect dialog. Use this when the user gives a URL but not a source type; then call the matching plugin add tool such as `openapi.previewSpec` + `openapi.addSource`, `graphql.addSource`, or `mcp.addSource`.",
638+ inputSchema: SourcesDetectInputStd,
639+ outputSchema: SourcesDetectOutputStd,
640+ execute: (input, { ctx }) =>
641+ Effect.map(ctx.core.sources.detect(input.url), (results) => ({ results })),
642+ }),
643+ tool({
644+ name: "sources.presets",
645+ description:
646+ "List the same popular source presets shown in Executor web's Connect dialog. Use this before asking the user what to connect; filter with `query` for names like GitHub, Stripe, Axiom, Google Calendar, Linear, or OpenAI. For MCP and GraphQL presets, pass `endpoint` to the probe/add tools. For OpenAPI and Google Discovery presets, pass `url` to the preview/probe and add tools. For stdio MCP presets, use the returned command/args/env.",
647+ inputSchema: SourcesPresetsInputStd,
648+ outputSchema: SourcesPresetsOutputStd,
649+ execute: (input, { ctx }) =>
650+ Effect.sync(() => {
651+ const query = input.query?.trim().toLowerCase() ?? "";
652+ const pluginId = input.pluginId?.trim();
653+ const featuredOnly = input.featuredOnly ?? false;
654+ const limit = Math.max(0, Math.trunc(input.limit ?? 50));
655+ const presets = ctx.core.sources
656+ .presets()
657+ .filter((preset) => (pluginId ? preset.pluginId === pluginId : true))
658+ .filter((preset) => (featuredOnly ? preset.featured === true : true))
659+ .filter((preset) => {
660+ if (query.length === 0) return true;
661+ const corpus =
662+ `${preset.name} ${preset.summary} ${preset.pluginId} ${preset.id}`.toLowerCase();
663+ return corpus.includes(query);
664+ })
665+ .slice(0, limit);
666+ return { presets };
667+ }),
668+ }),
669+ tool({
670+ name: "sources.configure",
671+ description:
672+ 'Low-level escape hatch for configuring an existing source through its owning plugin. Prefer plugin-specific tools such as `openapi.configureSource`, `graphql.configureSource`, `mcp.configureSource`, or `googleDiscovery.configureSource`; this accepts plugin config as `unknown` for repair and compatibility cases. Use `secrets.create`/`oauth.start` first for sensitive inputs. Pass secret refs as `{kind:"secret", secretId}` and OAuth connections as `{kind:"connection", connectionId}` when the plugin schema supports them.',
673+ annotations: {
674+ requiresApproval: true,
675+ approvalDescription: "Configure an Executor source",
676+ },
677+ inputSchema: SourcesConfigureInputStd,
678+ outputSchema: SourcesConfigureOutputStd,
679+ execute: (input, { ctx }) =>
680+ Effect.gen(function* () {
681+ const sourceScope = yield* resolveScopeInput(ctx.scopes, input.source.scope);
682+ const targetScope = yield* resolveScopeInput(ctx.scopes, input.scope);
683+ const result = yield* ctx.core.sources.configure({
684+ ...input,
685+ source: { ...input.source, scope: sourceScope },
686+ scope: targetScope,
687+ });
688+ return { result };
689+ }),
690+ }),
691+ tool({
692+ name: "sources.refresh",
693+ description:
694+ "Refresh a configurable source's registered tools from its backing spec/server. Use `sources.list` first to get the source id and owning scope, then refresh the owning scope.",
695+ annotations: {
696+ requiresApproval: true,
697+ approvalDescription: "Refresh an Executor source",
698+ },
699+ inputSchema: SourceLifecycleInputStd,
700+ outputSchema: RefreshedOutputStd,
701+ execute: (input, { ctx }) =>
702+ Effect.gen(function* () {
703+ const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);
704+ return yield* Effect.as(ctx.core.sources.refresh({ ...input, targetScope }), {
705+ refreshed: true,
706+ });
707+ }),
708+ }),
709+ tool({
710+ name: "sources.remove",
711+ description:
712+ "Remove a configurable source and its registered tools from a target scope. Use `sources.list` and, when credentials are involved, `sources.bindings.list` first so the user can confirm exactly what will be removed.",
713+ annotations: {
714+ requiresApproval: true,
715+ approvalDescription: "Remove an Executor source",
716+ },
717+ inputSchema: SourceLifecycleInputStd,
718+ outputSchema: RemovedOutputStd,
719+ execute: (input, { ctx }) =>
720+ Effect.gen(function* () {
721+ const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);
722+ return yield* Effect.as(ctx.core.sources.remove({ ...input, targetScope }), {
723+ removed: true,
724+ });
725+ }),
726+ }),
727+ tool({
728+ name: "sources.bindings.list",
729+ description:
730+ "List credential bindings for a source. Use this to verify that secrets or OAuth connections were bound after a plugin-specific configureSource tool.",
731+ inputSchema: SourceBindingsListInputStd,
732+ outputSchema: SourceBindingsListOutputStd,
733+ execute: (input, { ctx }) =>
734+ Effect.gen(function* () {
735+ const sourceScope = yield* resolveScopeInput(ctx.scopes, input.source.scope);
736+ const bindings = yield* ctx.core.sources.listBindings({
737+ source: { id: input.source.id, scope: ScopeId.make(sourceScope) },
738+ });
739+ return { bindings };
740+ }),
741+ }),
742+ tool({
743+ name: "sources.bindings.resolve",
744+ description:
745+ "Resolve the effective credential binding for one source slot, accounting for scope shadowing. Values are references only; plaintext is never returned.",
746+ inputSchema: SourceBindingsResolveInputStd,
747+ outputSchema: SourceBindingsResolveOutputStd,
748+ execute: (input, { ctx }) =>
749+ Effect.gen(function* () {
750+ const sourceScope = yield* resolveScopeInput(ctx.scopes, input.source.scope);
751+ const binding = yield* ctx.core.sources.resolveBinding({
752+ source: { id: input.source.id, scope: ScopeId.make(sourceScope) },
753+ slotKey: input.slotKey,
754+ });
755+ return { binding };
756+ }),
757+ }),
758+ tool({
759+ name: "sources.bindings.set",
760+ description:
761+ "Set one credential binding for a source slot. Prefer plugin-specific configureSource tools for normal flows because they name the right credential fields. Use this low-level tool only when a plugin or status output has given an exact slot key.",
762+ annotations: {
763+ requiresApproval: true,
764+ approvalDescription: "Set a source credential binding",
765+ },
766+ inputSchema: SourceBindingsSetInputStd,
767+ outputSchema: SourceBindingsSetOutputStd,
768+ execute: (input, { ctx }) =>
769+ Effect.gen(function* () {
770+ const scope = yield* resolveScopeInput(ctx.scopes, input.scope);
771+ const sourceScope = yield* resolveScopeInput(ctx.scopes, input.source.scope);
772+ const binding = yield* ctx.core.sources.setBinding({
773+ scope: ScopeId.make(scope),
774+ source: { id: input.source.id, scope: ScopeId.make(sourceScope) },
775+ slotKey: input.slotKey,
776+ value: normalizeCredentialBindingValue(input.value),
777+ });
778+ return { binding };
779+ }),
780+ }),
781+ tool({
782+ name: "sources.bindings.remove",
783+ description:
784+ "Remove one credential binding from a source slot at a target scope. Use `sources.bindings.list` first so the user can confirm the exact binding being removed.",
785+ annotations: {
786+ requiresApproval: true,
787+ approvalDescription: "Remove a source credential binding",
788+ },
789+ inputSchema: SourceBindingsRemoveInputStd,
790+ execute: (input, { ctx }) =>
791+ Effect.gen(function* () {
792+ const scope = yield* resolveScopeInput(ctx.scopes, input.scope);
793+ const sourceScope = yield* resolveScopeInput(ctx.scopes, input.source.scope);
794+ return yield* Effect.asVoid(
795+ ctx.core.sources.removeBinding({
796+ scope: ScopeId.make(scope),
797+ source: { id: input.source.id, scope: ScopeId.make(sourceScope) },
798+ slotKey: input.slotKey,
799+ }),
800+ );
801+ }),
802+ }),
803+ tool({
804+ name: "connections.list",
805+ description:
806+ "List OAuth/sign-in connections. This returns metadata and token secret ids, never token values. Use it to verify that `oauth.start` completed, then bind the connection id with the relevant plugin-specific configureSource tool.",
807+ outputSchema: ConnectionsListOutputStd,
808+ execute: (_args, { ctx }) =>
809+ Effect.map(ctx.connections.list(), (connections) => ({ connections })),
810+ }),
811+ tool({
812+ name: "connections.usages",
813+ description:
814+ "List sources and credential slots that reference an OAuth/sign-in connection. Call this before removing a connection so the user can detach it first if needed.",
815+ inputSchema: ConnectionPointerInputStd,
816+ outputSchema: ConnectionUsagesOutputStd,
817+ execute: (input, { ctx }) =>
818+ Effect.map(ctx.connections.usages(input.id), (usages) => ({ usages })),
819+ }),
820+ tool({
821+ name: "connections.providers",
822+ description:
823+ "List registered connection providers. Use this to understand which OAuth/sign-in connection kinds this executor can mint and refresh.",
824+ outputSchema: ProvidersOutputStd,
825+ execute: (_args, { ctx }) =>
826+ Effect.map(ctx.connections.providers(), (providers) => ({ providers })),
827+ }),
828+ tool({
829+ name: "connections.remove",
830+ description:
831+ "Remove an OAuth/sign-in connection and its owned token secrets from a target scope. Call `connections.usages` first; removal is refused while sources still reference the connection.",
832+ annotations: {
833+ requiresApproval: true,
834+ approvalDescription: "Remove an Executor connection",
835+ },
836+ inputSchema: ConnectionScopedPointerInputStd,
837+ outputSchema: RemovedOutputStd,
838+ execute: (input, { ctx }) =>
839+ Effect.gen(function* () {
840+ const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);
841+ return yield* Effect.as(
842+ ctx.connections.remove({
843+ id: ConnectionId.make(input.id),
844+ targetScope: ScopeId.make(targetScope),
845+ }),
846+ { removed: true },
847+ );
848+ }),
849+ }),
850+ tool({
851+ name: "policies.list",
852+ description:
853+ "List tool approval policies visible to this executor, sorted in evaluation order. Use this before creating, updating, reordering, or removing policies.",
854+ outputSchema: PoliciesListOutputStd,
855+ execute: (_args, { ctx }) =>
856+ Effect.map(ctx.core.policies.list(), (policies) => ({
857+ policies: policies.map(policyOutput),
858+ })),
859+ }),
860+ tool({
861+ name: "policies.create",
862+ description:
863+ 'Create a tool approval policy. Patterns are exact tool ids, a trailing wildcard such as `executor.openapi.*`, or `*`. Actions are `"approve"`, `"require_approval"`, or `"block"`. Omit `position` to place the policy at the top of the target scope.',
864+ annotations: {
865+ requiresApproval: true,
866+ approvalDescription: "Create an Executor tool policy",
867+ },
868+ inputSchema: PolicyCreateInputStd,
869+ outputSchema: PolicyMutationOutputStd,
870+ execute: (input, { ctx }) =>
871+ Effect.gen(function* () {
872+ const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);
873+ const policy = yield* ctx.core.policies.create({ ...input, targetScope });
874+ return { policy: policyOutput(policy) };
875+ }),
876+ }),
877+ tool({
878+ name: "policies.update",
879+ description:
880+ "Update or reorder an approval policy. Use `policies.list` first; preserve fields you are not changing, and use the listed `position` values when computing a new order.",
881+ annotations: {
882+ requiresApproval: true,
883+ approvalDescription: "Update an Executor tool policy",
884+ },
885+ inputSchema: PolicyUpdateInputStd,
886+ outputSchema: PolicyMutationOutputStd,
887+ execute: (input, { ctx }) =>
888+ Effect.gen(function* () {
889+ const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);
890+ const policy = yield* ctx.core.policies.update({ ...input, targetScope });
891+ return { policy: policyOutput(policy) };
892+ }),
893+ }),
894+ tool({
895+ name: "policies.remove",
896+ description:
897+ "Remove an approval policy from a target scope. Use `policies.list` first so the user can confirm the exact rule id and pattern.",
898+ annotations: {
899+ requiresApproval: true,
900+ approvalDescription: "Remove an Executor tool policy",
901+ },
902+ inputSchema: PolicyRemoveInputStd,
903+ outputSchema: RemovedOutputStd,
904+ execute: (input, { ctx }) =>
905+ Effect.gen(function* () {
906+ const targetScope = yield* resolveScopeInput(ctx.scopes, input.targetScope);
907+ return yield* Effect.as(ctx.core.policies.remove({ ...input, targetScope }), {
908+ removed: true,
909+ });
910+ }),
911+ }),
912+ tool({
913+ name: "oauth.probe",
914+ description:
915+ 'Probe an OAuth-protected endpoint before starting OAuth. For dynamic MCP-style OAuth, call this first; if `supportsDynamicRegistration` is true, call `oauth.start` with strategy `{kind:"dynamic-dcr"}`. If false, create client id/secret secrets in the browser and use an `authorization-code` strategy.',
916+ inputSchema: OAuthProbeInputStd,
917+ outputSchema: OAuthProbeOutputStd,
918+ execute: (input, { ctx }) =>
919+ ctx.oauth
920+ .probe(input)
921+ .pipe(
922+ Effect.catchTag("OAuthProbeError", ({ message }) =>
923+ Effect.succeed(oauthToolFailure("oauth_probe_failed", message)),
924+ ),
925+ ),
926+ }),
927+ tool({
928+ name: "oauth.start",
929+ description:
930+ "Start an OAuth flow and return the authorization URL the user must open in a browser. `credentialScope` chooses where Executor stores the OAuth connection/token secrets; omit it only in a single-scope local executor, otherwise call `scopes.list` and ask whether the connection should be personal/user-scoped or organization-scoped. OAuth permission scopes belong in `strategy.scopes`. Never put OAuth passwords, authorization codes, or client secrets in chat. For confidential clients, first call `secrets.create` for client id/secret and pass those secret ids in the strategy. After the browser callback completes, call `connections.list`, then configure the source with the returned connection id.",
931+ inputSchema: OAuthStartInputStd,
932+ outputSchema: OAuthStartOutputStd,
933+ execute: (input, { ctx }) =>
934+ Effect.gen(function* () {
935+ const webBaseUrl = yield* requireWebBaseUrl(options.webBaseUrl);
936+ const tokenScope = yield* resolveScopeInput(ctx.scopes, input.credentialScope);
937+ const result = yield* ctx.oauth.start({
938+ endpoint: input.endpoint,
939+ headers: input.headers,
940+ queryParams: input.queryParams,
941+ redirectUrl: input.redirectUrl ?? `${webBaseUrl}/api/oauth/callback`,
942+ connectionId: input.connectionId,
943+ tokenScope,
944+ strategy: input.strategy,
945+ pluginId: input.pluginId,
946+ identityLabel: input.identityLabel,
947+ });
948+ return {
949+ ...result,
950+ instructions:
951+ result.authorizationUrl === null
952+ ? "This OAuth flow completed without a browser handoff. The OAuth connection/token secrets were saved to the selected credential scope. Call connections.list to verify the connection id, then pass that connection id to the relevant source configuration tool."
953+ : "The user needs to open this authorization URL in a browser and complete the OAuth/sign-in flow. Until the browser callback completes, no connection is available for binding. After the user finishes sign-in, call connections.list to find the connection id, then pass that connection id to the relevant source configuration tool. The OAuth connection/token secrets are saved to the selected credential scope.",
954+ };
955+ }).pipe(
956+ Effect.catchTags({
957+ CoreToolsConfigurationError: ({ message }) =>
958+ Effect.succeed(oauthToolFailure("oauth_start_not_configured", message)),
959+ CoreToolsScopeNotFoundError: ({ message, scope }) =>
960+ Effect.succeed(oauthToolFailure("scope_not_found", message, { scope })),
961+ OAuthStartError: ({ message, error, errorDescription }) =>
962+ Effect.succeed(
963+ oauthToolFailure("oauth_start_failed", message, {
964+ ...(error ? { error } : {}),
965+ ...(errorDescription ? { errorDescription } : {}),
966+ }),
967+ ),
968+ }),
969+ ),
970+ }),
971+ tool({
972+ name: "oauth.cancel",
973+ description:
974+ "`credentialScope` must match where `oauth.start` saved the pending browser handoff. Cancel it if the user declines or the wrong flow was started.",
975+ inputSchema: OAuthCancelInputStd,
976+ outputSchema: OAuthCancelOutputStd,
977+ execute: (input, { ctx }) =>
978+ Effect.gen(function* () {
979+ const scope = yield* resolveScopeInput(ctx.scopes, input.credentialScope);
980+ return yield* Effect.as(ctx.oauth.cancel(input.sessionId, scope), {
981+ cancelled: true,
982+ });
983+ }).pipe(
984+ Effect.catchTag("CoreToolsScopeNotFoundError", ({ message, scope }) =>
985+ Effect.succeed(oauthToolFailure("scope_not_found", message, { scope })),
986+ ),
987+ ),
988+ }),
989+ ],
990+ },
991+ ],
992+}));
993+
994+export default coreToolsPlugin;
packages/core/sdk/src/executor.test.ts+419−2
@@ -6,11 +6,16 @@ import { scopedExecutorTable, textColumn } from "./core-schema"; · 5 unmodified lines
66 import { ElicitationResponse } from "./elicitation";
77 import { ToolNotFoundError } from "./errors";
88 import { createExecutor } from "./executor";
9−import { ScopeId } from "./ids";
9+import { ScopeId, SecretId } from "./ids";
1010 import { definePlugin } from "./plugin";
1111 import { Scope } from "./scope";
1212 import { SourceDetectionResult } from "./types";
13−import { makeTestConfig, makeTestExecutor } from "./testing";
13+import {
14+ makeTestConfig,
15+ makeTestExecutor,
16+ memorySecretsPlugin,
17+ serveOAuthTestServer,
18+} from "./testing";
1419
1520 class TestPluginError extends Data.TaggedError("TestPluginError")<{
1621 readonly message: string;
@@ -191,6 +196,15 @@ const caseSensitiveDynamicPlugin = definePlugin(() => ({ · 174 unmodified lines
191196
192197 const configurableSourcePlugin = definePlugin(() => ({
193198 id: "configurable" as const,
199+ sourcePresets: [
200+ {
201+ id: "configurable-demo",
202+ name: "Configurable Demo",
203+ summary: "Demo source preset for agent and web discovery.",
204+ url: "https://example.com/configurable.json",
205+ featured: true,
206+ },
207+ ],
194208 storage: ({ pluginStorage }) => ({
195209 get: (scope: string, sourceId = "configured-source") =>
196210 pluginStorage.getAtScope<{ readonly header: string; readonly sourceScope: string }>({
@@ -473,4 +487,407 @@ describe("createExecutor", () => { · 276 unmodified lines
473487 expect(visibleConfig?.data).toEqual({ header: "user-token", sourceScope: "org" });
474488 }),
475489 );
490+
491+ it.effect("core tools configure sources through agent-visible tool calls", () =>
492+ Effect.gen(function* () {
493+ const orgScope = Scope.make({
494+ id: ScopeId.make("org"),
495+ name: "Org",
496+ createdAt: new Date(),
497+ });
498+ const userScope = Scope.make({
499+ id: ScopeId.make("user"),
500+ name: "User",
501+ createdAt: new Date(),
502+ });
503+ const config = makeTestConfig({
504+ scopes: [userScope, orgScope],
505+ plugins: [configurableSourcePlugin] as const,
506+ });
507+ const executor = yield* createExecutor({
508+ ...config,
509+ coreTools: { webBaseUrl: "http://executor.test" },
510+ });
511+
512+ yield* executor.configurable.registerSource("org");
513+
514+ expect((yield* executor.tools.list()).map((tool) => tool.id)).not.toContain(
515+ "executor.coreTools.sources.configureSchemas",
516+ );
517+ const presets = yield* executor.tools.invoke("executor.coreTools.sources.presets", {
518+ query: "demo",
519+ });
520+ expect(presets).toMatchObject({
521+ presets: [
522+ expect.objectContaining({
523+ pluginId: "configurable",
524+ id: "configurable-demo",
525+ name: "Configurable Demo",
526+ url: "https://example.com/configurable.json",
527+ featured: true,
528+ }),
529+ ],
530+ });
531+
532+ yield* executor.tools.invoke("executor.coreTools.sources.configure", {
533+ source: { id: "configured-source", scope: "org" },
534+ scope: "user",
535+ type: "configurable",
536+ config: { header: "agent-token" },
537+ });
538+
539+ const visibleConfig = yield* executor.configurable.getVisibleConfig();
540+ expect(visibleConfig?.data).toEqual({ header: "agent-token", sourceScope: "org" });
541+
542+ yield* executor.close();
543+ yield* Effect.promise(() => config.testDb.close());
544+ }),
545+ );
546+
547+ it.effect("core tools generate browser handoff URLs for secret values", () =>
548+ Effect.gen(function* () {
549+ const config = makeTestConfig({ plugins: [memorySecretsPlugin()] as const });
550+ const executor = yield* createExecutor({
551+ ...config,
552+ coreTools: { webBaseUrl: "http://executor.test" },
553+ });
554+
555+ const result = yield* executor.tools.invoke("executor.coreTools.secrets.create", {
556+ name: "api-token",
557+ provider: "memory",
558+ });
559+
560+ expect(result).toMatchObject({
561+ id: expect.any(String),
562+ url: expect.any(String),
563+ instructions: expect.stringContaining("placeholder"),
564+ });
565+ const url = new URL((result as { readonly url: string }).url);
566+ expect(url.origin).toBe("http://executor.test");
567+ expect(url.pathname).toBe("/secrets");
568+ expect(url.searchParams.get("scope")).toBe("test-scope");
569+ expect(url.searchParams.get("name")).toBe("api-token");
570+ expect(url.searchParams.get("provider")).toBe("memory");
571+ expect(url.searchParams.get("secretId")).toBe((result as { readonly id: string }).id);
572+
573+ const idResult = yield* executor.tools.invoke("executor.coreTools.secrets.create", {
574+ scope: "test-scope",
575+ name: "api-token-by-id",
576+ provider: "memory",
577+ });
578+ const idUrl = new URL((idResult as { readonly url: string }).url);
579+ expect(idUrl.searchParams.get("scope")).toBe("test-scope");
580+ expect(idUrl.searchParams.get("name")).toBe("api-token-by-id");
581+
582+ const invalidProvider = yield* executor.tools.invoke("executor.coreTools.secrets.create", {
583+ name: "api-token-invalid-provider",
584+ provider: "vercel",
585+ });
586+ expect(invalidProvider).toMatchObject({
587+ ok: false,
588+ error: {
589+ code: "secret_provider_not_found",
590+ message:
591+ 'Unknown secret storage provider "vercel". Omit provider unless the user chose one from secrets.providers.',
592+ details: { providers: ["memory"] },
593+ },
594+ });
595+
596+ yield* executor.close();
597+ yield* Effect.promise(() => config.testDb.close());
598+ }),
599+ );
600+
601+ it.effect("core tools require an explicit secret scope when multiple scopes are visible", () =>
602+ Effect.gen(function* () {
603+ const orgScope = Scope.make({
604+ id: ScopeId.make("org"),
605+ name: "Org",
606+ createdAt: new Date(),
607+ });
608+ const userScope = Scope.make({
609+ id: ScopeId.make("user"),
610+ name: "User",
611+ createdAt: new Date(),
612+ });
613+ const config = makeTestConfig({
614+ scopes: [userScope, orgScope],
615+ plugins: [memorySecretsPlugin()] as const,
616+ });
617+ const executor = yield* createExecutor({
618+ ...config,
619+ coreTools: { webBaseUrl: "http://executor.test" },
620+ });
621+
622+ const result = yield* executor.tools.invoke("executor.coreTools.secrets.create", {
623+ name: "api-token",
624+ });
625+
626+ expect(result).toMatchObject({
627+ ok: false,
628+ error: {
629+ code: "scope_not_found",
630+ message:
631+ "Multiple scopes are visible. Call scopes.list and pass the target scope id or name.",
632+ },
633+ });
634+
635+ yield* executor.close();
636+ yield* Effect.promise(() => config.testDb.close());
637+ }),
638+ );
639+
640+ it.effect("core tools cover web UI source secret and policy management flows", () =>
641+ Effect.gen(function* () {
642+ const config = makeTestConfig({
643+ plugins: [memorySecretsPlugin(), configurableSourcePlugin] as const,
644+ });
645+ const executor = yield* createExecutor({
646+ ...config,
647+ coreTools: { webBaseUrl: "http://executor.test" },
648+ });
649+
650+ yield* executor.configurable.registerSource("test-scope");
651+ yield* executor.secrets.set({
652+ id: SecretId.make("agent-secret"),
653+ name: "Agent secret",
654+ value: "secret-value",
655+ scope: ScopeId.make("test-scope"),
656+ provider: "memory",
657+ });
658+
659+ expect(
660+ yield* executor.tools.invoke("executor.coreTools.secrets.providers", {}),
661+ ).toMatchObject({
662+ providers: expect.arrayContaining(["memory"]),
663+ });
664+ expect(
665+ yield* executor.tools.invoke("executor.coreTools.secrets.status", {
666+ id: "agent-secret",
667+ }),
668+ ).toEqual({ id: "agent-secret", status: "resolved" });
669+ expect(
670+ yield* executor.tools.invoke("executor.coreTools.secrets.usages", {
671+ id: "agent-secret",
672+ }),
673+ ).toEqual({ usages: [] });
674+
675+ const createdPolicy = yield* executor.tools.invoke("executor.coreTools.policies.create", {
676+ targetScope: "test-scope",
677+ pattern: "configured-source.*",
678+ action: "require_approval",
679+ });
680+ const policyId = (createdPolicy as { readonly policy: { readonly id: string } }).policy.id;
681+ expect(createdPolicy).toMatchObject({
682+ policy: {
683+ id: expect.any(String),
684+ scopeId: "test-scope",
685+ pattern: "configured-source.*",
686+ action: "require_approval",
687+ },
688+ });
689+ expect(yield* executor.tools.invoke("executor.coreTools.policies.list", {})).toMatchObject({
690+ policies: [expect.objectContaining({ id: policyId })],
691+ });
692+ expect(
693+ yield* executor.tools.invoke("executor.coreTools.policies.update", {
694+ id: policyId,
695+ targetScope: "test-scope",
696+ action: "approve",
697+ }),
698+ ).toMatchObject({ policy: { id: policyId, action: "approve" } });
699+ yield* executor.tools.invoke("executor.coreTools.policies.remove", {
700+ id: policyId,
701+ targetScope: "test-scope",
702+ });
703+ expect(yield* executor.policies.list()).toEqual([]);
704+
705+ yield* executor.tools.invoke("executor.coreTools.sources.refresh", {
706+ id: "configured-source",
707+ targetScope: "test-scope",
708+ });
709+ yield* executor.tools.invoke("executor.coreTools.sources.remove", {
710+ id: "configured-source",
711+ targetScope: "test-scope",
712+ });
713+ expect((yield* executor.sources.list()).map((source) => source.id)).not.toContain(
714+ "configured-source",
715+ );
716+
717+ yield* executor.tools.invoke("executor.coreTools.secrets.remove", {
718+ id: "agent-secret",
719+ targetScope: "test-scope",
720+ });
721+ expect(yield* executor.secrets.list()).toEqual([]);
722+
723+ yield* executor.close();
724+ yield* Effect.promise(() => config.testDb.close());
725+ }),
726+ );
727+
728+ it.effect("core tools start OAuth and expose completed connections", () =>
729+ Effect.scoped(
730+ Effect.gen(function* () {
731+ const oauthServer = yield* serveOAuthTestServer();
732+ const config = makeTestConfig({ plugins: [memorySecretsPlugin()] as const });
733+ const executor = yield* createExecutor({
734+ ...config,
735+ coreTools: { webBaseUrl: "http://executor.test" },
736+ oauthEndpointUrlPolicy: { allowHttp: true },
737+ });
738+
739+ yield* executor.secrets.set({
740+ id: SecretId.make("client-id"),
741+ name: "OAuth client id",
742+ value: "test-client",
743+ scope: ScopeId.make("test-scope"),
744+ provider: "memory",
745+ });
746+ yield* executor.secrets.set({
747+ id: SecretId.make("client-secret"),
748+ name: "OAuth client secret",
749+ value: "test-secret",
750+ scope: ScopeId.make("test-scope"),
751+ provider: "memory",
752+ });
753+
754+ const schema = yield* executor.tools.schema("executor.coreTools.oauth.start");
755+ expect(schema?.inputTypeScript).toContain("credentialScope?: string");
756+ expect(schema?.inputTypeScript).not.toContain("scope: string; endpoint");
757+
758+ const started = yield* executor.tools.invoke("executor.coreTools.oauth.start", {
759+ credentialScope: "test-scope",
760+ endpoint: oauthServer.resourceUrl,
761+ connectionId: "agent-oauth",
762+ pluginId: "test-plugin",
763+ strategy: {
764+ kind: "client-credentials",
765+ tokenEndpoint: oauthServer.tokenEndpoint,
766+ clientIdSecretId: "client-id",
767+ clientSecretSecretId: "client-secret",
768+ scopes: ["read"],
769+ },
770+ });
771+
772+ expect(started).toMatchObject({
773+ authorizationUrl: null,
774+ completedConnection: { connectionId: "agent-oauth" },
775+ instructions: expect.stringContaining("completed without a browser handoff"),
776+ });
777+
778+ const listed = yield* executor.tools.invoke("executor.coreTools.connections.list", {});
779+ expect(listed).toMatchObject({
780+ connections: [expect.objectContaining({ id: "agent-oauth", provider: "oauth2" })],
781+ });
782+ expect(
783+ yield* executor.tools.invoke("executor.coreTools.connections.providers", {}),
784+ ).toMatchObject({
785+ providers: expect.arrayContaining(["oauth2"]),
786+ });
787+ expect(
788+ yield* executor.tools.invoke("executor.coreTools.connections.usages", {
789+ id: "agent-oauth",
790+ }),
791+ ).toEqual({ usages: [] });
792+ yield* executor.tools.invoke("executor.coreTools.connections.remove", {
793+ id: "agent-oauth",
794+ targetScope: "test-scope",
795+ });
796+ expect(yield* executor.connections.list()).toEqual([]);
797+
798+ yield* executor.close();
799+ yield* Effect.promise(() => config.testDb.close());
800+ }),
801+ ),
802+ );
803+
804+ it.effect("core OAuth tools return actionable tool failures for expected errors", () =>
805+ Effect.gen(function* () {
806+ const config = makeTestConfig({ plugins: [memorySecretsPlugin()] as const });
807+ const executor = yield* createExecutor({
808+ ...config,
809+ coreTools: { webBaseUrl: "http://executor.test" },
810+ oauthEndpointUrlPolicy: { allowHttp: true },
811+ });
812+
813+ const result = yield* executor.tools.invoke("executor.coreTools.oauth.probe", {
814+ endpoint: "http://127.0.0.1:1/mcp",
815+ });
816+
817+ expect(result).toMatchObject({
818+ ok: false,
819+ error: {
820+ code: "oauth_probe_failed",
821+ },
822+ });
823+
824+ yield* executor.close();
825+ yield* Effect.promise(() => config.testDb.close());
826+ }),
827+ );
828+
829+ it.effect("core tools start browser OAuth and expose the completed connection", () =>
830+ Effect.scoped(
831+ Effect.gen(function* () {
832+ const oauthServer = yield* serveOAuthTestServer();
833+ const config = makeTestConfig({ plugins: [memorySecretsPlugin()] as const });
834+ const executor = yield* createExecutor({
835+ ...config,
836+ coreTools: { webBaseUrl: "http://executor.test" },
837+ oauthEndpointUrlPolicy: { allowHttp: true },
838+ });
839+
840+ yield* executor.secrets.set({
841+ id: SecretId.make("browser-client-id"),
842+ name: "OAuth client id",
843+ value: "test-client",
844+ scope: ScopeId.make("test-scope"),
845+ provider: "memory",
846+ });
847+ yield* executor.secrets.set({
848+ id: SecretId.make("browser-client-secret"),
849+ name: "OAuth client secret",
850+ value: "test-secret",
851+ scope: ScopeId.make("test-scope"),
852+ provider: "memory",
853+ });
854+
855+ const started = yield* executor.tools.invoke("executor.coreTools.oauth.start", {
856+ credentialScope: "test",
857+ endpoint: oauthServer.resourceUrl,
858+ connectionId: "agent-browser-oauth",
859+ pluginId: "test-plugin",
860+ strategy: {
861+ kind: "authorization-code",
862+ authorizationEndpoint: oauthServer.authorizationEndpoint,
863+ tokenEndpoint: oauthServer.tokenEndpoint,
864+ clientIdSecretId: "browser-client-id",
865+ clientSecretSecretId: "browser-client-secret",
866+ scopes: ["read"],
867+ },
868+ });
869+ expect(started).toMatchObject({
870+ authorizationUrl: expect.stringContaining(oauthServer.authorizationEndpoint),
871+ completedConnection: null,
872+ instructions: expect.stringContaining("open this authorization URL"),
873+ });
874+
875+ const authorizationUrl = (started as { authorizationUrl: string }).authorizationUrl;
876+ const callback = yield* oauthServer.completeAuthorizationCodeFlow({ authorizationUrl });
877+ const completed = yield* executor.oauth.complete({
878+ state: callback.state,
879+ code: callback.code,
880+ });
881+ expect(completed.connectionId).toBe("agent-browser-oauth");
882+
883+ const listed = yield* executor.tools.invoke("executor.coreTools.connections.list", {});
884+ expect(listed).toMatchObject({
885+ connections: [expect.objectContaining({ id: "agent-browser-oauth", provider: "oauth2" })],
886+ });
887+
888+ yield* executor.close();
889+ yield* Effect.promise(() => config.testDb.close());
890+ }),
891+ ),
892+ );
476893 });
packages/core/sdk/src/executor.ts+124−18
@@ -5,6 +5,7 @@ import { · 4 unmodified lines
55 Layer,
66 Match,
77 Option,
8+ Predicate,
89 Result,
910 Schema,
1011 Semaphore,
@@ -28,6 +29,7 @@ import { · 17 unmodified lines
2829 } from "./fuma-runtime";
2930
3031 import { makeFumaBlobStore, pluginBlobStore } from "./blob";
32+import { coreToolsPlugin } from "./core-tools";
3133 import {
3234 ConnectionProviderState,
3335 ConnectionRef,
@@ -110,6 +112,7 @@ import type { · 76 unmodified lines
110112 Elicit,
111113 PluginCtx,
112114 PluginExtensions,
115+ SourceConfigureSchema,
113116 StaticSourceDecl,
114117 StaticToolDecl,
115118 StaticToolSchema,
@@ -410,6 +413,20 @@ export interface ExecutorConfig<TPlugins extends readonly AnyPlugin[] = readonly · 294 unmodified lines
410413 readonly timeout?: Duration.Input;
411414 readonly hostedOutboundPolicy?: boolean;
412415 };
416+ /**
417+ * Enable the built-in `core-tools` plugin which contributes
418+ * agent-facing static tools (`scopes.list`, `secrets.list`,
419+ * `secrets.create`). The `webBaseUrl` is where the executor's web
420+ * UI lives; `secrets.create` builds a URL elicitation that points
421+ * the user at `${webBaseUrl}/secrets?...` so the plaintext value
422+ * never crosses the agent.
423+ *
424+ * Omit to skip registration (tests, MCP-only hosts that don't
425+ * surface a web UI, etc.).
426+ */
427+ readonly coreTools?: {
428+ readonly webBaseUrl: string;
429+ };
413430 }
414431
415432 // ---------------------------------------------------------------------------
@@ -562,21 +579,59 @@ const toToolJsonSchema = ( · 146 unmodified lines
562579 });
563580 };
564581
582+const toConfigureJsonSchema = (
583+ schema: StaticToolSchema | Schema.Decoder<unknown, never> | undefined,
584+): unknown => {
585+ if (schema == null) return undefined;
586+ const standard = schema as {
587+ readonly "~standard"?: {
588+ readonly validate?: unknown;
589+ readonly jsonSchema?: StaticToolSchema["~standard"]["jsonSchema"];
590+ };
591+ };
592+ if (typeof standard["~standard"]?.validate !== "function") {
593+ const jsonSchema = Schema.toStandardSchemaV1(
594+ Schema.toStandardJSONSchemaV1(schema as Schema.Decoder<unknown, never>) as never,
595+ ) as StaticToolSchema;
596+ return toToolJsonSchema(jsonSchema);
597+ }
598+ return standard["~standard"].jsonSchema?.input({
599+ target: "draft-2020-12",
600+ });
601+};
602+
565603 const decodeConfigureInput = (
566604 schema: StaticToolSchema | Schema.Decoder<unknown, never> | undefined,
567605 input: unknown,
568606 ): Effect.Effect<unknown, unknown> => {
569607 if (schema == null) return Effect.succeed(input);
570− if (!("~standard" in schema)) {
571− return Schema.decodeUnknownEffect(schema)(input);
608+ const standard = schema as {
609+ readonly "~standard"?: { readonly validate?: unknown };
610+ };
611+ if (standard["~standard"] === undefined || typeof standard["~standard"].validate !== "function") {
612+ return Schema.decodeUnknownEffect(schema as Schema.Decoder<unknown, never>)(input);
572613 }
573− return Effect.promise(() => Promise.resolve(schema["~standard"].validate(input))).pipe(
574− Effect.flatMap((result) =>
575− "value" in result ? Effect.succeed(result.value) : Effect.fail(result),
576− ),
614+ return Effect.promise(() =>
615+ Promise.resolve((standard["~standard"]!.validate as (input: unknown) => unknown)(input)),
616+ ).pipe(
617+ Effect.flatMap((result) => {
618+ const validationResult = result as { readonly value?: unknown };
619+ return "value" in validationResult
620+ ? Effect.succeed(validationResult.value)
621+ : Effect.fail(result);
622+ }),
577623 );
578624 };
579625
626+const sourceConfigureSchemaView = (
627+ pluginId: string,
628+ configure: NonNullable<AnyPlugin["sourceConfigure"]>,
629+): SourceConfigureSchema => ({
630+ pluginId,
631+ type: configure.type,
632+ schema: toConfigureJsonSchema(configure.schema),
633+});
634+
580635 const EXECUTOR_SOURCE_ID = "executor";
581636 const EXECUTOR_SOURCE: StaticSourceDecl = {
582637 id: EXECUTOR_SOURCE_ID,
@@ -1031,7 +1086,25 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 448 unmodified lines
10311086 const empty: readonly AnyPlugin[] = [];
10321087 return empty as TPlugins;
10331088 };
1034− const { scopes, plugins = defaultPlugins() } = config;
1089+ const { scopes, plugins: userPlugins = defaultPlugins() } = config;
1090+
1091+ if (scopes.length === 0) {
1092+ return yield* new StorageError({
1093+ message: "createExecutor requires a non-empty scopes array",
1094+ cause: undefined,
1095+ });
1096+ }
1097+
1098+ // Built-in core-tools plugin: contributes scopes.list / secrets.list /
1099+ // secrets.create static tools so agents can manage executor primitives
1100+ // without the host wiring it explicitly. Opt-in via `coreTools` config.
1101+ const plugins: readonly AnyPlugin[] = config.coreTools
1102+ ? ([
1103+ coreToolsPlugin({ webBaseUrl: config.coreTools.webBaseUrl }),
1104+ ...userPlugins,
1105+ ] as readonly AnyPlugin[])
1106+ : (userPlugins as readonly AnyPlugin[]);
1107+
10351108 const tables = yield* Effect.try({
10361109 try: () => collectTables(plugins),
10371110 catch: (cause) => storageFailureFromUnknown("Failed to collect executor tables", cause),
@@ -1051,14 +1124,6 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 13 unmodified lines
10511124 },
10521125 catch: (cause) => storageFailureFromUnknown("Failed to validate executor tables", cause),
10531126 });
1054−
1055− if (scopes.length === 0) {
1056− return yield* new StorageError({
1057− message: "createExecutor requires a non-empty scopes array",
1058− cause: undefined,
1059− });
1060− }
1061−
10621127 const scopeIds = scopes.map((s) => String(s.id));
10631128 const rootDb = withQueryContext(rootDbUntyped, {
10641129 allowedScopeIds: new Set(scopeIds),
@@ -1661,6 +1726,7 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 596 unmodified lines
16611726 const list = yield* secretsList();
16621727 return list.map((ref) => ({
16631728 id: String(ref.id),
1729+ scopeId: ref.scopeId,
16641730 name: ref.name,
16651731 provider: ref.provider,
16661732 }));
@@ -3051,6 +3117,36 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 1384 unmodified lines
30513117 },
30523118 })
30533119 .pipe(Effect.asVoid),
3120+ list: () => listSources(),
3121+ remove: (input) => removeSource(input),
3122+ refresh: (input) => refreshSource(input),
3123+ detect: (url) => detectSource(url),
3124+ configure: (input) => sourceConfigure(input),
3125+ listBindings: (input) => sourceBindingList(input),
3126+ resolveBinding: (input) => sourceBindingResolve(input),
3127+ setBinding: (input) => sourceBindingSet(input),
3128+ removeBinding: (input) => sourceBindingRemove(input),
3129+ configureSchemas: () =>
3130+ Array.from(runtimes.values())
3131+ .map(({ plugin }) =>
3132+ plugin.sourceConfigure
3133+ ? sourceConfigureSchemaView(plugin.id, plugin.sourceConfigure)
3134+ : undefined,
3135+ )
3136+ .filter(Predicate.isNotUndefined),
3137+ presets: () =>
3138+ Array.from(runtimes.values()).flatMap(({ plugin }) =>
3139+ (plugin.sourcePresets ?? []).map((preset) => ({
3140+ ...preset,
3141+ pluginId: plugin.id,
3142+ })),
3143+ ),
3144+ },
3145+ policies: {
3146+ list: () => policiesList(),
3147+ create: (input) => policiesCreate(input),
3148+ update: (input) => policiesUpdate(input),
3149+ remove: (input) => policiesRemove(input),
30543150 },
30553151 definitions: {
30563152 register: (input: DefinitionsInput) =>
@@ -3061,6 +3157,10 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 4 unmodified lines
30613157 get: (id) => secretsGet(id),
30623158 getAtScope: (id, scope) => secretsGetAtScope(id, scope),
30633159 list: () => secretsListForCtx(),
3160+ status: (id) => secretsStatus(id),
3161+ usages: (id) => secretsUsages(id),
3162+ providers: () =>
3163+ Effect.sync(() => Array.from(secretProviders.keys()) as readonly string[]),
30643164 set: (input) => secretsSet(input),
30653165 remove: (input) => secretsRemove(input),
30663166 },
@@ -3068,6 +3168,9 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 1 unmodified line
30683168 get: (id) => connectionsGet(id),
30693169 getAtScope: (id, scope) => connectionsGetAtScope(id, scope),
30703170 list: () => connectionsListForCtx(),
3171+ usages: (id) => connectionsUsages(id),
3172+ providers: () =>
3173+ Effect.sync(() => Array.from(connectionProviders.keys()) as readonly string[]),
30713174 create: (input) => connectionsCreate(input),
30723175 updateTokens: (input) => connectionsUpdateTokens(input),
30733176 setIdentityLabel: (id, label) => connectionsSetIdentityLabel(id, label),
@@ -3092,11 +3195,14 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 18 unmodified lines
30923195 // Resolve static declarations to the in-memory pools. NO DB WRITES.
30933196 // Plugin-owned executor tools are intentionally mounted under the
30943197 // single `executor` namespace so source inventory is about configured
3095− // integrations, not plugin management surfaces:
3198+ // integrations, not plugin management surfaces. The static source id
3199+ // becomes the path segment, so plugins can expose TypeScript-friendly
3200+ // management namespaces without changing their persisted plugin ids:
30963201 // openapi.addSource -> executor.openapi.addSource
3202+ // googleDiscovery.addSource -> executor.googleDiscovery.addSource
30973203 const decls = plugin.staticSources ? plugin.staticSources(extension) : [];
30983204 for (const source of decls) {
3099− const mountUnderExecutor = source.kind === "executor" && source.id === plugin.id;
3205+ const mountUnderExecutor = source.kind === "executor";
31003206 const mountedSource = mountUnderExecutor ? EXECUTOR_SOURCE : source;
31013207
31023208 if (mountUnderExecutor) {
@@ -3120,7 +3226,7 @@ export const createExecutor = <const TPlugins extends readonly AnyPlugin[] = rea · 17 unmodified lines
31203226 const mountedTool = mountUnderExecutor
31213227 ? {
31223228 ...tool,
3123− name: `${plugin.id}.${tool.name}`,
3229+ name: `${source.id}.${tool.name}`,
31243230 }
31253231 : tool;
31263232 const fqid = `${mountedSource.id}.${mountedTool.name}`;
packages/core/sdk/src/index.ts+8−1
@@ -41,7 +41,7 @@ export { StorageError, UniqueViolationError, isStorageFailure } from "./fuma-run · 40 unmodified lines
4141 export { ScopeId, ToolId, SecretId, PolicyId, ConnectionId, CredentialBindingId } from "./ids";
4242
4343 // Scope
44−export { Scope } from "./scope";
44+export { Scope, defaultSourceInstallScopeId } from "./scope";
4545
4646 // Errors (tagged)
4747 export {
@@ -293,6 +293,7 @@ export { · 245 unmodified lines
293293 type StorageDeps,
294294 type StaticSourceDecl,
295295 type StaticToolDecl,
296+ type StaticToolSchema,
296297 type StaticToolExecuteContext,
297298 type StaticToolHandlerInput,
298299 type StaticToolInput,
@@ -328,6 +329,12 @@ export { · 29 unmodified lines
328329 collectTables,
329330 } from "./executor";
330331
332+// Built-in core-tools plugin (scopes.list, secrets.list, secrets.create
333+// with URL elicitation). Auto-registered by createExecutor when
334+// `coreTools` is set on the config; also exportable for callers who
335+// want to register it manually.
336+export { coreToolsPlugin, type CoreToolsPluginOptions } from "./core-tools";
337+
331338 // CLI / runtime config
332339 export {
333340 defineExecutorConfig,
packages/core/sdk/src/plugin.ts+99−3
@@ -14,9 +14,17 @@ import type { · 13 unmodified lines
1414 RemoveConnectionInput,
1515 UpdateConnectionTokensInput,
1616 } from "./connections";
17−import type { CredentialBindingsFacade } from "./credential-bindings";
17+import type {
18+ CredentialBindingRef,
19+ CredentialBindingsFacade,
20+ RemoveSourceCredentialBindingInput,
21+ SetSourceCredentialBindingInput,
22+ SourceCredentialBindingSlotInput,
23+ SourceCredentialBindingSourceInput,
24+} from "./credential-bindings";
1825 import type { DefinitionsInput, SourceInput, ToolAnnotations, ToolRow } from "./core-schema";
19−import type { RemoveSourceInput, SourceDetectionResult } from "./types";
26+import type { ScopeId } from "./ids";
27+import type { RefreshSourceInput, RemoveSourceInput, Source, SourceDetectionResult } from "./types";
2028 import type {
2129 ElicitationDeclinedError,
2230 ElicitationHandler,
@@ -31,9 +39,16 @@ import type { · 8 unmodified lines
3139 ConnectionRefreshNotSupportedError,
3240 SecretInUseError,
3341 SecretOwnedByConnectionError,
42+ SourceRemovalNotAllowedError,
3443 } from "./errors";
3544 import type { OAuthService } from "./oauth";
3645 import type { PluginStorageFacade } from "./plugin-storage";
46+import type {
47+ CreateToolPolicyInput,
48+ RemoveToolPolicyInput,
49+ ToolPolicy,
50+ UpdateToolPolicyInput,
51+} from "./policies";
3752 import type { Scope } from "./scope";
3853 import type { RemoveSecretInput, SecretProvider, SecretRef, SetSecretInput } from "./secrets";
3954 import type { Usage, UsagesForConnectionInput, UsagesForSecretInput } from "./usages";
@@ -99,6 +114,47 @@ export interface PluginCtx<TStore = unknown> { · 59 unmodified lines
99114 readonly name?: string;
100115 readonly url?: string | null;
101116 }) => Effect.Effect<void, StorageFailure>;
117+ readonly list: () => Effect.Effect<readonly Source[], StorageFailure>;
118+ readonly remove: (
119+ input: RemoveSourceInput,
120+ ) => Effect.Effect<void, SourceRemovalNotAllowedError | StorageFailure>;
121+ readonly refresh: (input: RefreshSourceInput) => Effect.Effect<void, StorageFailure>;
122+ readonly detect: (
123+ url: string,
124+ ) => Effect.Effect<readonly SourceDetectionResult[], StorageFailure>;
125+ readonly configure: (input: {
126+ readonly source: {
127+ readonly id: string;
128+ readonly scope: ScopeId | string;
129+ };
130+ readonly scope: ScopeId | string;
131+ readonly type?: string;
132+ readonly config: unknown;
133+ }) => Effect.Effect<unknown, StorageFailure>;
134+ readonly listBindings: (
135+ input: SourceCredentialBindingSourceInput,
136+ ) => Effect.Effect<readonly CredentialBindingRef[], StorageFailure>;
137+ readonly resolveBinding: (
138+ input: SourceCredentialBindingSlotInput,
139+ ) => Effect.Effect<CredentialBindingRef | null, StorageFailure>;
140+ readonly setBinding: (
141+ input: SetSourceCredentialBindingInput,
142+ ) => Effect.Effect<CredentialBindingRef, StorageFailure>;
143+ readonly removeBinding: (
144+ input: RemoveSourceCredentialBindingInput,
145+ ) => Effect.Effect<void, StorageFailure>;
146+ /** Source configuration declarations for every plugin that
147+ * supports `executor.sources.configure`. Exposed to core tools
148+ * so agent-facing configuration surfaces can describe the
149+ * plugin-specific payload shape before dispatching a write. */
150+ readonly configureSchemas: () => readonly SourceConfigureSchema[];
151+ readonly presets: () => readonly SourcePresetCatalogEntry[];
152+ };
153+ readonly policies: {
154+ readonly list: () => Effect.Effect<readonly ToolPolicy[], StorageFailure>;
155+ readonly create: (input: CreateToolPolicyInput) => Effect.Effect<ToolPolicy, StorageFailure>;
156+ readonly update: (input: UpdateToolPolicyInput) => Effect.Effect<ToolPolicy, StorageFailure>;
157+ readonly remove: (input: RemoveToolPolicyInput) => Effect.Effect<void, StorageFailure>;
102158 };
103159 /** Register shared JSON-schema `$defs` for a source. Tool
104160 * input/output schemas registered via `sources.register` can carry
@@ -123,9 +179,17 @@ export interface PluginCtx<TStore = unknown> { · 18 unmodified lines
123179 * `owned_by_connection_id` set) are filtered out so they don't
124180 * clutter the UI — users see the Connection instead. */
125181 readonly list: () => Effect.Effect<
126− readonly { readonly id: string; readonly name: string; readonly provider: string }[],
182+ readonly {
183+ readonly id: string;
184+ readonly scopeId: ScopeId;
185+ readonly name: string;
186+ readonly provider: string;
187+ }[],
127188 StorageFailure
128189 >;
190+ readonly status: (id: string) => Effect.Effect<"resolved" | "missing", StorageFailure>;
191+ readonly usages: (id: string) => Effect.Effect<readonly Usage[], StorageFailure>;
192+ readonly providers: () => Effect.Effect<readonly string[], never>;
129193 /** Write a secret value through a provider. Used by plugins that
130194 * mint secrets on behalf of the user (OAuth2 token storage,
131195 * interactive onboarding flows). Normally writes go through
@@ -156,6 +220,8 @@ export interface PluginCtx<TStore = unknown> { · 24 unmodified lines
156220 scope: string,
157221 ) => Effect.Effect<ConnectionRef | null, StorageFailure>;
158222 readonly list: () => Effect.Effect<readonly ConnectionRef[], StorageFailure>;
223+ readonly usages: (id: string) => Effect.Effect<readonly Usage[], StorageFailure>;
224+ readonly providers: () => Effect.Effect<readonly string[], never>;
159225 readonly create: (
160226 input: CreateConnectionInput,
161227 ) => Effect.Effect<ConnectionRef, ConnectionProviderNotRegisteredError | StorageFailure>;
@@ -371,6 +437,30 @@ export interface SourceConfigureDecl<TStore = unknown> { · 209 unmodified lines
371437 ) => Effect.Effect<unknown, unknown>;
372438 }
373439
440+export interface SourceConfigureSchema {
441+ readonly pluginId: string;
442+ readonly type: string;
443+ readonly schema?: unknown;
444+}
445+
446+export interface SourcePreset {
447+ readonly id: string;
448+ readonly name: string;
449+ readonly summary: string;
450+ readonly url?: string;
451+ readonly endpoint?: string;
452+ readonly icon?: string;
453+ readonly featured?: boolean;
454+ readonly transport?: "remote" | "stdio";
455+ readonly command?: string;
456+ readonly args?: readonly string[];
457+ readonly env?: Readonly<Record<string, string>>;
458+}
459+
460+export interface SourcePresetCatalogEntry extends SourcePreset {
461+ readonly pluginId: string;
462+}
463+
374464 // ---------------------------------------------------------------------------
375465 // PluginSpec — what a `definePlugin(factory)` call returns.
376466 // ---------------------------------------------------------------------------
@@ -432,6 +522,12 @@ export interface PluginSpec< · 55 unmodified lines
432522 * sync. */
433523 readonly clientConfig?: unknown;
434524
525+ /** Source presets shown by the web UI's "Popular sources" list and
526+ * exposed through core tools for agents. Keep this server-safe:
527+ * no React components, only JSON-serializable metadata and optional
528+ * add-flow hints such as URL or stdio command. */
529+ readonly sourcePresets?: readonly SourcePreset[];
530+
435531 /** Build the plugin's extension API. The returned object becomes
436532 * `executor[plugin.id]` and is also the `self` passed to
437533 * `staticSources`. Field order matters: `extension` MUST appear
packages/core/sdk/src/schema-types.test.ts+29−0
@@ -405,4 +405,33 @@ describe("schema-types", () => { · 404 unmodified lines
405405 outputTypeScript: "unknown",
406406 });
407407 });
408+
409+ it("renders open object schemas as unknown-key records", async () => {
410+ await expect(
411+ buildToolTypeScriptPreview({
412+ inputSchema: {
413+ type: "object",
414+ properties: {
415+ resourceMetadata: {
416+ anyOf: [{ type: "object" }, { type: "null" }],
417+ },
418+ },
419+ required: ["resourceMetadata"],
420+ additionalProperties: false,
421+ },
422+ outputSchema: {
423+ type: "object",
424+ properties: {
425+ metadata: { type: "object" },
426+ },
427+ required: ["metadata"],
428+ additionalProperties: false,
429+ },
430+ defs: new Map(),
431+ }),
432+ ).resolves.toEqual({
433+ inputTypeScript: "{ resourceMetadata: { [k: string]: unknown; } | null; }",
434+ outputTypeScript: "{ metadata: { [k: string]: unknown; }; }",
435+ });
436+ });
408437 });
packages/core/sdk/src/schema-types.ts+9−1
@@ -165,7 +165,15 @@ const normalizeSchema = (node: unknown): unknown => { · 164 unmodified lines
165165 normalized[key] = normalizeSchema(value);
166166 }
167167
168− return normalizeNullable(normalized);
168+ const nullable = normalizeNullable(normalized);
169+ if (
170+ nullable.type === "object" &&
171+ nullable.properties === undefined &&
172+ nullable.additionalProperties === undefined
173+ ) {
174+ return { ...nullable, additionalProperties: {} };
175+ }
176+ return nullable;
169177 };
170178
171179 const mergeDefinitions = (
packages/core/sdk/src/scope.ts+13−0
@@ -8,3 +8,16 @@ export const Scope = Schema.Struct({ · 7 unmodified lines
88 createdAt: Schema.Date,
99 });
1010 export type Scope = typeof Scope.Type;
11+
12+/**
13+ * Source-add flows that do not expose a user-facing placement choice install
14+ * sources at the outermost visible scope. Local executors have one scope, while
15+ * cloud executors use an innermost personal scope plus an outer organization
16+ * scope where shared sources live.
17+ */
18+export const defaultSourceInstallScopeId = (
19+ scopes: readonly { readonly id: ScopeId | string }[],
20+): string | null => {
21+ const scope = scopes[scopes.length - 1];
22+ return scope ? String(scope.id) : null;
23+};
packages/hosts/mcp/src/server.test.ts+29−0
@@ -559,6 +559,35 @@ describe("MCP host server — client without elicitation (pause/resume)", () => · 558 unmodified lines
559559 const structured = result.structuredContent as Record<string, unknown>;
560560 expect(structured?.executionId).toBe("exec_42");
561561 expect(structured?.status).toBe("waiting_for_interaction");
562+ const interaction = structured.interaction as Record<string, unknown>;
563+ expect(interaction.instructions).toContain(
564+ "Ask the user for values matching requestedSchema",
565+ );
566+ });
567+ });
568+
569+ it("default model resume mode explains empty form schemas as model-side confirmation", async () => {
570+ const engine = makeStubEngine({
571+ executeWithPause: () =>
572+ Effect.succeed(
573+ makePausedResult(
574+ "exec_confirm",
575+ FormElicitation.make({ message: "Confirm source add", requestedSchema: {} }),
576+ ),
577+ ),
578+ });
579+
580+ await withClient(engine, NO_CAPS, async (client) => {
581+ const result = await client.callTool({
582+ name: "execute",
583+ arguments: { code: "confirm-me" },
584+ });
585+
586+ expect(textOf(result)).toContain("no browser form is waiting");
587+ const structured = result.structuredContent as Record<string, unknown>;
588+ const interaction = structured.interaction as Record<string, unknown>;
589+ expect(interaction.instructions).toContain("model-side confirmation gate");
590+ expect(interaction.instructions).toContain('action "accept"');
562591 });
563592 });
564593
packages/kernel/runtime-dynamic-worker/src/executor.ts+27−6
@@ -267,6 +267,7 @@ const rehydrateBinary = (value: unknown, seen = new WeakSet<object>()): unknown · 266 unmodified lines
267267 }
268268 seen.add(value);
269269 if (isBinaryEnvelope(value)) {
270+ seen.delete(value);
270271 if (value.kind === "file" && typeof value.name === "string") {
271272 return new File([value.buffer], value.name, {
272273 type: value.type,
@@ -275,12 +276,20 @@ const rehydrateBinary = (value: unknown, seen = new WeakSet<object>()): unknown · 2 unmodified lines
275276 }
276277 return new Blob([value.buffer], { type: value.type });
277278 }
278− if (Array.isArray(value)) return value.map((item) => rehydrateBinary(item, seen));
279− if (!isPlainObject(value)) return value;
279+ if (Array.isArray(value)) {
280+ const out = value.map((item) => rehydrateBinary(item, seen));
281+ seen.delete(value);
282+ return out;
283+ }
284+ if (!isPlainObject(value)) {
285+ seen.delete(value);
286+ return value;
287+ }
280288 const out: Record<string, unknown> = {};
281289 for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
282290 out[k] = rehydrateBinary(v, seen);
283291 }
292+ seen.delete(value);
284293 return out;
285294 };
286295
@@ -294,7 +303,7 @@ const encodeBinary = async (value: unknown, seen = new WeakSet<object>()): Promi · 7 unmodified lines
294303 }
295304 seen.add(value);
296305 if (typeof File !== "undefined" && value instanceof File) {
297− return {
306+ const out = {
298307 __executorBinary: 1 as const,
299308 kind: "file" as const,
300309 type: value.type,
@@ -302,21 +311,33 @@ const encodeBinary = async (value: unknown, seen = new WeakSet<object>()): Promi · 1 unmodified line
302311 lastModified: value.lastModified,
303312 buffer: await value.arrayBuffer(),
304313 };
314+ seen.delete(value);
315+ return out;
305316 }
306317 if (value instanceof Blob) {
307− return {
318+ const out = {
308319 __executorBinary: 1 as const,
309320 kind: "blob" as const,
310321 type: value.type,
311322 buffer: await value.arrayBuffer(),
312323 };
324+ seen.delete(value);
325+ return out;
326+ }
327+ if (Array.isArray(value)) {
328+ const out = await Promise.all(value.map((item) => encodeBinary(item, seen)));
329+ seen.delete(value);
330+ return out;
331+ }
332+ if (!isPlainObject(value)) {
333+ seen.delete(value);
334+ return value;
313335 }
314− if (Array.isArray(value)) return Promise.all(value.map((item) => encodeBinary(item, seen)));
315− if (!isPlainObject(value)) return value;
316336 const out: Record<string, unknown> = {};
317337 for (const [k, v] of Object.entries(value as Record<string, unknown>)) {
318338 out[k] = await encodeBinary(v, seen);
319339 }
340+ seen.delete(value);
320341 return out;
321342 };
322343
packages/kernel/runtime-dynamic-worker/src/invocation.test.ts+26−0
@@ -114,6 +114,19 @@ describe("ToolDispatcher", () => { · 113 unmodified lines
114114 });
115115 });
116116
117+ it("allows shared object references in RPC args", async () => {
118+ const invoker = makeInvoker(({ args }) => args);
119+ const dispatcher = new ToolDispatcher(invoker, Effect.runPromise);
120+ const shared = { value: 1 };
121+
122+ const result = await dispatcher.call("test.tool", { first: shared, second: shared });
123+
124+ expect(result).toEqual({
125+ ok: true,
126+ result: { first: { value: 1 }, second: { value: 1 } },
127+ });
128+ });
129+
117130 it("passes the tool path correctly", async () => {
118131 let capturedPath = "";
119132 const invoker = makeInvoker(({ path }) => {
@@ -404,6 +417,19 @@ describe("makeDynamicWorkerExecutor", () => { · 284 unmodified lines
404417 expect(result.error).toBe("Internal tool error");
405418 });
406419
420+ it("returns shared object references from tool results", async () => {
421+ const executor = makeDynamicWorkerExecutor({ loader });
422+ const shared = { _tag: "None" };
423+ const invoker = makeInvoker(() => ({ first: shared, second: shared }));
424+
425+ const result = await Effect.runPromise(
426+ executor.execute("async () => await tools.shared.read({})", invoker),
427+ );
428+
429+ expect(result.error).toBeUndefined();
430+ expect(result.result).toEqual({ first: { _tag: "None" }, second: { _tag: "None" } });
431+ });
432+
407433 it("respects timeout", async () => {
408434 const executor = makeDynamicWorkerExecutor({ loader, timeoutMs: 500 });
409435 const invoker = makeInvoker(() => null);
packages/kernel/runtime-dynamic-worker/src/module-template.ts+17−6
@@ -89,7 +89,7 @@ export const buildExecutorModule = (body: string, timeoutMs: number): string => · 88 unmodified lines
8989 " if (seen.has(value)) throw new Error('Tool RPC payload contains a circular reference');",
9090 " seen.add(value);",
9191 " if (typeof File !== 'undefined' && value instanceof File) {",
92− " return {",
92+ " const out = {",
9393 " __executorBinary: 1,",
9494 " kind: 'file',",
9595 " type: value.type,",
@@ -97,14 +97,23 @@ export const buildExecutorModule = (body: string, timeoutMs: number): string => · 1 unmodified line
9797 " lastModified: value.lastModified,",
9898 " buffer: await value.arrayBuffer(),",
9999 " };",
100+ " seen.delete(value);",
101+ " return out;",
100102 " }",
101103 " if (value instanceof Blob) {",
102− " return { __executorBinary: 1, kind: 'blob', type: value.type, buffer: await value.arrayBuffer() };",
104+ " const out = { __executorBinary: 1, kind: 'blob', type: value.type, buffer: await value.arrayBuffer() };",
105+ " seen.delete(value);",
106+ " return out;",
107+ " }",
108+ " if (Array.isArray(value)) {",
109+ " const out = await Promise.all(value.map((item) => __encodeBinary(item, seen)));",
110+ " seen.delete(value);",
111+ " return out;",
103112 " }",
104− " if (Array.isArray(value)) return Promise.all(value.map((item) => __encodeBinary(item, seen)));",
105− " if (!__isPlainObject(value)) return value;",
113+ " if (!__isPlainObject(value)) { seen.delete(value); return value; }",
106114 " const out = {};",
107115 " for (const [k, v] of Object.entries(value)) out[k] = await __encodeBinary(v, seen);",
116+ " seen.delete(value);",
108117 " return out;",
109118 " };",
110119 " const __decodeBinary = (value, seen = new WeakSet()) => {",
@@ -113,6 +122,7 @@ export const buildExecutorModule = (body: string, timeoutMs: number): string => · 2 unmodified lines
113122 " if (seen.has(value)) throw new Error('Tool RPC payload contains a circular reference');",
114123 " seen.add(value);",
115124 " if (__isBinaryEnvelope(value)) {",
125+ " seen.delete(value);",
116126 " if (value.kind === 'file' && typeof value.name === 'string') {",
117127 " return new File([value.buffer], value.name, {",
118128 " type: value.type,",
@@ -121,10 +131,11 @@ export const buildExecutorModule = (body: string, timeoutMs: number): string => · 2 unmodified lines
121131 " }",
122132 " return new Blob([value.buffer], { type: value.type });",
123133 " }",
124− " if (Array.isArray(value)) return value.map((item) => __decodeBinary(item, seen));",
125− " if (!__isPlainObject(value)) return value;",
134+ " if (Array.isArray(value)) { const out = value.map((item) => __decodeBinary(item, seen)); seen.delete(value); return out; }",
135+ " if (!__isPlainObject(value)) { seen.delete(value); return value; }",
126136 " const out = {};",
127137 " for (const [k, v] of Object.entries(value)) out[k] = __decodeBinary(v, seen);",
138+ " seen.delete(value);",
128139 " return out;",
129140 " };",
130141 " const __publicToolErrorMessage = (error) => {",
packages/plugins/desktop-settings/package.json+1−0
@@ -38,6 +38,7 @@ · 37 unmodified lines
3838 },
3939 "scripts": {
4040 "build": "tsup",
41+ "test": "vitest run",
4142 "typecheck": "tsgo --noEmit",
4243 "typecheck:slow": "tsc --noEmit"
4344 },
packages/plugins/desktop-settings/src/server.test.ts+28−0
@@ -0,0 +1,28 @@
1+import { describe, expect, it } from "@effect/vitest";
2+import { Effect } from "effect";
3+
4+import { createExecutor } from "@executor-js/sdk";
5+import { makeTestConfig } from "@executor-js/sdk/testing";
6+
7+import { desktopSettingsPlugin } from "./server";
8+
9+describe("desktopSettingsPlugin", () => {
10+ it.effect("returns a browser handoff URL for Desktop-only settings", () =>
11+ Effect.gen(function* () {
12+ const config = makeTestConfig({
13+ plugins: [desktopSettingsPlugin({ webBaseUrl: "http://executor.test/base/" })] as const,
14+ });
15+ const executor = yield* createExecutor(config);
16+
17+ const result = yield* executor.tools.invoke("executor.desktopSettings.openSettings", {});
18+
19+ expect(result).toEqual({
20+ url: "http://executor.test/base/plugins/desktop-settings/",
21+ flow: "Open this URL in Executor Desktop. The user can change port/auth or regenerate the password there; then rerun discovery/list tools to observe the restarted server.",
22+ });
23+
24+ yield* executor.close();
25+ yield* Effect.promise(() => config.testDb.close());
26+ }),
27+ );
28+});
packages/plugins/desktop-settings/src/server.ts+48−5
@@ -3,15 +3,58 @@ · 2 unmodified lines
33 *
44 * Zero-server-state plugin. The Desktop Settings panel reads and writes
55 * its configuration via Electron IPC (`window.executor.*`), not through
6− * the executor server. This file exists so the host can register the
7− * plugin's `packageName` and the vite plugin can find the `./client`
8− * bundle — that's the entire server contribution.
6+ * the executor server. The server contribution exposes an agent-facing
7+ * browser handoff tool so a chat flow can still route the user to the
8+ * Desktop-only settings UI without moving the Basic-auth password
9+ * through the model context.
910 */
1011
11−import { definePlugin } from "@executor-js/sdk/core";
12+import { Effect, Schema } from "effect";
1213
13−export const desktopSettingsPlugin = definePlugin(() => ({
14+import { definePlugin, tool, type StaticToolSchema } from "@executor-js/sdk/core";
15+
16+export interface DesktopSettingsPluginOptions {
17+ readonly webBaseUrl?: string;
18+}
19+
20+const schemaToStaticToolSchema = <A, I>(schema: Schema.Decoder<A, I>): StaticToolSchema<A, I> =>
21+ Schema.toStandardSchemaV1(Schema.toStandardJSONSchemaV1(schema) as never) as StaticToolSchema<
22+ A,
23+ I
24+ >;
25+
26+const DesktopSettingsOpenOutput = Schema.Struct({
27+ url: Schema.String,
28+ flow: Schema.String,
29+});
30+
31+const DesktopSettingsOpenOutputStd = schemaToStaticToolSchema(DesktopSettingsOpenOutput);
32+
33+const resolveWebBaseUrl = (configured: string | undefined): string =>
34+ (configured ?? "http://localhost:4788").replace(/\/$/, "");
35+
36+export const desktopSettingsPlugin = definePlugin((options: DesktopSettingsPluginOptions = {}) => ({
1437 id: "desktop-settings" as const,
1538 packageName: "@executor-js/plugin-desktop-settings",
1639 storage: () => ({}),
40+ staticSources: () => [
41+ {
42+ id: "desktopSettings",
43+ kind: "executor",
44+ name: "Desktop Settings",
45+ tools: [
46+ tool({
47+ name: "openSettings",
48+ description:
49+ "Return the Desktop Settings browser URL for configuring the local sidecar port, Basic-auth requirement, and generated password. This flow must stay in the Desktop UI because password display/regeneration and server restart are Electron IPC operations; never ask the user to paste the password in chat.",
50+ outputSchema: DesktopSettingsOpenOutputStd,
51+ execute: () =>
52+ Effect.succeed({
53+ url: `${resolveWebBaseUrl(options.webBaseUrl)}/plugins/desktop-settings/`,
54+ flow: "Open this URL in Executor Desktop. The user can change port/auth or regenerate the password there; then rerun discovery/list tools to observe the restarted server.",
55+ }),
56+ }),
57+ ],
58+ },
59+ ],
1760 }));
packages/plugins/desktop-settings/vitest.config.ts+7−0
@@ -0,0 +1,7 @@
1+import { defineConfig } from "vitest/config";
2+
3+export default defineConfig({
4+ test: {
5+ include: ["src/**/*.test.ts"],
6+ },
7+});
packages/plugins/google-discovery/src/sdk/plugin.test.ts+18−0
@@ -425,6 +425,24 @@ describe("Google Discovery plugin", () => { · 424 unmodified lines
425425 });
426426
427427 expect(result.toolCount).toBe(2);
428+ expect((yield* executor.tools.list()).map((tool) => tool.id)).toEqual(
429+ expect.arrayContaining([
430+ "executor.googleDiscovery.probeDiscovery",
431+ "executor.googleDiscovery.addSource",
432+ "executor.googleDiscovery.getSource",
433+ "executor.googleDiscovery.configureSource",
434+ ]),
435+ );
436+
437+ const inspected = yield* executor.tools.invoke(
438+ "executor.googleDiscovery.getSource",
439+ { namespace: "drive", scope: "test-scope" },
440+ autoApprove,
441+ );
442+ expect(inspected).toMatchObject({
443+ ok: true,
444+ data: { source: { namespace: "drive", scope: "test-scope" } },
445+ });
428446
429447 const invocation = (yield* executor.tools.invoke(
430448 "drive.files.get",
packages/plugins/google-discovery/src/sdk/plugin.ts+216−20
@@ -5,9 +5,12 @@ import { · 4 unmodified lines
55 SourceDetectionResult,
66 ToolResult,
77 Usage,
8+ defaultSourceInstallScopeId,
89 definePlugin,
10+ tool,
911 resolveSecretBackedMap,
1012 type PluginCtx,
13+ type StaticToolSchema,
1114 type StorageFailure,
1215 type ToolAnnotations,
1316 } from "@executor-js/sdk/core";
@@ -17,18 +20,19 @@ import { · 3 unmodified lines
1720 makeGoogleDiscoveryStore,
1821 type GoogleDiscoveryStore,
1922 } from "./binding-store";
23+import { googleDiscoveryPresets } from "./presets";
2024 import { extractGoogleDiscoveryManifest } from "./document";
2125 import { annotationsForOperation, invokeGoogleDiscoveryTool } from "./invoke";
2226 import { GoogleDiscoveryParseError, GoogleDiscoverySourceError } from "./errors";
23−import type {
27+import {
2428 GoogleDiscoveryAuth,
2529 GoogleDiscoveryFetchCredentials,
26− GoogleDiscoveryManifest,
27− GoogleDiscoveryManifestMethod,
28− GoogleDiscoveryMethodBinding,
29− GoogleDiscoveryStoredSourceData,
30+ GoogleDiscoveryStoredSourceData as GoogleDiscoveryStoredSourceDataSchema,
31+ type GoogleDiscoveryManifest,
32+ type GoogleDiscoveryManifestMethod,
33+ type GoogleDiscoveryMethodBinding,
3034 } from "./types";
31−import { GoogleDiscoveryStoredSourceData as GoogleDiscoveryStoredSourceDataSchema } from "./types";
35+import type { GoogleDiscoveryStoredSourceData } from "./types";
3236
3337 // ---------------------------------------------------------------------------
3438 // Upstream-error message extraction
@@ -114,20 +118,6 @@ export interface GoogleDiscoveryProbeResult { · 79 unmodified lines
114118 readonly operations: readonly GoogleDiscoveryProbeOperation[];
115119 }
116120
117−export interface GoogleDiscoveryProbeInput {
118− readonly discoveryUrl: string;
119− readonly credentials?: GoogleDiscoveryFetchCredentials;
120−}
121−
122−export interface GoogleDiscoveryAddSourceInput {
123− readonly name: string;
124− readonly scope: string;
125− readonly discoveryUrl: string;
126− readonly credentials?: GoogleDiscoveryFetchCredentials;
127− readonly namespace?: string;
128− readonly auth: GoogleDiscoveryAuth;
129−}
130−
131121 export interface GoogleDiscoveryUpdateSourceInput {
132122 readonly name?: string;
133123 /** Rewrite the source's auth — typically after a successful
@@ -135,6 +125,118 @@ export interface GoogleDiscoveryUpdateSourceInput { · 1 unmodified line
135125 readonly auth?: GoogleDiscoveryAuth;
136126 }
137127
128+const GoogleDiscoveryProbeInputSchema = Schema.Struct({
129+ discoveryUrl: Schema.String,
130+ credentials: Schema.optional(GoogleDiscoveryFetchCredentials),
131+});
132+
133+const GoogleDiscoveryProbeOutputSchema = Schema.Struct({
134+ name: Schema.String,
135+ title: Schema.NullOr(Schema.String),
136+ service: Schema.String,
137+ version: Schema.String,
138+ toolCount: Schema.Number,
139+ scopes: Schema.Array(Schema.String),
140+ operations: Schema.Array(
141+ Schema.Struct({
142+ toolPath: Schema.String,
143+ method: Schema.String,
144+ pathTemplate: Schema.String,
145+ description: Schema.NullOr(Schema.String),
146+ }),
147+ ),
148+});
149+
150+const GoogleDiscoveryAddSourceInputSchema = Schema.Struct({
151+ name: Schema.String,
152+ scope: Schema.String,
153+ discoveryUrl: Schema.String,
154+ credentials: Schema.optional(GoogleDiscoveryFetchCredentials),
155+ namespace: Schema.optional(Schema.String),
156+ auth: GoogleDiscoveryAuth,
157+});
158+const GoogleDiscoveryStaticAddSourceInputSchema = Schema.Struct({
159+ name: Schema.String,
160+ discoveryUrl: Schema.String,
161+ credentials: Schema.optional(GoogleDiscoveryFetchCredentials),
162+ namespace: Schema.optional(Schema.String),
163+ auth: GoogleDiscoveryAuth,
164+});
165+export type GoogleDiscoveryProbeInput = typeof GoogleDiscoveryProbeInputSchema.Type;
166+export type GoogleDiscoveryAddSourceInput = typeof GoogleDiscoveryAddSourceInputSchema.Type;
167+
168+const GoogleDiscoveryAddSourceOutputSchema = Schema.Struct({
169+ namespace: Schema.String,
170+ source: Schema.Struct({
171+ id: Schema.String,
172+ scope: Schema.String,
173+ }),
174+ toolCount: Schema.Number,
175+});
176+
177+const GoogleDiscoveryGetSourceInputSchema = Schema.Struct({
178+ namespace: Schema.String,
179+ scope: Schema.String,
180+});
181+
182+const GoogleDiscoveryGetSourceOutputSchema = Schema.Struct({
183+ source: Schema.NullOr(Schema.Unknown),
184+});
185+
186+const GoogleDiscoveryConfigureInputSchema = Schema.Struct({
187+ name: Schema.optional(Schema.String),
188+ auth: Schema.optional(GoogleDiscoveryAuth),
189+});
190+const GoogleDiscoveryConfigureSourceInputSchema = Schema.Struct({
191+ source: Schema.Struct({
192+ id: Schema.String,
193+ scope: Schema.String,
194+ }),
195+ ...GoogleDiscoveryConfigureInputSchema.fields,
196+});
197+const GoogleDiscoveryConfigureSourceOutputSchema = Schema.Struct({
198+ configured: Schema.Boolean,
199+});
200+
201+const schemaToStaticToolSchema = <A, I>(schema: Schema.Decoder<A, I>): StaticToolSchema<A, I> =>
202+ Schema.toStandardSchemaV1(Schema.toStandardJSONSchemaV1(schema) as never) as StaticToolSchema<
203+ A,
204+ I
205+ >;
206+
207+const GoogleDiscoveryProbeInputStandardSchema = schemaToStaticToolSchema(
208+ GoogleDiscoveryProbeInputSchema,
209+);
210+const GoogleDiscoveryProbeOutputStandardSchema = schemaToStaticToolSchema(
211+ GoogleDiscoveryProbeOutputSchema,
212+);
213+const GoogleDiscoveryAddSourceInputStandardSchema = schemaToStaticToolSchema(
214+ GoogleDiscoveryStaticAddSourceInputSchema,
215+);
216+const GoogleDiscoveryAddSourceOutputStandardSchema = schemaToStaticToolSchema(
217+ GoogleDiscoveryAddSourceOutputSchema,
218+);
219+const GoogleDiscoveryGetSourceInputStandardSchema = schemaToStaticToolSchema(
220+ GoogleDiscoveryGetSourceInputSchema,
221+);
222+const GoogleDiscoveryGetSourceOutputStandardSchema = schemaToStaticToolSchema(
223+ GoogleDiscoveryGetSourceOutputSchema,
224+);
225+const GoogleDiscoveryConfigureSourceInputStandardSchema = schemaToStaticToolSchema(
226+ GoogleDiscoveryConfigureSourceInputSchema,
227+);
228+const GoogleDiscoveryConfigureSourceOutputStandardSchema = schemaToStaticToolSchema(
229+ GoogleDiscoveryConfigureSourceOutputSchema,
230+);
231+
232+const resolveStaticScopeInput = (
233+ ctx: { readonly scopes: readonly { readonly id: ScopeId; readonly name: string }[] },
234+ value: string,
235+): string =>
236+ String(
237+ ctx.scopes.find((scope) => scope.name === value || String(scope.id) === value)?.id ?? value,
238+ );
239+
138240 /**
139241 * Errors any Google Discovery extension method may surface.
140242 */
@@ -439,11 +541,105 @@ export type GoogleDiscoveryPluginExtension = ReturnType<typeof makeGoogleDiscove · 298 unmodified lines
439541 export const googleDiscoveryPlugin = definePlugin(() => ({
440542 id: "googleDiscovery" as const,
441543 packageName: "@executor-js/plugin-google-discovery",
544+ sourcePresets: googleDiscoveryPresets,
442545 schema: googleDiscoverySchema,
443546 storage: (deps) => makeGoogleDiscoveryStore(deps),
444547
445548 extension: makeGoogleDiscoveryPluginExtension,
446549
550+ staticSources: (self) => [
551+ {
552+ id: "googleDiscovery",
553+ kind: "executor",
554+ name: "Google Discovery",
555+ tools: [
556+ tool({
557+ name: "probeDiscovery",
558+ description:
559+ "Preview a Google Discovery document before adding it as a source. Use this to inspect available operations and OAuth scopes. Do not collect Google OAuth client secrets in chat; create them with `executor.coreTools.secrets.create`, then start sign-in with `executor.coreTools.oauth.start`.",
560+ inputSchema: GoogleDiscoveryProbeInputStandardSchema,
561+ outputSchema: GoogleDiscoveryProbeOutputStandardSchema,
562+ execute: (input) => Effect.map(self.probeDiscovery(input), ToolResult.ok),
563+ }),
564+ tool({
565+ name: "addSource",
566+ description:
567+ 'Add a Google Discovery source and register its operations as tools. Executor chooses the source install scope (local scope locally, organization scope in cloud) and returns it as `source`. Recommended flow: call `probeDiscovery`, create any OAuth client id/client secret values through `secrets.create` at the user\'s chosen credential scope, call `oauth.start` with `credentialScope` set to the user\'s chosen personal or organization credential scope for OAuth sources, then pass `{kind:"oauth2", connectionId, clientIdSecretId, clientSecretSecretId, scopes}` or `{kind:"none"}` here.',
568+ annotations: {
569+ requiresApproval: true,
570+ approvalDescription: "Add a Google Discovery source",
571+ },
572+ inputSchema: GoogleDiscoveryAddSourceInputStandardSchema,
573+ outputSchema: GoogleDiscoveryAddSourceOutputStandardSchema,
574+ execute: (input, { ctx }) => {
575+ const args = input as typeof GoogleDiscoveryStaticAddSourceInputSchema.Type;
576+ const sourceScope = defaultSourceInstallScopeId(ctx.scopes);
577+ if (sourceScope === null) {
578+ return Effect.succeed(
579+ ToolResult.fail({
580+ code: "source_scope_unavailable",
581+ message:
582+ "Cannot add a Google Discovery source because this executor has no source install scope.",
583+ }),
584+ );
585+ }
586+ return Effect.map(self.addSource({ ...args, scope: sourceScope }), (result) =>
587+ ToolResult.ok({
588+ ...result,
589+ source: { id: result.namespace, scope: sourceScope },
590+ }),
591+ );
592+ },
593+ }),
594+ tool({
595+ name: "getSource",
596+ description:
597+ "Inspect an existing Google Discovery source, including discovery URL, service metadata, auth mode, OAuth scopes, connection id, and credential slots. Use this before repairing an existing source with `googleDiscovery.configureSource`, `secrets.create`, or `oauth.start`.",
598+ inputSchema: GoogleDiscoveryGetSourceInputStandardSchema,
599+ outputSchema: GoogleDiscoveryGetSourceOutputStandardSchema,
600+ execute: (input, { ctx }) => {
601+ const args = input as typeof GoogleDiscoveryGetSourceInputSchema.Type;
602+ return Effect.map(
603+ self.getSource(args.namespace, resolveStaticScopeInput(ctx, args.scope)),
604+ (source) => ToolResult.ok({ source }),
605+ );
606+ },
607+ }),
608+ tool({
609+ name: "configureSource",
610+ description:
611+ "Configure an existing Google Discovery source with concrete fields. Use `source` returned by `googleDiscovery.addSource` or `sources.list`. For OAuth, call `oauth.start` with the target `credentialScope` first, then pass the returned connection id and client secret ids through `auth`.",
612+ annotations: {
613+ requiresApproval: true,
614+ approvalDescription: "Configure a Google Discovery source",
615+ },
616+ inputSchema: GoogleDiscoveryConfigureSourceInputStandardSchema,
617+ outputSchema: GoogleDiscoveryConfigureSourceOutputStandardSchema,
618+ execute: (input, { ctx }) => {
619+ const { source, ...config } =
620+ input as typeof GoogleDiscoveryConfigureSourceInputSchema.Type;
621+ const sourceScope = resolveStaticScopeInput(ctx, source.scope);
622+ return Effect.as(
623+ self.updateSource(source.id, sourceScope, config),
624+ ToolResult.ok({ configured: true }),
625+ );
626+ },
627+ }),
628+ ],
629+ },
630+ ],
631+
632+ sourceConfigure: {
633+ type: "googleDiscovery",
634+ schema: GoogleDiscoveryConfigureInputSchema,
635+ configure: ({ ctx, sourceId, sourceScope, config }) =>
636+ makeGoogleDiscoveryPluginExtension(ctx as PluginCtx<GoogleDiscoveryStore>).updateSource(
637+ sourceId,
638+ sourceScope,
639+ config as typeof GoogleDiscoveryConfigureInputSchema.Type,
640+ ),
641+ },
642+
447643 invokeTool: ({ ctx, toolRow, args }) =>
448644 Effect.gen(function* () {
449645 const result = yield* invokeGoogleDiscoveryTool({
packages/plugins/graphql/src/sdk/plugin.test.ts+50−4
@@ -630,7 +630,9 @@ describe("graphqlPlugin", () => { · 629 unmodified lines
630630 expect(ids).toContain("test_api.query.hello");
631631 expect(ids).toContain("test_api.mutation.setGreeting");
632632 // static executor tool also present under the executor namespace
633+ expect(ids).toContain("executor.graphql.getSource");
633634 expect(ids).toContain("executor.graphql.addSource");
635+ expect(ids).toContain("executor.graphql.configureSource");
634636
635637 const queryTool = tools.find((t) => t.id === "test_api.query.hello");
636638 expect(queryTool?.description).toBe("Say hello");
@@ -770,7 +772,6 @@ describe("graphqlPlugin", () => { · 133 unmodified lines
770772 const result = yield* executor.tools.invoke(
771773 "executor.graphql.addSource",
772774 {
773− scope: String(orgScope),
774775 endpoint: "http://localhost:4000/graphql",
775776 name: "Via Static",
776777 introspectionJson,
@@ -778,17 +779,60 @@ describe("graphqlPlugin", () => { · 1 unmodified line
778779 },
779780 { onElicitation: "accept-all" },
780781 );
781− expect(result).toEqual({ ok: true, data: { toolCount: 2, namespace: "via_static" } });
782+ expect(result).toEqual({
783+ ok: true,
784+ data: {
785+ namespace: "via_static",
786+ source: { id: "via_static", scope: String(orgScope) },
787+ toolCount: 2,
788+ },
789+ });
782790 expect(yield* executor.graphql.getSource("via_static", String(userScope))).toBeNull();
783791 expect((yield* executor.graphql.getSource("via_static", String(orgScope)))?.scope).toBe(
784792 orgScope,
785793 );
794+ const inspected = yield* executor.tools.invoke(
795+ "executor.graphql.getSource",
796+ { namespace: "via_static", scope: "org" },
797+ { onElicitation: "accept-all" },
798+ );
799+ expect(inspected).toMatchObject({
800+ ok: true,
801+ data: { source: { namespace: "via_static", scope: String(orgScope) } },
802+ });
786803
787804 const tools = yield* executor.tools.list();
788805 expect(tools.filter((t) => t.sourceId === "via_static").length).toBe(2);
789806 }),
790807 );
791808
809+ it.effect("static executor.graphql.addSource returns actionable tool failures", () =>
810+ Effect.gen(function* () {
811+ const config = makeTestConfig({ plugins: [graphqlPlugin()] as const });
812+ const executor = yield* createExecutor(config);
813+
814+ const result = yield* executor.tools.invoke(
815+ "executor.graphql.addSource",
816+ {
817+ endpoint: "http://127.0.0.1:1/graphql",
818+ name: "Broken GraphQL",
819+ namespace: "broken_graphql",
820+ },
821+ { onElicitation: "accept-all" },
822+ );
823+
824+ expect(result).toMatchObject({
825+ ok: false,
826+ error: {
827+ code: "graphql_introspection_failed",
828+ },
829+ });
830+
831+ yield* executor.close();
832+ yield* Effect.promise(() => config.testDb.close());
833+ }),
834+ );
835+
792836 it.effect("describes static addSource parameters from Standard Schema", () =>
793837 Effect.gen(function* () {
794838 const executor = yield* createExecutor(makeTestConfig({ plugins: [graphqlPlugin()] }));
@@ -796,8 +840,11 @@ describe("graphqlPlugin", () => { · 1 unmodified line
796840 const schema = yield* executor.tools.schema("executor.graphql.addSource");
797841
798842 expect(schema).not.toBeNull();
799− expect(schema!.inputTypeScript).toContain("scope: string");
800843 expect(schema!.inputTypeScript).toContain("endpoint: string");
844+ expect(schema!.inputTypeScript).toContain("credentials?: { scope: string");
845+ expect(
846+ (schema!.inputSchema as { properties?: Record<string, unknown> }).properties,
847+ ).not.toHaveProperty("scope");
801848 expect(
802849 (schema!.inputSchema as { properties?: Record<string, unknown> }).properties,
803850 ).not.toHaveProperty("targetScope");
@@ -823,7 +870,6 @@ describe("graphqlPlugin", () => { · 19 unmodified lines
823870 "executor.graphql.addSource",
824871 {
825872 endpoint: server.endpoint,
826− scope: TEST_SCOPE,
827873 introspectionJson,
828874 namespace: "runtime_graphql",
829875 },
packages/plugins/graphql/src/sdk/plugin.ts+120−4
@@ -7,6 +7,7 @@ import { · 6 unmodified lines
77 type CredentialBindingValue,
88 definePlugin,
99 tool,
10+ defaultSourceInstallScopeId,
1011 ScopeId,
1112 SourceDetectionResult,
1213 StorageError,
@@ -40,6 +41,7 @@ import { · 27 unmodified lines
4041 import { extract } from "./extract";
4142 import { GraphqlIntrospectionError, GraphqlInvocationError } from "./errors";
4243 import { invokeWithLayer } from "./invoke";
44+import { graphqlPresets } from "./presets";
4345 import {
4446 graphqlSchema,
4547 makeDefaultGraphqlStore,
@@ -120,7 +122,6 @@ const GraphqlInitialCredentialsInputSchema = Schema.Struct({ · 74 unmodified lines
120122 type GraphqlInitialCredentialsInput = typeof GraphqlInitialCredentialsInputSchema.Type;
121123
122124 const StaticAddSourceInputSchema = Schema.Struct({
123− scope: Schema.String,
124125 endpoint: Schema.String,
125126 name: Schema.String,
126127 introspectionJson: Schema.optional(Schema.String),
@@ -137,13 +138,67 @@ const SourceConfigureInputSchema = Schema.Struct({ · 10 unmodified lines
137138 queryParams: Schema.optional(Schema.Record(Schema.String, GraphqlCredentialInputSchema)),
138139 auth: Schema.optional(GraphqlSourceAuthInputSchema),
139140 });
141+const StaticConfigureSourceInputSchema = Schema.Struct({
142+ source: Schema.Struct({
143+ id: Schema.String,
144+ scope: Schema.String,
145+ }),
146+ scope: Schema.String,
147+ ...SourceConfigureInputSchema.fields,
148+});
149+const StaticConfigureSourceOutputSchema = Schema.Struct({
150+ configured: Schema.Boolean,
151+});
152+const StaticGetSourceInputSchema = Schema.Struct({
153+ namespace: Schema.String,
154+ scope: Schema.String,
155+});
156+const StaticGetSourceOutputSchema = Schema.Struct({
157+ source: Schema.NullOr(Schema.Unknown),
158+});
140159
141160 const StaticAddSourceInputStandardSchema = Schema.toStandardSchemaV1(
142161 Schema.toStandardJSONSchemaV1(StaticAddSourceInputSchema),
143162 );
144163 const StaticAddSourceOutputStandardSchema = Schema.toStandardSchemaV1(
145− Schema.toStandardJSONSchemaV1(Schema.Struct({ toolCount: Schema.Number })),
164+ Schema.toStandardJSONSchemaV1(
165+ Schema.Struct({
166+ namespace: Schema.String,
167+ source: Schema.Struct({
168+ id: Schema.String,
169+ scope: Schema.String,
170+ }),
171+ toolCount: Schema.Number,
172+ }),
173+ ),
174+);
175+const StaticGetSourceInputStandardSchema = Schema.toStandardSchemaV1(
176+ Schema.toStandardJSONSchemaV1(StaticGetSourceInputSchema),
177+);
178+const StaticGetSourceOutputStandardSchema = Schema.toStandardSchemaV1(
179+ Schema.toStandardJSONSchemaV1(StaticGetSourceOutputSchema),
146180 );
181+const StaticConfigureSourceInputStandardSchema = Schema.toStandardSchemaV1(
182+ Schema.toStandardJSONSchemaV1(StaticConfigureSourceInputSchema),
183+);
184+const StaticConfigureSourceOutputStandardSchema = Schema.toStandardSchemaV1(
185+ Schema.toStandardJSONSchemaV1(StaticConfigureSourceOutputSchema),
186+);
187+
188+const graphqlToolFailure = (code: string, message: string, details?: unknown) =>
189+ ToolResult.fail({
190+ code,
191+ message,
192+ ...(details === undefined ? {} : { details }),
193+ });
194+
195+const resolveStaticScopeInput = (
196+ ctx: { readonly scopes: readonly { readonly id: ScopeId; readonly name: string }[] },
197+ value: string,
198+): string =>
199+ String(
200+ ctx.scopes.find((scope) => scope.name === value || String(scope.id) === value)?.id ?? value,
201+ );
147202
148203 // ---------------------------------------------------------------------------
149204 // Plugin extension
@@ -890,6 +945,7 @@ export const graphqlPlugin = definePlugin((options?: GraphqlPluginOptions) => { · 740 unmodified lines
890945 return {
891946 id: "graphql" as const,
892947 packageName: "@executor-js/plugin-graphql",
948+ sourcePresets: graphqlPresets,
893949 schema: graphqlSchema,
894950 storage: (deps): GraphqlStore => makeDefaultGraphqlStore(deps),
895951
@@ -922,16 +978,76 @@ export const graphqlPlugin = definePlugin((options?: GraphqlPluginOptions) => { · 26 unmodified lines
922978 kind: "executor",
923979 name: "GraphQL",
924980 tools: [
981+ tool({
982+ name: "getSource",
983+ description:
984+ "Inspect an existing GraphQL source, including endpoint, auth mode, configured headers/query params, and credential slots. Use this before repairing an existing source with `graphql.configureSource`, `secrets.create`, or `oauth.start`.",
985+ inputSchema: StaticGetSourceInputStandardSchema,
986+ outputSchema: StaticGetSourceOutputStandardSchema,
987+ execute: (input, { ctx }) =>
988+ Effect.map(
989+ self.getSource(input.namespace, resolveStaticScopeInput(ctx, input.scope)),
990+ (source) => ToolResult.ok({ source }),
991+ ),
992+ }),
925993 tool({
926994 name: "addSource",
927− description: "Add a GraphQL endpoint and register its operations as tools",
995+ description:
996+ "Add a GraphQL endpoint and register its operations as tools. Executor chooses the source install scope (local scope locally, organization scope in cloud) and returns it as `source`. For API keys or bearer tokens, first call `executor.coreTools.secrets.create` at the user's chosen credential scope and pass secret refs through `credentials`. For OAuth, start the browser flow with `executor.coreTools.oauth.start` using `credentialScope` set to the user's chosen personal or organization credential scope, verify completion with `connections.list`, then bind the connection through `credentials` or `graphql.configureSource`.",
928997 annotations: {
929998 requiresApproval: true,
930999 approvalDescription: "Add a GraphQL source",
9311000 },
9321001 inputSchema: StaticAddSourceInputStandardSchema,
9331002 outputSchema: StaticAddSourceOutputStandardSchema,
934− execute: (input) => Effect.map(self.addSource(input), ToolResult.ok),
1003+ execute: (input, { ctx }) => {
1004+ const sourceScope = defaultSourceInstallScopeId(ctx.scopes);
1005+ if (sourceScope === null) {
1006+ return Effect.succeed(
1007+ graphqlToolFailure(
1008+ "source_scope_unavailable",
1009+ "Cannot add a GraphQL source because this executor has no source install scope.",
1010+ ),
1011+ );
1012+ }
1013+ return self.addSource({ ...input, scope: sourceScope }).pipe(
1014+ Effect.map((result) =>
1015+ ToolResult.ok({
1016+ ...result,
1017+ source: { id: result.namespace, scope: sourceScope },
1018+ }),
1019+ ),
1020+ Effect.catchTags({
1021+ GraphqlIntrospectionError: ({ message }) =>
1022+ Effect.succeed(graphqlToolFailure("graphql_introspection_failed", message)),
1023+ GraphqlExtractionError: ({ message }) =>
1024+ Effect.succeed(graphqlToolFailure("graphql_extraction_failed", message)),
1025+ }),
1026+ );
1027+ },
1028+ }),
1029+ tool({
1030+ name: "configureSource",
1031+ description:
1032+ 'Configure an existing GraphQL source with concrete fields. Use `source` returned by `graphql.addSource` or `sources.list`. The top-level `scope` is the credential target scope for bindings; in cloud, choose the user or organization credential scope deliberately. Pass secret refs as `{kind:"secret", secretId}` and OAuth connections as `{kind:"connection", connectionId}`.',
1033+ annotations: {
1034+ requiresApproval: true,
1035+ approvalDescription: "Configure a GraphQL source",
1036+ },
1037+ inputSchema: StaticConfigureSourceInputStandardSchema,
1038+ outputSchema: StaticConfigureSourceOutputStandardSchema,
1039+ execute: (input, { ctx }) => {
1040+ const { source, ...config } = input as typeof StaticConfigureSourceInputSchema.Type;
1041+ const sourceScope = resolveStaticScopeInput(ctx, source.scope);
1042+ const targetScope = resolveStaticScopeInput(ctx, config.scope);
1043+ return Effect.as(
1044+ self.configure(
1045+ { id: source.id, scope: sourceScope },
1046+ { ...config, scope: targetScope },
1047+ ),
1048+ ToolResult.ok({ configured: true }),
1049+ );
1050+ },
9351051 }),
9361052 ],
9371053 },
packages/plugins/graphql/src/sdk/presets.ts+6−0
@@ -3,6 +3,7 @@ export interface GraphqlPreset { · 2 unmodified lines
33 readonly name: string;
44 readonly summary: string;
55 readonly url: string;
6+ readonly endpoint: string;
67 readonly icon?: string;
78 readonly featured?: boolean;
89 }
@@ -13,6 +14,7 @@ export const graphqlPresets: readonly GraphqlPreset[] = [ · 4 unmodified lines
1314 name: "GitHub GraphQL",
1415 summary: "Repos, issues, PRs, and users via GitHub's GraphQL API.",
1516 url: "https://api.github.com/graphql",
17+ endpoint: "https://api.github.com/graphql",
1618 icon: "https://github.com/favicon.ico",
1719 featured: true,
1820 },
@@ -21,6 +23,7 @@ export const graphqlPresets: readonly GraphqlPreset[] = [ · 2 unmodified lines
2123 name: "GitLab",
2224 summary: "Projects, merge requests, pipelines, and users.",
2325 url: "https://gitlab.com/api/graphql",
26+ endpoint: "https://gitlab.com/api/graphql",
2427 icon: "https://gitlab.com/favicon.ico",
2528 featured: true,
2629 },
@@ -29,6 +32,7 @@ export const graphqlPresets: readonly GraphqlPreset[] = [ · 2 unmodified lines
2932 name: "Linear",
3033 summary: "Issues, projects, teams, and cycles.",
3134 url: "https://api.linear.app/graphql",
35+ endpoint: "https://api.linear.app/graphql",
3236 icon: "https://linear.app/favicon.ico",
3337 featured: true,
3438 },
@@ -37,6 +41,7 @@ export const graphqlPresets: readonly GraphqlPreset[] = [ · 2 unmodified lines
3741 name: "Monday.com",
3842 summary: "Boards, items, columns, and workspace automation.",
3943 url: "https://api.monday.com/v2",
44+ endpoint: "https://api.monday.com/v2",
4045 icon: "https://monday.com/favicon.ico",
4146 },
4247 {
@@ -44,6 +49,7 @@ export const graphqlPresets: readonly GraphqlPreset[] = [ · 1 unmodified line
4449 name: "AniList",
4550 summary: "Anime and manga database — no auth required.",
4651 url: "https://graphql.anilist.co",
52+ endpoint: "https://graphql.anilist.co",
4753 icon: "https://anilist.co/img/icons/favicon-32x32.png",
4854 },
4955 ];
packages/plugins/mcp/src/sdk/plugin.test.ts+71−4
@@ -215,24 +215,28 @@ describe("mcpPlugin", () => { · 214 unmodified lines
215215 expect(executor.mcp.removeSource).toBeTypeOf("function");
216216 expect(executor.mcp.refreshSource).toBeTypeOf("function");
217217 expect(executor.mcp.probeEndpoint).toBeTypeOf("function");
218+ expect(executor.mcp.getSource).toBeTypeOf("function");
219+ expect((yield* executor.tools.list()).map((tool) => tool.id)).toContain(
220+ "executor.mcp.configureSource",
221+ );
218222 expect(executor.oauth.start).toBeTypeOf("function");
219223 expect(executor.oauth.complete).toBeTypeOf("function");
220224 }),
221225 );
222226
223− it.effect("sources list is initially empty", () =>
227+ it.effect("sources list has no configured MCP sources initially", () =>
224228 Effect.gen(function* () {
225229 const executor = yield* createExecutor(makeTestConfig({ plugins: [mcpPlugin()] as const }));
226230 const sources = yield* executor.sources.list();
227− expect(sources).toHaveLength(0);
231+ expect(sources.filter((source) => !source.runtime)).toHaveLength(0);
228232 }),
229233 );
230234
231− it.effect("tools list is initially empty", () =>
235+ it.effect("tools list has no configured MCP source tools initially", () =>
232236 Effect.gen(function* () {
233237 const executor = yield* createExecutor(makeTestConfig({ plugins: [mcpPlugin()] as const }));
234238 const tools = yield* executor.tools.list();
235− expect(tools).toHaveLength(0);
239+ expect(tools.filter((tool) => !tool.id.startsWith("executor.mcp."))).toHaveLength(0);
236240 }),
237241 );
238242
@@ -268,6 +272,69 @@ describe("mcpPlugin", () => { · 29 unmodified lines
268272
269273 const tools = yield* executor.tools.list();
270274 expect(tools.filter((t) => t.sourceId === "broken_source")).toHaveLength(0);
275+ const inspected = yield* executor.tools.invoke(
276+ "executor.mcp.getSource",
277+ { namespace: "broken_source", scope: "test-scope" },
278+ { onElicitation: "accept-all" },
279+ );
280+ expect(inspected).toMatchObject({
281+ ok: true,
282+ data: { source: { namespace: "broken_source", scope: "test-scope" } },
283+ });
284+ }),
285+ );
286+
287+ it.effect("static addSource reports saved remote source when discovery fails", () =>
288+ Effect.gen(function* () {
289+ const executor = yield* createExecutor(makeTestConfig({ plugins: [mcpPlugin()] as const }));
290+
291+ const result = yield* executor.tools.invoke(
292+ "executor.mcp.addSource",
293+ {
294+ transport: "remote",
295+ name: "broken static",
296+ endpoint: "http://127.0.0.1:1/mcp",
297+ remoteTransport: "auto",
298+ namespace: "broken_static_source",
299+ },
300+ { onElicitation: "accept-all" },
301+ );
302+
303+ expect(result).toMatchObject({
304+ ok: true,
305+ data: {
306+ namespace: "broken_static_source",
307+ source: { id: "broken_static_source", scope: "test-scope" },
308+ toolCount: 0,
309+ discovery: {
310+ status: "failed",
311+ },
312+ },
313+ });
314+
315+ const source = yield* executor.mcp.getSource("broken_static_source", "test-scope");
316+ expect(source?.namespace).toBe("broken_static_source");
317+ }),
318+ );
319+
320+ it.effect("static probeEndpoint returns actionable tool failures", () =>
321+ Effect.gen(function* () {
322+ const config = makeTestConfig({ plugins: [mcpPlugin()] as const });
323+ const executor = yield* createExecutor(config);
324+
325+ const result = yield* executor.tools.invoke("executor.mcp.probeEndpoint", {
326+ endpoint: "http://127.0.0.1:1/mcp",
327+ });
328+
329+ expect(result).toMatchObject({
330+ ok: false,
331+ error: {
332+ code: "mcp_connection_failed",
333+ },
334+ });
335+
336+ yield* executor.close();
337+ yield* Effect.promise(() => config.testDb.close());
271338 }),
272339 );
273340
packages/plugins/mcp/src/sdk/plugin.ts+303−6
@@ -21,9 +21,12 @@ import { · 20 unmodified lines
2121 ScopeId,
2222 SourceDetectionResult,
2323 ToolResult,
24+ defaultSourceInstallScopeId,
2425 definePlugin,
26+ tool,
2527 resolveSecretBackedMap as resolveSharedSecretBackedMap,
2628 type PluginCtx,
29+ type StaticToolSchema,
2730 type StorageFailure,
2831 StorageError,
2932 type ToolAnnotations,
@@ -46,19 +49,22 @@ import { discoverTools } from "./discover"; · 16 unmodified lines
4649 import { McpConnectionError, McpInvocationError, McpToolDiscoveryError } from "./errors";
4750 import { invokeMcpTool } from "./invoke";
4851 import { deriveMcpNamespace, type McpToolManifest, type McpToolManifestEntry } from "./manifest";
52+import { mcpPresets } from "./presets";
4953 import { probeMcpEndpointShape, type McpShapeProbeResult } from "./probe-shape";
5054 import {
5155 MCP_OAUTH_CLIENT_ID_SLOT,
5256 MCP_OAUTH_CLIENT_SECRET_SLOT,
5357 MCP_OAUTH_CONNECTION_SLOT,
5458 McpConnectionAuthInput,
59+ McpConfiguredValueInput,
5560 McpCredentialInput,
61+ McpRemoteTransport,
5662 McpToolBinding,
5763 mcpHeaderSlot,
5864 mcpQueryParamSlot,
5965 type McpConnectionAuth,
6066 type McpConfiguredValueInput as McpConfiguredValueInputType,
61− type SecretBackedValue,
67+ SecretBackedValue,
6268 type McpStoredSourceData,
6369 type ConfiguredMcpCredentialValue,
6470 } from "./types";
@@ -157,11 +163,122 @@ const McpInitialCredentialsInputSchema = Schema.Struct({ · 92 unmodified lines
157163 });
158164 type McpInitialCredentialsInput = typeof McpInitialCredentialsInputSchema.Type;
159165
160−export interface McpProbeEndpointInput {
161− readonly endpoint: string;
162− readonly headers?: Record<string, SecretBackedValue>;
163− readonly queryParams?: Record<string, SecretBackedValue>;
164−}
166+const McpRemoteAddSourceInputSchema = Schema.Struct({
167+ transport: Schema.Literal("remote"),
168+ name: Schema.String,
169+ endpoint: Schema.String,
170+ remoteTransport: Schema.optional(McpRemoteTransport),
171+ queryParams: Schema.optional(Schema.Record(Schema.String, McpConfiguredValueInput)),
172+ headers: Schema.optional(Schema.Record(Schema.String, McpConfiguredValueInput)),
173+ namespace: Schema.optional(Schema.String),
174+ oauth2: Schema.optional(OAuth2SourceConfig),
175+ credentials: Schema.optional(McpInitialCredentialsInputSchema),
176+});
177+
178+const McpStdioAddSourceInputSchema = Schema.Struct({
179+ transport: Schema.Literal("stdio"),
180+ name: Schema.String,
181+ command: Schema.String,
182+ args: Schema.optional(Schema.Array(Schema.String)),
183+ env: Schema.optional(Schema.Record(Schema.String, Schema.String)),
184+ cwd: Schema.optional(Schema.String),
185+ namespace: Schema.optional(Schema.String),
186+});
187+
188+const McpAddSourceInputSchema = Schema.Union([
189+ McpRemoteAddSourceInputSchema,
190+ McpStdioAddSourceInputSchema,
191+]);
192+
193+const McpAddSourceOutputSchema = Schema.Struct({
194+ namespace: Schema.String,
195+ source: Schema.Struct({
196+ id: Schema.String,
197+ scope: Schema.String,
198+ }),
199+ toolCount: Schema.Number,
200+ discovery: Schema.optional(
201+ Schema.Struct({
202+ status: Schema.Literals(["ok", "failed"]),
203+ message: Schema.optional(Schema.String),
204+ stage: Schema.optional(Schema.String),
205+ }),
206+ ),
207+});
208+
209+const McpProbeEndpointInputSchema = Schema.Struct({
210+ endpoint: Schema.String,
211+ headers: Schema.optional(Schema.Record(Schema.String, SecretBackedValue)),
212+ queryParams: Schema.optional(Schema.Record(Schema.String, SecretBackedValue)),
213+});
214+
215+const McpProbeEndpointOutputSchema = Schema.Struct({
216+ connected: Schema.Boolean,
217+ requiresOAuth: Schema.Boolean,
218+ supportsDynamicRegistration: Schema.Boolean,
219+ name: Schema.String,
220+ namespace: Schema.String,
221+ toolCount: Schema.NullOr(Schema.Number),
222+ serverName: Schema.NullOr(Schema.String),
223+});
224+
225+const McpGetSourceInputSchema = Schema.Struct({
226+ namespace: Schema.String,
227+ scope: Schema.String,
228+});
229+
230+const McpGetSourceOutputSchema = Schema.Struct({
231+ source: Schema.NullOr(Schema.Unknown),
232+});
233+
234+const McpStaticConfigureSourceInputSchema = Schema.Struct({
235+ source: Schema.Struct({
236+ id: Schema.String,
237+ scope: Schema.String,
238+ }),
239+ scope: Schema.String,
240+ ...McpConfigureSourcePayloadSchema.fields,
241+});
242+
243+const McpStaticConfigureSourceOutputSchema = Schema.Struct({
244+ configured: Schema.Boolean,
245+});
246+
247+const schemaToStaticToolSchema = <A, I>(schema: Schema.Decoder<A, I>): StaticToolSchema<A, I> =>
248+ Schema.toStandardSchemaV1(Schema.toStandardJSONSchemaV1(schema) as never) as StaticToolSchema<
249+ A,
250+ I
251+ >;
252+
253+const mcpToolFailure = (code: string, message: string, details?: unknown) =>
254+ ToolResult.fail({
255+ code,
256+ message,
257+ ...(details === undefined ? {} : { details }),
258+ });
259+
260+const McpAddSourceInputStandardSchema = schemaToStaticToolSchema(McpAddSourceInputSchema);
261+const McpAddSourceOutputStandardSchema = schemaToStaticToolSchema(McpAddSourceOutputSchema);
262+const McpProbeEndpointInputStandardSchema = schemaToStaticToolSchema(McpProbeEndpointInputSchema);
263+const McpProbeEndpointOutputStandardSchema = schemaToStaticToolSchema(McpProbeEndpointOutputSchema);
264+const McpGetSourceInputStandardSchema = schemaToStaticToolSchema(McpGetSourceInputSchema);
265+const McpGetSourceOutputStandardSchema = schemaToStaticToolSchema(McpGetSourceOutputSchema);
266+const McpStaticConfigureSourceInputStandardSchema = schemaToStaticToolSchema(
267+ McpStaticConfigureSourceInputSchema,
268+);
269+const McpStaticConfigureSourceOutputStandardSchema = schemaToStaticToolSchema(
270+ McpStaticConfigureSourceOutputSchema,
271+);
272+
273+export type McpProbeEndpointInput = typeof McpProbeEndpointInputSchema.Type;
274+
275+const resolveStaticScopeInput = (
276+ ctx: { readonly scopes: readonly { readonly id: ScopeId; readonly name: string }[] },
277+ value: string,
278+): string =>
279+ String(
280+ ctx.scopes.find((scope) => scope.name === value || String(scope.id) === value)?.id ?? value,
281+ );
165282
166283 // ---------------------------------------------------------------------------
167284 // Helpers
@@ -1001,6 +1118,17 @@ export const mcpPlugin = definePlugin((options?: McpPluginOptions) => { · 833 unmodified lines
10011118 return {
10021119 id: "mcp" as const,
10031120 packageName: "@executor-js/plugin-mcp",
1121+ sourcePresets: allowStdio
1122+ ? mcpPresets.map((preset) => ({
1123+ ...preset,
1124+ transport: "transport" in preset ? preset.transport : "remote",
1125+ }))
1126+ : mcpPresets
1127+ .filter((preset) => !("transport" in preset && preset.transport === "stdio"))
1128+ .map((preset) => ({
1129+ ...preset,
1130+ transport: "remote" as const,
1131+ })),
10041132 // Surfaced to the client bundle via the Vite plugin (see
10051133 // `@executor-js/vite-plugin`). The MCP `./client` factory reads
10061134 // `allowStdio` and gates the stdio tab + presets in AddMcpSource —
@@ -1579,6 +1707,175 @@ export const mcpPlugin = definePlugin((options?: McpPluginOptions) => { · 572 unmodified lines
15791707 }),
15801708 },
15811709
1710+ staticSources: (self) => [
1711+ {
1712+ id: "mcp",
1713+ kind: "executor",
1714+ name: "MCP",
1715+ tools: [
1716+ tool({
1717+ name: "probeEndpoint",
1718+ description:
1719+ "Probe a remote MCP endpoint before adding it. If the result requires OAuth, call `executor.coreTools.oauth.probe` and `executor.coreTools.oauth.start` with `credentialScope` set to the user's chosen personal or organization credential scope first, then pass the resulting connection through `addSource` credentials or `mcp.configureSource`.",
1720+ inputSchema: McpProbeEndpointInputStandardSchema,
1721+ outputSchema: McpProbeEndpointOutputStandardSchema,
1722+ execute: (input) =>
1723+ self.probeEndpoint(input).pipe(
1724+ Effect.map(ToolResult.ok),
1725+ Effect.catchTag("McpConnectionError", ({ message, transport }) =>
1726+ Effect.succeed(mcpToolFailure("mcp_connection_failed", message, { transport })),
1727+ ),
1728+ ),
1729+ }),
1730+ tool({
1731+ name: "getSource",
1732+ description:
1733+ "Inspect an existing MCP source, including transport, endpoint/command, auth mode, configured headers/query params, and credential slots. Use this before repairing an existing source with `mcp.configureSource`, `secrets.create`, or `oauth.start`.",
1734+ inputSchema: McpGetSourceInputStandardSchema,
1735+ outputSchema: McpGetSourceOutputStandardSchema,
1736+ execute: (input, { ctx }) => {
1737+ const args = input as typeof McpGetSourceInputSchema.Type;
1738+ return Effect.map(
1739+ self.getSource(args.namespace, resolveStaticScopeInput(ctx, args.scope)),
1740+ (source) => ToolResult.ok({ source }),
1741+ );
1742+ },
1743+ }),
1744+ tool({
1745+ name: "addSource",
1746+ description:
1747+ "Add an MCP source and register its tools. Executor chooses the source install scope (local scope locally, organization scope in cloud) and returns it as `source`. For remote OAuth-protected servers, first use `probeEndpoint` and the core OAuth browser handoff (`oauth.probe`, `oauth.start` with the user's chosen `credentialScope`), then bind the completed connection with `mcp.configureSource` if needed. For header/API-key auth, first call `secrets.create` at the user's chosen credential scope so the value is entered in the browser, then pass the secret reference in `credentials`. Remote sources are still saved if discovery fails; inspect the returned `discovery` field and use `sources.refresh` after credentials or network access are fixed.",
1748+ annotations: {
1749+ requiresApproval: true,
1750+ approvalDescription: "Add an MCP source",
1751+ },
1752+ inputSchema: McpAddSourceInputStandardSchema,
1753+ outputSchema: McpAddSourceOutputStandardSchema,
1754+ execute: (rawInput, { ctx }) => {
1755+ const input = rawInput as typeof McpAddSourceInputSchema.Type;
1756+ const sourceScope = defaultSourceInstallScopeId(ctx.scopes);
1757+ if (sourceScope === null) {
1758+ return Effect.succeed(
1759+ mcpToolFailure(
1760+ "source_scope_unavailable",
1761+ "Cannot add an MCP source because this executor has no source install scope.",
1762+ ),
1763+ );
1764+ }
1765+ const normalizedInput = {
1766+ ...input,
1767+ scope: sourceScope,
1768+ } as McpSourceConfig;
1769+ const added = self.addSource(normalizedInput).pipe(
1770+ Effect.map((result) =>
1771+ ToolResult.ok({
1772+ ...result,
1773+ source: { id: result.namespace, scope: sourceScope },
1774+ discovery: { status: "ok" },
1775+ }),
1776+ ),
1777+ );
1778+ if (normalizedInput.transport !== "remote") return added;
1779+
1780+ const savedWithDiscoveryFailure = (failure: {
1781+ readonly message: string;
1782+ readonly stage?: string;
1783+ }) =>
1784+ Effect.succeed(
1785+ ToolResult.ok({
1786+ namespace:
1787+ normalizedInput.namespace ??
1788+ deriveMcpNamespace({
1789+ name: normalizedInput.name,
1790+ endpoint: normalizedInput.endpoint,
1791+ }),
1792+ source: {
1793+ id:
1794+ normalizedInput.namespace ??
1795+ deriveMcpNamespace({
1796+ name: normalizedInput.name,
1797+ endpoint: normalizedInput.endpoint,
1798+ }),
1799+ scope: sourceScope,
1800+ },
1801+ toolCount: 0,
1802+ discovery: {
1803+ status: "failed" as const,
1804+ message: failure.message,
1805+ ...(failure.stage ? { stage: failure.stage } : {}),
1806+ },
1807+ }),
1808+ );
1809+
1810+ return added.pipe(
1811+ Effect.catchTags({
1812+ McpToolDiscoveryError: savedWithDiscoveryFailure,
1813+ McpConnectionError: ({ message }) =>
1814+ Effect.succeed(
1815+ ToolResult.ok({
1816+ namespace:
1817+ normalizedInput.namespace ??
1818+ deriveMcpNamespace({
1819+ name: normalizedInput.name,
1820+ endpoint: normalizedInput.endpoint,
1821+ }),
1822+ source: {
1823+ id:
1824+ normalizedInput.namespace ??
1825+ deriveMcpNamespace({
1826+ name: normalizedInput.name,
1827+ endpoint: normalizedInput.endpoint,
1828+ }),
1829+ scope: sourceScope,
1830+ },
1831+ toolCount: 0,
1832+ discovery: {
1833+ status: "failed" as const,
1834+ message,
1835+ },
1836+ }),
1837+ ),
1838+ }),
1839+ );
1840+ },
1841+ }),
1842+ tool({
1843+ name: "configureSource",
1844+ description:
1845+ 'Configure an existing remote MCP source with concrete fields. Use `source` returned by `mcp.addSource` or `sources.list`. The top-level `scope` is the credential target scope for bindings; in cloud, choose the user or organization credential scope deliberately. Pass secret refs as `{kind:"secret", secretId}` and OAuth connections as `{kind:"connection", connectionId}`.',
1846+ annotations: {
1847+ requiresApproval: true,
1848+ approvalDescription: "Configure an MCP source",
1849+ },
1850+ inputSchema: McpStaticConfigureSourceInputStandardSchema,
1851+ outputSchema: McpStaticConfigureSourceOutputStandardSchema,
1852+ execute: (rawInput, { ctx }) =>
1853+ Effect.gen(function* () {
1854+ const { source, ...config } =
1855+ rawInput as typeof McpStaticConfigureSourceInputSchema.Type;
1856+ const sourceScope = resolveStaticScopeInput(ctx, source.scope);
1857+ const targetScope = resolveStaticScopeInput(ctx, config.scope);
1858+ yield* ctx.core.sources.configure({
1859+ source: { id: source.id, scope: sourceScope },
1860+ scope: targetScope,
1861+ type: "mcp",
1862+ config: {
1863+ ...(config.name !== undefined ? { name: config.name } : {}),
1864+ ...(config.endpoint !== undefined ? { endpoint: config.endpoint } : {}),
1865+ ...(config.headers !== undefined ? { headers: config.headers } : {}),
1866+ ...(config.queryParams !== undefined
1867+ ? { queryParams: config.queryParams }
1868+ : {}),
1869+ ...(config.auth !== undefined ? { auth: config.auth } : {}),
1870+ },
1871+ });
1872+ return ToolResult.ok({ configured: true });
1873+ }),
1874+ }),
1875+ ],
1876+ },
1877+ ],
1878+
15821879 invokeTool: ({ ctx, toolRow, args, elicit }) =>
15831880 Effect.gen(function* () {
15841881 const runtime = yield* ensureRuntime();
packages/plugins/mcp/src/sdk/presets.ts+12−0
@@ -3,6 +3,7 @@ export interface McpRemotePreset { · 2 unmodified lines
33 readonly name: string;
44 readonly summary: string;
55 readonly url: string;
6+ readonly endpoint: string;
67 readonly icon?: string;
78 readonly featured?: boolean;
89 readonly transport?: undefined;
@@ -28,6 +29,7 @@ export const mcpPresets: readonly McpPreset[] = [ · 19 unmodified lines
2829 name: "DeepWiki",
2930 summary: "Search and read documentation from any GitHub repo.",
3031 url: "https://mcp.deepwiki.com/mcp",
32+ endpoint: "https://mcp.deepwiki.com/mcp",
3133 icon: "https://deepwiki.com/favicon.ico",
3234 featured: true,
3335 },
@@ -36,6 +38,7 @@ export const mcpPresets: readonly McpPreset[] = [ · 2 unmodified lines
3638 name: "Context7",
3739 summary: "Up-to-date docs and code examples for any library.",
3840 url: "https://mcp.context7.com/mcp",
41+ endpoint: "https://mcp.context7.com/mcp",
3942 icon: "https://context7.com/favicon.ico",
4043 featured: true,
4144 },
@@ -44,6 +47,7 @@ export const mcpPresets: readonly McpPreset[] = [ · 2 unmodified lines
4447 name: "Browserbase",
4548 summary: "Cloud browser sessions for web scraping and automation.",
4649 url: "https://mcp.browserbase.com/mcp",
50+ endpoint: "https://mcp.browserbase.com/mcp",
4751 icon: "https://www.browserbase.com/favicon.ico",
4852 featured: true,
4953 },
@@ -52,6 +56,7 @@ export const mcpPresets: readonly McpPreset[] = [ · 2 unmodified lines
5256 name: "Firecrawl",
5357 summary: "Crawl and scrape websites into structured data.",
5458 url: "https://mcp.firecrawl.dev/mcp",
59+ endpoint: "https://mcp.firecrawl.dev/mcp",
5560 icon: "https://www.firecrawl.dev/favicon.ico",
5661 featured: true,
5762 },
@@ -60,6 +65,7 @@ export const mcpPresets: readonly McpPreset[] = [ · 2 unmodified lines
6065 name: "Neon",
6166 summary: "Serverless Postgres — branches, queries, and management.",
6267 url: "https://mcp.neon.tech/mcp",
68+ endpoint: "https://mcp.neon.tech/mcp",
6369 icon: "https://neon.tech/favicon/favicon.ico",
6470 featured: true,
6571 },
@@ -68,6 +74,7 @@ export const mcpPresets: readonly McpPreset[] = [ · 2 unmodified lines
6874 name: "Axiom",
6975 summary: "Query, analyze, and monitor your logs and event data.",
7076 url: "https://mcp.axiom.co/mcp",
77+ endpoint: "https://mcp.axiom.co/mcp",
7178 icon: "https://axiom.co/favicon.ico",
7279 featured: true,
7380 },
@@ -76,6 +83,7 @@ export const mcpPresets: readonly McpPreset[] = [ · 2 unmodified lines
7683 name: "Stripe",
7784 summary: "Manage payments, subscriptions, and billing via MCP.",
7885 url: "https://mcp.stripe.com",
86+ endpoint: "https://mcp.stripe.com",
7987 icon: "https://stripe.com/favicon.ico",
8088 featured: true,
8189 },
@@ -84,6 +92,7 @@ export const mcpPresets: readonly McpPreset[] = [ · 2 unmodified lines
8492 name: "Linear",
8593 summary: "Issues, projects, teams, and cycles via MCP.",
8694 url: "https://mcp.linear.app/mcp",
95+ endpoint: "https://mcp.linear.app/mcp",
8796 icon: "https://linear.app/favicon.ico",
8897 featured: true,
8998 },
@@ -92,6 +101,7 @@ export const mcpPresets: readonly McpPreset[] = [ · 2 unmodified lines
92101 name: "Notion",
93102 summary: "Databases, pages, blocks, and search via MCP.",
94103 url: "https://mcp.notion.com/mcp",
104+ endpoint: "https://mcp.notion.com/mcp",
95105 icon: "https://www.notion.com/front-static/favicon.ico",
96106 featured: true,
97107 },
@@ -100,6 +110,7 @@ export const mcpPresets: readonly McpPreset[] = [ · 2 unmodified lines
100110 name: "Sentry",
101111 summary: "Error monitoring, issues, and performance data.",
102112 url: "https://mcp.sentry.dev/mcp",
113+ endpoint: "https://mcp.sentry.dev/mcp",
103114 icon: "https://sentry-brand.storage.googleapis.com/sentry-glyph-black.png",
104115 },
105116 {
@@ -107,6 +118,7 @@ export const mcpPresets: readonly McpPreset[] = [ · 1 unmodified line
107118 name: "Cloudflare",
108119 summary: "Workers, KV, D1, R2, and DNS management via MCP.",
109120 url: "https://mcp.cloudflare.com/mcp",
121+ endpoint: "https://mcp.cloudflare.com/mcp",
110122 icon: "https://cloudflare.com/favicon.ico",
111123 },
112124 {
packages/plugins/onepassword/src/sdk/plugin.test.ts+33−0
@@ -54,6 +54,39 @@ layer( · 53 unmodified lines
5454 }),
5555 );
5656
57+ it.effect("exposes provider configuration as agent-callable static tools", () =>
58+ Effect.gen(function* () {
59+ const { config: harnessConfig } = yield* TestWorkspace;
60+ const executor = yield* createExecutor({ ...harnessConfig, plugins });
61+
62+ const configured = yield* executor.tools.invoke(
63+ "executor.onepassword.configure",
64+ {
65+ scope: "test-scope",
66+ auth: { kind: "desktop-app", accountName: "my.1password.com" },
67+ vaultId: "vault-123",
68+ name: "Personal",
69+ },
70+ { onElicitation: "accept-all" },
71+ );
72+
73+ expect(configured).toEqual({ ok: true, data: { configured: true } });
74+ expect(yield* executor.tools.invoke("executor.onepassword.getConfig", {})).toMatchObject({
75+ ok: true,
76+ data: { config: { vaultId: "vault-123", name: "Personal" } },
77+ });
78+
79+ const removed = yield* executor.tools.invoke(
80+ "executor.onepassword.removeConfig",
81+ { targetScope: "test-scope" },
82+ { onElicitation: "accept-all" },
83+ );
84+
85+ expect(removed).toEqual({ ok: true, data: { removed: true } });
86+ expect(yield* executor.onepassword.getConfig()).toBeNull();
87+ }),
88+ );
89+
5790 it.effect("status reports not-configured before configure", () =>
5891 Effect.gen(function* () {
5992 const { config: harnessConfig } = yield* TestWorkspace;
packages/plugins/onepassword/src/sdk/plugin.ts+124−2
@@ -3,14 +3,16 @@ import { Effect, Schema } from "effect"; · 2 unmodified lines
33 import {
44 definePlugin,
55 StorageError,
6+ ToolResult,
7+ tool,
68 type PluginCtx,
79 type PluginBlobStore,
810 type SecretProvider,
11+ type StaticToolSchema,
912 type StorageFailure,
1013 } from "@executor-js/sdk/core";
1114
12−import { OnePasswordConfig, Vault, ConnectionStatus } from "./types";
13−import type { OnePasswordAuth } from "./types";
15+import { OnePasswordAuth, OnePasswordConfig, Vault, ConnectionStatus } from "./types";
1416 import { OnePasswordError } from "./errors";
1517 import { makeOnePasswordService, type ResolvedAuth, type OnePasswordService } from "./service";
1618
@@ -22,6 +24,61 @@ const CREDENTIAL_FIELD = "credential"; · 5 unmodified lines
2224 const DEFAULT_TIMEOUT_MS = 15_000;
2325 const CONFIG_KEY = "config";
2426
27+const schemaToStaticToolSchema = <A, I>(schema: Schema.Decoder<A, I>): StaticToolSchema<A, I> =>
28+ Schema.toStandardSchemaV1(Schema.toStandardJSONSchemaV1(schema) as never) as StaticToolSchema<
29+ A,
30+ I
31+ >;
32+
33+const OnePasswordConfigureInput = Schema.Struct({
34+ scope: Schema.String,
35+ auth: OnePasswordAuth,
36+ vaultId: Schema.String,
37+ name: Schema.String,
38+});
39+
40+const OnePasswordConfigureOutput = Schema.Struct({
41+ configured: Schema.Boolean,
42+});
43+
44+const OnePasswordGetConfigOutput = Schema.Struct({
45+ config: Schema.NullOr(OnePasswordConfig),
46+});
47+
48+const OnePasswordListVaultsInput = OnePasswordAuth;
49+
50+const OnePasswordListVaultsOutput = Schema.Struct({
51+ vaults: Schema.Array(Vault),
52+});
53+
54+const OnePasswordRemoveConfigInput = Schema.Struct({
55+ targetScope: Schema.String,
56+});
57+
58+const OnePasswordRemoveConfigOutput = Schema.Struct({
59+ removed: Schema.Boolean,
60+});
61+
62+const OnePasswordStatusOutput = ConnectionStatus;
63+
64+const OnePasswordConfigureInputStd = schemaToStaticToolSchema<
65+ typeof OnePasswordConfigureInput.Type,
66+ typeof OnePasswordConfigureInput.Encoded
67+>(OnePasswordConfigureInput);
68+const OnePasswordConfigureOutputStd = schemaToStaticToolSchema(OnePasswordConfigureOutput);
69+const OnePasswordGetConfigOutputStd = schemaToStaticToolSchema(OnePasswordGetConfigOutput);
70+const OnePasswordListVaultsInputStd = schemaToStaticToolSchema<
71+ typeof OnePasswordListVaultsInput.Type,
72+ typeof OnePasswordListVaultsInput.Encoded
73+>(OnePasswordListVaultsInput);
74+const OnePasswordListVaultsOutputStd = schemaToStaticToolSchema(OnePasswordListVaultsOutput);
75+const OnePasswordRemoveConfigInputStd = schemaToStaticToolSchema<
76+ typeof OnePasswordRemoveConfigInput.Type,
77+ typeof OnePasswordRemoveConfigInput.Encoded
78+>(OnePasswordRemoveConfigInput);
79+const OnePasswordRemoveConfigOutputStd = schemaToStaticToolSchema(OnePasswordRemoveConfigOutput);
80+const OnePasswordStatusOutputStd = schemaToStaticToolSchema(OnePasswordStatusOutput);
81+
2582 // ---------------------------------------------------------------------------
2683 // Shared failure alias.
2784 //
@@ -304,6 +361,71 @@ export const onepasswordPlugin = definePlugin((options?: OnePasswordPluginOption · 276 unmodified lines
304361
305362 extension: (ctx) => makeOnePasswordExtension(ctx, timeoutMs, preferSdk),
306363
364+ staticSources: (self) => [
365+ {
366+ id: "onepassword",
367+ kind: "executor",
368+ name: "1Password",
369+ tools: [
370+ tool({
371+ name: "status",
372+ description:
373+ "Check whether the 1Password secret provider is configured and can reach its selected vault. This returns status only, never secret values.",
374+ outputSchema: OnePasswordStatusOutputStd,
375+ execute: () => Effect.map(self.status(), ToolResult.ok),
376+ }),
377+ tool({
378+ name: "getConfig",
379+ description:
380+ "Read the current 1Password provider configuration. This returns account/vault metadata and secret ids only; service-account token values are never returned.",
381+ outputSchema: OnePasswordGetConfigOutputStd,
382+ execute: () => Effect.map(self.getConfig(), (config) => ToolResult.ok({ config })),
383+ }),
384+ tool({
385+ name: "listVaults",
386+ description:
387+ "List available 1Password vaults before configuring the provider. For service-account auth, first call `executor.coreTools.secrets.create` so the token is entered in the browser, then pass that token secret id here.",
388+ inputSchema: OnePasswordListVaultsInputStd,
389+ outputSchema: OnePasswordListVaultsOutputStd,
390+ execute: (input) =>
391+ Effect.map(self.listVaults(input), (vaults) => ToolResult.ok({ vaults })),
392+ }),
393+ tool({
394+ name: "configure",
395+ description:
396+ "Configure the 1Password secret provider for a target executor scope. Use desktop-app auth for local biometric access, or service-account auth with a token secret id created through `executor.coreTools.secrets.create`; never ask the user to paste the token in chat.",
397+ annotations: {
398+ requiresApproval: true,
399+ approvalDescription: "Configure the 1Password secret provider",
400+ },
401+ inputSchema: OnePasswordConfigureInputStd,
402+ outputSchema: OnePasswordConfigureOutputStd,
403+ execute: (input) =>
404+ Effect.as(
405+ self.configure(
406+ { auth: input.auth, vaultId: input.vaultId, name: input.name },
407+ input.scope,
408+ ),
409+ ToolResult.ok({ configured: true }),
410+ ),
411+ }),
412+ tool({
413+ name: "removeConfig",
414+ description:
415+ "Remove the 1Password provider configuration from a target scope. Existing secrets are not revealed; future 1Password secret resolution will stop until reconfigured.",
416+ annotations: {
417+ requiresApproval: true,
418+ approvalDescription: "Remove the 1Password secret provider configuration",
419+ },
420+ inputSchema: OnePasswordRemoveConfigInputStd,
421+ outputSchema: OnePasswordRemoveConfigOutputStd,
422+ execute: (input) =>
423+ Effect.as(self.removeConfig(input.targetScope), ToolResult.ok({ removed: true })),
424+ }),
425+ ],
426+ },
427+ ],
428+
307429 secretProviders: (ctx) => [makeProvider(ctx, timeoutMs, preferSdk)],
308430 };
309431 // HTTP transport (routes/handlers/extensionService) is layered on by
packages/plugins/openapi/src/sdk/__snapshots__/real-specs.test.ts.snap+5−5
@@ -258,7 +258,7 @@ exports[`Real specs: Cloudflare API > preserves registered tool schema and TypeS · 257 unmodified lines
258258 "AccessAppPolicyLink": "{ id?: AccessSchemasUuid; precedence?: AccessPrecedence; }",
259259 "AccessAppPolicyRequest": "({ precedence?: AccessPrecedence; } & AccessPolicyReq)",
260260 "AccessAppPolicyResponse": "(AccessPolicyResp & { precedence?: AccessPrecedence; })",
261− "AccessAppReqEmbeddedPolicies": "{ policies?: (AccessAppPolicyLink | ({ [k: string]: unknown; } & AccessSchemasUuid) | ({ } & { id?: AccessSchemasUuid; } & AccessAppPolicyRequest))[]; }",
261+ "AccessAppReqEmbeddedPolicies": "{ policies?: (AccessAppPolicyLink | ({ [k: string]: unknown; } & AccessSchemasUuid) | ({ [k: string]: unknown; } & { id?: AccessSchemasUuid; } & AccessAppPolicyRequest))[]; }",
262262 "AccessAppReqEmbeddedScimConfig": "{ scim_config?: AccessScimConfig; }",
263263 "AccessAppRequest": "SelfHostedApplication | SaaSApplication | BrowserSSHApplication | BrowserVNCApplication | AppLauncherApplication | DeviceEnrollmentPermissionsApplication | BrowserIsolationPermissionsApplication | GatewayIdentityProxyEndpointApplication | BookmarkApplication | InfrastructureApplication | BrowserRDPApplication | MCPServerApplication | MCPServerPortalApplication",
264264 "AccessAppRespEmbeddedPolicies": "{ policies?: AccessAppPolicyResponse[]; }",
@@ -354,7 +354,7 @@ exports[`Real specs: Cloudflare API > preserves registered tool schema and TypeS · 89 unmodified lines
354354 "AccessUuid": "string",
355355 "AccessVncProps": "(SelfHostedApplication1 & { type?: (AccessType & { [k: string]: unknown; }); })",
356356 "AccessWarpProps": "(AccessFeatureAppProps & { domain?: { [k: string]: unknown; }; name?: string; type?: (AccessType & { [k: string]: unknown; }); })",
357− "AnyValidServiceToken": "{ any_valid_service_token: { }; }",
357+ "AnyValidServiceToken": "{ any_valid_service_token: { [k: string]: unknown; }; }",
358358 "AppLauncherApplication": "(AccessAppLauncherProps & AccessAppReqEmbeddedPolicies)",
359359 "AppLauncherApplication1": "(AccessBasicAppResponseProps & AccessAppLauncherProps & AccessAppRespEmbeddedPolicies)",
360360 "AuthenticationContext": "{ auth_context: { ac_id: string; id: string; identity_provider_id: string; }; }",
@@ -381,7 +381,7 @@ exports[`Real specs: Cloudflare API > preserves registered tool schema and TypeS · 20 unmodified lines
381381 "Email": "{ email: { email: string; }; }",
382382 "EmailDomain": "{ email_domain: { domain: string; }; }",
383383 "EmailList": "{ email_list: { id: string; }; }",
384− "Everyone": "{ everyone: { }; }",
384+ "Everyone": "{ everyone: { [k: string]: unknown; }; }",
385385 "ExternalEvaluation": "{ external_evaluation: { evaluate_url: string; keys_url: string; }; }",
386386 "GatewayIdentityProxyEndpointApplication": "(AccessProxyEndpointProps & AccessAppReqEmbeddedPolicies)",
387387 "GatewayIdentityProxyEndpointApplication1": "(AccessBasicAppResponseProps & AccessProxyEndpointProps & AccessAppRespEmbeddedPolicies)",
@@ -420,7 +420,7 @@ exports[`Real specs: Cloudflare API > preserves registered tool schema and TypeS · 32 unmodified lines
420420 "ServiceToken": "{ service_token: { token_id: string; }; }",
421421 "TargetCriteria": "{ port: AccessPort; target_attributes: AccessTargetAttributes; }",
422422 "UserRiskScore": "{ user_risk_score: { user_risk_score: ["low" | "medium" | "high" | "unscored", ...(("low" | "medium" | "high" | "unscored"))[]]; }; }",
423− "ValidCertificate": "{ certificate: { }; }",
423+ "ValidCertificate": "{ certificate: { [k: string]: unknown; }; }",
424424 "ViaMCPServerPortalDestination": "{ mcp_server_id?: string; type?: "via_mcp_server_portal"; }",
425425 },
426426 }
@@ -4325,7 +4325,7 @@ exports[`Real specs: Vercel API > preserves registered tool schema and TypeScrip · 3898 unmodified lines
43254325 ],
43264326 "type": "object",
43274327 },
4328− "outputTypeScript": "{ aliasAssignedAt?: number | false | true | null; alwaysRefuseToBuild?: false | true; build: { env: string[]; }; buildArtifactUrls?: string[]; builds?: { use: string; src?: string; config?: { [k: string]: unknown; }; }[]; env: string[]; inspectorUrl: string | null; isInConcurrentBuildsQueue: false | true; isInSystemBuildsQueue: false | true; projectSettings: { nodeVersion?: "24.x" | "22.x" | "20.x" | "18.x" | "16.x" | "14.x" | "12.x" | "10.x" | "8.10.x"; buildCommand?: string | null; devCommand?: string | null; framework?: "blitzjs" | "nextjs" | "gatsby" | "remix" | "react-router" | "astro" | "hexo" | "eleventy" | "docusaurus-2" | "docusaurus" | "preact" | "solidstart-1" | "solidstart" | "dojo" | "ember" | "vue" | "scully" | "ionic-angular" | "angular" | "polymer" | "svelte" | "sveltekit" | "sveltekit-1" | "ionic-react" | "create-react-app" | "gridsome" | "umijs" | "sapper" | "saber" | "stencil" | "nuxtjs" | "redwoodjs" | "hugo" | "jekyll" | "brunch" | "middleman" | "zola" | "hydrogen" | "vite" | "tanstack-start" | "vitepress" | "vuepress" | "parcel" | "fastapi" | "flask" | "fasthtml" | "django" | "ash" | "sanity-v3" | "sanity" | "storybook" | "nitro" | "hono" | "express" | "h3" | "koa" | "nestjs" | "elysia" | "fastify" | "xmcp" | "python" | "ruby" | "rust" | "axum" | "actix-web" | "node" | "go" | "services" | "mastra" | null; commandForIgnoringBuildStep?: string | null; installCommand?: string | null; outputDirectory?: string | null; speedInsights?: { id: string; enabledAt?: number; disabledAt?: number; canceledAt?: number; hasData?: false | true; paidAt?: number; }; webAnalytics?: { id: string; disabledAt?: number; canceledAt?: number; enabledAt?: number; hasData?: true; }; }; integrations?: { status: "skipped" | "pending" | "ready" | "error" | "timeout"; startedAt: number; claimedAt?: number; completedAt?: number; skippedAt?: number; skippedBy?: string; }; images?: { sizes?: number[]; qualities?: number[]; domains?: string[]; remotePatterns?: { protocol?: "http" | "https"; hostname: string; port?: string; pathname?: string; search?: string; }[]; localPatterns?: { pathname?: string; search?: string; }[]; minimumCacheTTL?: number; formats?: ("image/avif" | "image/webp")[]; dangerouslyAllowSVG?: false | true; contentSecurityPolicy?: string; contentDispositionType?: "inline" | "attachment"; }; alias?: string[]; aliasAssigned: false | true; bootedAt: number; buildingAt: number; buildContainerFinishedAt?: number; buildSkipped: false | true; creator: { uid: string; username?: string; avatar?: string; }; initReadyAt?: number; isFirstBranchDeployment?: false | true; lambdas?: { id: string; createdAt?: number; readyState?: "BUILDING" | "ERROR" | "INITIALIZING" | "READY"; entrypoint?: string | null; readyStateAt?: number; output: { path: string; functionName: string; }[]; }[]; public: false | true; ready?: number; status: "QUEUED" | "BUILDING" | "ERROR" | "BLOCKED" | "INITIALIZING" | "READY" | "CANCELED"; team?: { id: string; name: string; slug: string; avatar?: string; }; userAliases?: string[]; previewCommentsEnabled?: false | true; ttyBuildLogs?: false | true; customEnvironment?: { id: string; slug: string; type: "production" | "preview" | "development"; description?: string; branchMatcher?: { type: "endsWith" | "startsWith" | "equals"; pattern: string; }; domains?: { name: string; apexName: string; projectId: string; redirect?: string | null; redirectStatusCode?: 307 | 301 | 302 | 308 | null; gitBranch?: string | null; customEnvironmentId?: string | null; updatedAt?: number; createdAt?: number; verified: false | true; verification?: { type: string; domain: string; value: string; reason: string; }[]; }[]; currentDeploymentAliases?: string[]; createdAt: number; updatedAt: number; } | { id: string; }; oomReport?: "out-of-memory"; readyStateReason?: string; aliasWarning?: { code: string; message: string; link?: string; action?: string; } | null; id: string; createdAt: number; readyState: "QUEUED" | "BUILDING" | "ERROR" | "BLOCKED" | "INITIALIZING" | "READY" | "CANCELED"; name: string; type: "LAMBDAS"; aliasError?: { code: string; message: string; } | null; aliasFinal?: string | null; autoAssignCustomDomains?: false | true; automaticAliases?: string[]; buildErrorAt?: number; checksState?: "registered" | "running" | "completed"; checksConclusion?: "succeeded" | "failed" | "skipped" | "canceled"; deletedAt?: number | null; defaultRoute?: string; canceledAt?: number; errorCode?: string; errorLink?: string; errorMessage?: string | null; errorStep?: string; passiveRegions?: string[]; gitSource?: { type: "github"; repoId: string | number; ref?: string | null; sha?: string; prId?: number | null; } | { type: "github"; org: string; repo: string; ref?: string | null; sha?: string; prId?: number | null; } | { type: "github-custom-host"; host: string; repoId: string | number; ref?: string | null; sha?: string; prId?: number | null; } | { type: "github-custom-host"; host: string; org: string; repo: string; ref?: string | null; sha?: string; prId?: number | null; } | { type: "github-limited"; repoId: string | number; ref?: string | null; sha?: string; prId?: number | null; } | { type: "github-limited"; org: string; repo: string; ref?: string | null; sha?: string; prId?: number | null; } | { type: "gitlab"; projectId: string | number; ref?: string | null; sha?: string; prId?: number | null; } | { type: "bitbucket"; workspaceUuid?: string; repoUuid: string; ref?: string | null; sha?: string; prId?: number | null; } | { type: "bitbucket"; owner: string; slug: string; ref?: string | null; sha?: string; prId?: number | null; } | { type: "vercel"; org?: string; repo?: string; sha: string; repoPushedAt?: number; ref?: string | null; prId?: number | null; } | { type: "custom"; ref: string; sha: string; gitUrl: string; } | { type: "github"; ref: string; sha: string; repoId: number; org?: string; repo?: string; } | { type: "github-custom-host"; host: string; ref: string; sha: string; repoId: number; org?: string; repo?: string; } | { type: "github-limited"; ref: string; sha: string; repoId: number; org?: string; repo?: string; } | { type: "gitlab"; ref: string; sha: string; projectId: number; } | { type: "bitbucket"; ref: string; sha: string; owner?: string; slug?: string; workspaceUuid: string; repoUuid: string; } | { type: "vercel"; ref: string; sha: string; org: string; repo: string; repoPushedAt?: number; }; manualProvisioning?: { state: "PENDING" | "COMPLETE" | "TIMEOUT"; completedAt?: number; }; meta: { [k: string]: string; }; originCacheRegion?: string; nodeVersion?: "24.x" | "22.x" | "20.x" | "18.x" | "16.x" | "14.x" | "12.x" | "10.x" | "8.10.x"; project?: { id: string; name: string; framework?: string | null; }; prebuilt?: false | true; readySubstate?: "STAGED" | "ROLLING" | "PROMOTED"; regions: string[]; softDeletedByRetention?: false | true; source?: "api-trigger-git-deploy" | "cli" | "clone/repo" | "git" | "import" | "import/repo" | "redeploy" | "v0-web"; target?: "staging" | "production" | null; undeletedAt?: number; url: string; userConfiguredDeploymentId?: string; version: 2; oidcTokenClaims?: { iss: string; sub: string; scope: string; aud: string; owner: string; owner_id: string; project: string; project_id: string; environment: string; custom_environment_id?: string; plan?: string; }; projectId: string; plan: "pro" | "enterprise" | "hobby"; platform?: { source: { name: string; }; origin: { type: "id" | "url"; value: string; }; creator: { name: string; avatar?: string; }; meta?: { [k: string]: string; }; }; connectBuildsEnabled?: false | true; connectConfigurationId?: string; createdIn: string; crons?: { schedule: string; path: string; }[]; functions?: { [k: string]: { architecture?: "x86_64" | "arm64"; memory?: number; maxDuration?: number | "max"; regions?: string[]; functionFailoverRegions?: string[]; runtime?: string; includeFiles?: string; excludeFiles?: string; experimentalTriggers?: ({ type: "queue/v1beta"; consumer: string; topic: string; maxDeliveries?: number; retryAfterSeconds?: number; initialDelaySeconds?: number; maxConcurrency?: number; } | { type: "queue/v2beta"; topic: string; maxDeliveries?: number; retryAfterSeconds?: number; initialDelaySeconds?: number; maxConcurrency?: number; })[]; supportsCancellation?: false | true; }; } | null; monorepoManager?: string | null; ownerId: string; passiveConnectConfigurationId?: string; routes: ({ src: string; dest?: string; headers?: { [k: string]: string; }; methods?: string[]; continue?: (false | true); override?: (false | true); caseSensitive?: (false | true); check?: (false | true); important?: (false | true); status?: number; has?: ({ type: "host"; value: (string | { eq?: (string | number); neq?: string; inc?: string[]; ninc?: string[]; pre?: string; suf?: string; re?: string; gt?: number; gte?: number; lt?: number; lte?: number; }); } | { type: ("header" | "cookie" | "query"); key: string; value?: (string | { eq?: (string | number); neq?: string; inc?: string[]; ninc?: string[]; pre?: string; suf?: string; re?: string; gt?: number; gte?: number; lt?: number; lte?: number; }); })[]; missing?: ({ type: "host"; value: (string | { eq?: (string | number); neq?: string; inc?: string[]; ninc?: string[]; pre?: string; suf?: string; re?: string; gt?: number; gte?: number; lt?: number; lte?: number; }); } | { type: ("header" | "cookie" | "query"); key: string; value?: (string | { eq?: (string | number); neq?: string; inc?: string[]; ninc?: string[]; pre?: string; suf?: string; re?: string; gt?: number; gte?: number; lt?: number; lte?: number; }); })[]; mitigate?: { action: ("challenge" | "deny"); }; transforms?: { type: ("request.headers" | "request.query" | "response.headers"); op: ("append" | "set" | "delete"); target: { key: (string | { eq?: (string | number); neq?: string; inc?: string[]; ninc?: string[]; pre?: string; suf?: string; gt?: number; gte?: number; lt?: number; lte?: number; }); }; args?: (string | string[]); env?: string[]; }[]; env?: string[]; locale?: { redirect?: { [k: string]: string; }; cookie?: string; }; source?: string; destination?: string; statusCode?: number; middlewarePath?: string; middlewareRawSrc?: string[]; middleware?: number; respectOriginCacheControl?: (false | true); } | { handle: ("error" | "filesystem" | "hit" | "miss" | "rewrite" | "resource"); src?: string; dest?: string; status?: number; } | { src: string; continue: (false | true); middleware: 0; })[] | null; gitRepo?: { namespace: string; projectId: number; type: "gitlab"; url: string; path: string; defaultBranch: string; name: string; private: false | true; ownerType: "team" | "user"; } | { org: string; repo: string; repoId: number; type: "github"; repoOwnerId: number; path: string; defaultBranch: string; name: string; private: false | true; ownerType: "team" | "user"; } | { owner: string; repoUuid: string; slug: string; type: "bitbucket"; workspaceUuid: string; path: string; defaultBranch: string; name: string; private: false | true; ownerType: "team" | "user"; } | { org: string; repo: string; type: "vercel"; path: string; defaultBranch: string; name: string; private: false | true; ownerType: "team" | "user"; } | null; flags?: { definitions: { [k: string]: { options?: { value: FlagJSONValue; label?: string; }[]; url?: string; description?: string; }; }; } | { }[]; microfrontends?: { isDefaultApp?: false; defaultAppProjectName: string; defaultRoute?: string; groupIds: [string, ...(string)[]]; } | { isDefaultApp: true; mfeConfigUploadState?: "success" | "waiting_on_build" | "no_config"; defaultAppProjectName: string; defaultRoute?: string; groupIds: [string, ...(string)[]]; }; config?: { version?: number; functionType: "standard" | "fluid"; functionMemoryType: "standard" | "standard_legacy" | "performance"; functionTimeout: number | null; secureComputePrimaryRegion: string | null; secureComputeFallbackRegion: string | null; isUsingActiveCPU?: false | true; resourceConfig?: { buildQueue?: { configuration?: "SKIP_NAMESPACE_QUEUE" | "WAIT_FOR_NAMESPACE_QUEUE"; }; elasticConcurrency?: "TEAM_SETTING" | "PROJECT_SETTING" | "SKIP_QUEUE"; buildMachine?: { purchaseType?: "enhanced" | "turbo" | "standard" | null; }; }; }; checks?: { "deployment-alias": { state: "succeeded" | "failed" | "pending"; startedAt: number; completedAt?: number; }; }; seatBlock?: { blockCode: "TEAM_ACCESS_REQUIRED" | "COMMIT_AUTHOR_REQUIRED"; userId?: string; isVerified?: false | true; gitUserId?: string | number; gitProvider?: "gitlab" | "bitbucket" | "github"; }; attribution?: { commitMeta?: { email?: string; name?: string; isVerified?: false | true; }; gitUser?: { id: string | number; login: string; type?: string; provider?: string; }; vercelUser?: { id: string; username: string; teamRoles?: string[]; }; }; }",
4328+ "outputTypeScript": "{ aliasAssignedAt?: number | false | true | null; alwaysRefuseToBuild?: false | true; build: { env: string[]; }; buildArtifactUrls?: string[]; builds?: { use: string; src?: string; config?: { [k: string]: unknown; }; }[]; env: string[]; inspectorUrl: string | null; isInConcurrentBuildsQueue: false | true; isInSystemBuildsQueue: false | true; projectSettings: { nodeVersion?: "24.x" | "22.x" | "20.x" | "18.x" | "16.x" | "14.x" | "12.x" | "10.x" | "8.10.x"; buildCommand?: string | null; devCommand?: string | null; framework?: "blitzjs" | "nextjs" | "gatsby" | "remix" | "react-router" | "astro" | "hexo" | "eleventy" | "docusaurus-2" | "docusaurus" | "preact" | "solidstart-1" | "solidstart" | "dojo" | "ember" | "vue" | "scully" | "ionic-angular" | "angular" | "polymer" | "svelte" | "sveltekit" | "sveltekit-1" | "ionic-react" | "create-react-app" | "gridsome" | "umijs" | "sapper" | "saber" | "stencil" | "nuxtjs" | "redwoodjs" | "hugo" | "jekyll" | "brunch" | "middleman" | "zola" | "hydrogen" | "vite" | "tanstack-start" | "vitepress" | "vuepress" | "parcel" | "fastapi" | "flask" | "fasthtml" | "django" | "ash" | "sanity-v3" | "sanity" | "storybook" | "nitro" | "hono" | "express" | "h3" | "koa" | "nestjs" | "elysia" | "fastify" | "xmcp" | "python" | "ruby" | "rust" | "axum" | "actix-web" | "node" | "go" | "services" | "mastra" | null; commandForIgnoringBuildStep?: string | null; installCommand?: string | null; outputDirectory?: string | null; speedInsights?: { id: string; enabledAt?: number; disabledAt?: number; canceledAt?: number; hasData?: false | true; paidAt?: number; }; webAnalytics?: { id: string; disabledAt?: number; canceledAt?: number; enabledAt?: number; hasData?: true; }; }; integrations?: { status: "skipped" | "pending" | "ready" | "error" | "timeout"; startedAt: number; claimedAt?: number; completedAt?: number; skippedAt?: number; skippedBy?: string; }; images?: { sizes?: number[]; qualities?: number[]; domains?: string[]; remotePatterns?: { protocol?: "http" | "https"; hostname: string; port?: string; pathname?: string; search?: string; }[]; localPatterns?: { pathname?: string; search?: string; }[]; minimumCacheTTL?: number; formats?: ("image/avif" | "image/webp")[]; dangerouslyAllowSVG?: false | true; contentSecurityPolicy?: string; contentDispositionType?: "inline" | "attachment"; }; alias?: string[]; aliasAssigned: false | true; bootedAt: number; buildingAt: number; buildContainerFinishedAt?: number; buildSkipped: false | true; creator: { uid: string; username?: string; avatar?: string; }; initReadyAt?: number; isFirstBranchDeployment?: false | true; lambdas?: { id: string; createdAt?: number; readyState?: "BUILDING" | "ERROR" | "INITIALIZING" | "READY"; entrypoint?: string | null; readyStateAt?: number; output: { path: string; functionName: string; }[]; }[]; public: false | true; ready?: number; status: "QUEUED" | "BUILDING" | "ERROR" | "BLOCKED" | "INITIALIZING" | "READY" | "CANCELED"; team?: { id: string; name: string; slug: string; avatar?: string; }; userAliases?: string[]; previewCommentsEnabled?: false | true; ttyBuildLogs?: false | true; customEnvironment?: { id: string; slug: string; type: "production" | "preview" | "development"; description?: string; branchMatcher?: { type: "endsWith" | "startsWith" | "equals"; pattern: string; }; domains?: { name: string; apexName: string; projectId: string; redirect?: string | null; redirectStatusCode?: 307 | 301 | 302 | 308 | null; gitBranch?: string | null; customEnvironmentId?: string | null; updatedAt?: number; createdAt?: number; verified: false | true; verification?: { type: string; domain: string; value: string; reason: string; }[]; }[]; currentDeploymentAliases?: string[]; createdAt: number; updatedAt: number; } | { id: string; }; oomReport?: "out-of-memory"; readyStateReason?: string; aliasWarning?: { code: string; message: string; link?: string; action?: string; } | null; id: string; createdAt: number; readyState: "QUEUED" | "BUILDING" | "ERROR" | "BLOCKED" | "INITIALIZING" | "READY" | "CANCELED"; name: string; type: "LAMBDAS"; aliasError?: { code: string; message: string; } | null; aliasFinal?: string | null; autoAssignCustomDomains?: false | true; automaticAliases?: string[]; buildErrorAt?: number; checksState?: "registered" | "running" | "completed"; checksConclusion?: "succeeded" | "failed" | "skipped" | "canceled"; deletedAt?: number | null; defaultRoute?: string; canceledAt?: number; errorCode?: string; errorLink?: string; errorMessage?: string | null; errorStep?: string; passiveRegions?: string[]; gitSource?: { type: "github"; repoId: string | number; ref?: string | null; sha?: string; prId?: number | null; } | { type: "github"; org: string; repo: string; ref?: string | null; sha?: string; prId?: number | null; } | { type: "github-custom-host"; host: string; repoId: string | number; ref?: string | null; sha?: string; prId?: number | null; } | { type: "github-custom-host"; host: string; org: string; repo: string; ref?: string | null; sha?: string; prId?: number | null; } | { type: "github-limited"; repoId: string | number; ref?: string | null; sha?: string; prId?: number | null; } | { type: "github-limited"; org: string; repo: string; ref?: string | null; sha?: string; prId?: number | null; } | { type: "gitlab"; projectId: string | number; ref?: string | null; sha?: string; prId?: number | null; } | { type: "bitbucket"; workspaceUuid?: string; repoUuid: string; ref?: string | null; sha?: string; prId?: number | null; } | { type: "bitbucket"; owner: string; slug: string; ref?: string | null; sha?: string; prId?: number | null; } | { type: "vercel"; org?: string; repo?: string; sha: string; repoPushedAt?: number; ref?: string | null; prId?: number | null; } | { type: "custom"; ref: string; sha: string; gitUrl: string; } | { type: "github"; ref: string; sha: string; repoId: number; org?: string; repo?: string; } | { type: "github-custom-host"; host: string; ref: string; sha: string; repoId: number; org?: string; repo?: string; } | { type: "github-limited"; ref: string; sha: string; repoId: number; org?: string; repo?: string; } | { type: "gitlab"; ref: string; sha: string; projectId: number; } | { type: "bitbucket"; ref: string; sha: string; owner?: string; slug?: string; workspaceUuid: string; repoUuid: string; } | { type: "vercel"; ref: string; sha: string; org: string; repo: string; repoPushedAt?: number; }; manualProvisioning?: { state: "PENDING" | "COMPLETE" | "TIMEOUT"; completedAt?: number; }; meta: { [k: string]: string; }; originCacheRegion?: string; nodeVersion?: "24.x" | "22.x" | "20.x" | "18.x" | "16.x" | "14.x" | "12.x" | "10.x" | "8.10.x"; project?: { id: string; name: string; framework?: string | null; }; prebuilt?: false | true; readySubstate?: "STAGED" | "ROLLING" | "PROMOTED"; regions: string[]; softDeletedByRetention?: false | true; source?: "api-trigger-git-deploy" | "cli" | "clone/repo" | "git" | "import" | "import/repo" | "redeploy" | "v0-web"; target?: "staging" | "production" | null; undeletedAt?: number; url: string; userConfiguredDeploymentId?: string; version: 2; oidcTokenClaims?: { iss: string; sub: string; scope: string; aud: string; owner: string; owner_id: string; project: string; project_id: string; environment: string; custom_environment_id?: string; plan?: string; }; projectId: string; plan: "pro" | "enterprise" | "hobby"; platform?: { source: { name: string; }; origin: { type: "id" | "url"; value: string; }; creator: { name: string; avatar?: string; }; meta?: { [k: string]: string; }; }; connectBuildsEnabled?: false | true; connectConfigurationId?: string; createdIn: string; crons?: { schedule: string; path: string; }[]; functions?: { [k: string]: { architecture?: "x86_64" | "arm64"; memory?: number; maxDuration?: number | "max"; regions?: string[]; functionFailoverRegions?: string[]; runtime?: string; includeFiles?: string; excludeFiles?: string; experimentalTriggers?: ({ type: "queue/v1beta"; consumer: string; topic: string; maxDeliveries?: number; retryAfterSeconds?: number; initialDelaySeconds?: number; maxConcurrency?: number; } | { type: "queue/v2beta"; topic: string; maxDeliveries?: number; retryAfterSeconds?: number; initialDelaySeconds?: number; maxConcurrency?: number; })[]; supportsCancellation?: false | true; }; } | null; monorepoManager?: string | null; ownerId: string; passiveConnectConfigurationId?: string; routes: ({ src: string; dest?: string; headers?: { [k: string]: string; }; methods?: string[]; continue?: (false | true); override?: (false | true); caseSensitive?: (false | true); check?: (false | true); important?: (false | true); status?: number; has?: ({ type: "host"; value: (string | { eq?: (string | number); neq?: string; inc?: string[]; ninc?: string[]; pre?: string; suf?: string; re?: string; gt?: number; gte?: number; lt?: number; lte?: number; }); } | { type: ("header" | "cookie" | "query"); key: string; value?: (string | { eq?: (string | number); neq?: string; inc?: string[]; ninc?: string[]; pre?: string; suf?: string; re?: string; gt?: number; gte?: number; lt?: number; lte?: number; }); })[]; missing?: ({ type: "host"; value: (string | { eq?: (string | number); neq?: string; inc?: string[]; ninc?: string[]; pre?: string; suf?: string; re?: string; gt?: number; gte?: number; lt?: number; lte?: number; }); } | { type: ("header" | "cookie" | "query"); key: string; value?: (string | { eq?: (string | number); neq?: string; inc?: string[]; ninc?: string[]; pre?: string; suf?: string; re?: string; gt?: number; gte?: number; lt?: number; lte?: number; }); })[]; mitigate?: { action: ("challenge" | "deny"); }; transforms?: { type: ("request.headers" | "request.query" | "response.headers"); op: ("append" | "set" | "delete"); target: { key: (string | { eq?: (string | number); neq?: string; inc?: string[]; ninc?: string[]; pre?: string; suf?: string; gt?: number; gte?: number; lt?: number; lte?: number; }); }; args?: (string | string[]); env?: string[]; }[]; env?: string[]; locale?: { redirect?: { [k: string]: string; }; cookie?: string; }; source?: string; destination?: string; statusCode?: number; middlewarePath?: string; middlewareRawSrc?: string[]; middleware?: number; respectOriginCacheControl?: (false | true); } | { handle: ("error" | "filesystem" | "hit" | "miss" | "rewrite" | "resource"); src?: string; dest?: string; status?: number; } | { src: string; continue: (false | true); middleware: 0; })[] | null; gitRepo?: { namespace: string; projectId: number; type: "gitlab"; url: string; path: string; defaultBranch: string; name: string; private: false | true; ownerType: "team" | "user"; } | { org: string; repo: string; repoId: number; type: "github"; repoOwnerId: number; path: string; defaultBranch: string; name: string; private: false | true; ownerType: "team" | "user"; } | { owner: string; repoUuid: string; slug: string; type: "bitbucket"; workspaceUuid: string; path: string; defaultBranch: string; name: string; private: false | true; ownerType: "team" | "user"; } | { org: string; repo: string; type: "vercel"; path: string; defaultBranch: string; name: string; private: false | true; ownerType: "team" | "user"; } | null; flags?: { definitions: { [k: string]: { options?: { value: FlagJSONValue; label?: string; }[]; url?: string; description?: string; }; }; } | { [k: string]: unknown; }[]; microfrontends?: { isDefaultApp?: false; defaultAppProjectName: string; defaultRoute?: string; groupIds: [string, ...(string)[]]; } | { isDefaultApp: true; mfeConfigUploadState?: "success" | "waiting_on_build" | "no_config"; defaultAppProjectName: string; defaultRoute?: string; groupIds: [string, ...(string)[]]; }; config?: { version?: number; functionType: "standard" | "fluid"; functionMemoryType: "standard" | "standard_legacy" | "performance"; functionTimeout: number | null; secureComputePrimaryRegion: string | null; secureComputeFallbackRegion: string | null; isUsingActiveCPU?: false | true; resourceConfig?: { buildQueue?: { configuration?: "SKIP_NAMESPACE_QUEUE" | "WAIT_FOR_NAMESPACE_QUEUE"; }; elasticConcurrency?: "TEAM_SETTING" | "PROJECT_SETTING" | "SKIP_QUEUE"; buildMachine?: { purchaseType?: "enhanced" | "turbo" | "standard" | null; }; }; }; checks?: { "deployment-alias": { state: "succeeded" | "failed" | "pending"; startedAt: number; completedAt?: number; }; }; seatBlock?: { blockCode: "TEAM_ACCESS_REQUIRED" | "COMMIT_AUTHOR_REQUIRED"; userId?: string; isVerified?: false | true; gitUserId?: string | number; gitProvider?: "gitlab" | "bitbucket" | "github"; }; attribution?: { commitMeta?: { email?: string; name?: string; isVerified?: false | true; }; gitUser?: { id: string | number; login: string; type?: string; provider?: string; }; vercelUser?: { id: string; username: string; teamRoles?: string[]; }; }; }",
43294329 "schemaDefinitionCount": 1,
43304330 "schemaDefinitionNames": [
43314331 "FlagJSONValue",
packages/plugins/openapi/src/sdk/plugin.test.ts+72−7
@@ -237,7 +237,9 @@ describe("OpenAPI Plugin", () => { · 236 unmodified lines
237237 const tools = yield* executor.tools.list();
238238 const ids = tools.map((t) => t.id);
239239 expect(ids).toContain("executor.openapi.previewSpec");
240+ expect(ids).toContain("executor.openapi.getSource");
240241 expect(ids).toContain("executor.openapi.addSource");
242+ expect(ids).toContain("executor.openapi.configureSource");
241243 }),
242244 );
243245
@@ -282,9 +284,30 @@ describe("OpenAPI Plugin", () => { · 38 unmodified lines
282284 { spec: testApiSpec() },
283285 autoApprove,
284286 ),
285− ).data as { operationCount: number };
287+ ).data as { operationCount: number; operations?: unknown };
286288
287289 expect(preview.operationCount).toBeGreaterThanOrEqual(2);
290+ expect(preview.operations).toBeUndefined();
291+ }),
292+ );
293+
294+ it.effect("describes static previewSpec output from Standard Schema", () =>
295+ Effect.gen(function* () {
296+ const executor = yield* createExecutor(
297+ makeTestConfig({
298+ plugins: [openApiPlugin(), memorySecretsPlugin()] as const,
299+ }),
300+ );
301+
302+ const schema = yield* executor.tools.schema("executor.openapi.previewSpec");
303+
304+ expect(schema).not.toBeNull();
305+ expect(schema!.outputTypeScript).toContain("servers:");
306+ expect(schema!.outputTypeScript).toContain("securitySchemes:");
307+ expect(schema!.outputTypeScript).toContain("oauth2Presets:");
308+ expect(schema!.outputTypeScript).toContain("title: string | null");
309+ expect(schema!.outputTypeScript).not.toContain("operations:");
310+ expect(schema!.outputTypeScript).not.toContain("_tag");
288311 }),
289312 );
290313
@@ -299,7 +322,7 @@ describe("OpenAPI Plugin", () => { · 8 unmodified lines
299322 const schema = yield* executor.tools.schema("executor.openapi.addSource");
300323
301324 expect(schema).not.toBeNull();
302− expect(schema!.inputTypeScript).toContain("scope: string");
325+ expect(schema!.inputTypeScript).not.toContain("scope: string");
303326 expect(schema!.inputTypeScript).toContain('kind: "url"');
304327 expect(
305328 (schema!.inputSchema as { properties?: Record<string, unknown> }).properties,
@@ -330,20 +353,55 @@ describe("OpenAPI Plugin", () => { · 24 unmodified lines
330353 const result = unwrapInvocation(
331354 yield* executor.tools.invoke(
332355 "executor.openapi.addSource",
333− testApiSourceConfig({ scope: String(orgScope), namespace: "runtime" }),
356+ (({ scope: _scope, ...input }) => input)(
357+ testApiSourceConfig({ scope: "org", namespace: "runtime" }),
358+ ),
334359 autoApprove,
335360 ),
336− ).data as { sourceId: string; toolCount: number };
361+ ).data as { sourceId: string; source: { id: string; scope: string }; toolCount: number };
337362
338− expect(result).toEqual({ sourceId: "runtime", toolCount: 4 });
363+ expect(result).toEqual({
364+ sourceId: "runtime",
365+ source: { id: "runtime", scope: String(orgScope) },
366+ toolCount: 4,
367+ });
339368 expect(yield* executor.openapi.getSource("runtime", String(userScope))).toBeNull();
340369 expect((yield* executor.openapi.getSource("runtime", String(orgScope)))?.scope).toBe(
341370 orgScope,
342371 );
372+ const inspected = unwrapInvocation(
373+ yield* executor.tools.invoke(
374+ "executor.openapi.getSource",
375+ { namespace: "runtime", scope: "org" },
376+ autoApprove,
377+ ),
378+ ).data as { source: { namespace: string; scope: string } | null };
379+ expect(inspected.source).toMatchObject({ namespace: "runtime", scope: String(orgScope) });
343380 expect((yield* executor.tools.list()).map((t) => t.id)).toContain("runtime.items.listItems");
344381 }),
345382 );
346383
384+ it.effect("static previewSpec returns actionable tool failures", () =>
385+ Effect.gen(function* () {
386+ const config = makeTestConfig({ plugins: [openApiPlugin()] as const });
387+ const executor = yield* createExecutor(config);
388+
389+ const result = yield* executor.tools.invoke("executor.openapi.previewSpec", {
390+ spec: "not openapi",
391+ });
392+
393+ expect(result).toMatchObject({
394+ ok: false,
395+ error: {
396+ code: "openapi_parse_failed",
397+ },
398+ });
399+
400+ yield* executor.close();
401+ yield* Effect.promise(() => config.testDb.close());
402+ }),
403+ );
404+
347405 it.effect("requires approval before adding a source through the runtime tool", () =>
348406 Effect.gen(function* () {
349407 const executor = yield* createExecutor(
@@ -353,7 +411,9 @@ describe("OpenAPI Plugin", () => { · 3 unmodified lines
353411 const declined = yield* executor.tools
354412 .invoke(
355413 "executor.openapi.addSource",
356− testApiSourceConfig({ namespace: "runtime_declined" }),
414+ (({ scope: _scope, ...input }) => input)(
415+ testApiSourceConfig({ namespace: "runtime_declined" }),
416+ ),
357417 {
358418 onElicitation: () => Effect.succeed({ action: "decline" as const }),
359419 },
@@ -872,7 +932,12 @@ describe("OpenAPI Plugin", () => { · 512 unmodified lines
872932
873933 const remaining = yield* executor.tools.list();
874934 const ids = remaining.map((t) => t.id).sort();
875− expect(ids).toEqual(["executor.openapi.addSource", "executor.openapi.previewSpec"]);
935+ expect(ids).toEqual([
936+ "executor.openapi.addSource",
937+ "executor.openapi.configureSource",
938+ "executor.openapi.getSource",
939+ "executor.openapi.previewSpec",
940+ ]);
876941 }),
877942 );
878943
packages/plugins/openapi/src/sdk/plugin.ts+259−7
@@ -4,16 +4,17 @@ import { HttpClient } from "effect/unstable/http"; · 3 unmodified lines
44
55 import {
66 ConnectionId,
7+ CredentialBindingRef,
78 ScopeId,
89 SecretId,
910 SourceDetectionResult,
1011 StorageError,
1112 ToolResult,
13+ defaultSourceInstallScopeId,
1214 definePlugin,
1315 tool,
1416 resolveSecretBackedMap,
1517 type CredentialBindingValue,
16− type CredentialBindingRef,
1718 type PluginCtx,
1819 type StorageFailure,
1920 type ToolAnnotations,
@@ -31,7 +32,8 @@ import { parse, resolveSpecText } from "./parse"; · 11 unmodified lines
3132 import { extract } from "./extract";
3233 import { compileToolDefinitions, type ToolDefinition } from "./definitions";
3334 import { annotationsForOperation, invokeWithLayer } from "./invoke";
34−import { previewSpec, SpecPreview } from "./preview";
35+import { previewSpec, type SpecPreview } from "./preview";
36+import { openApiPresets } from "./presets";
3537 import {
3638 makeDefaultOpenapiStore,
3739 openapiSchema,
@@ -247,6 +249,70 @@ const PreviewSpecInputSchema = Schema.Struct({ · 209 unmodified lines
247249 ),
248250 });
249251
252+const StaticPreviewServerVariableSchema = Schema.Struct({
253+ default: Schema.String,
254+ enum: Schema.NullOr(Schema.Array(Schema.String)),
255+ description: Schema.NullOr(Schema.String),
256+});
257+const StaticPreviewServerSchema = Schema.Struct({
258+ url: Schema.String,
259+ description: Schema.NullOr(Schema.String),
260+ variables: Schema.NullOr(Schema.Record(Schema.String, StaticPreviewServerVariableSchema)),
261+});
262+const StaticPreviewOAuthAuthorizationCodeFlowSchema = Schema.Struct({
263+ authorizationUrl: Schema.String,
264+ tokenUrl: Schema.String,
265+ refreshUrl: Schema.NullOr(Schema.String),
266+ scopes: Schema.Record(Schema.String, Schema.String),
267+});
268+const StaticPreviewOAuthClientCredentialsFlowSchema = Schema.Struct({
269+ tokenUrl: Schema.String,
270+ refreshUrl: Schema.NullOr(Schema.String),
271+ scopes: Schema.Record(Schema.String, Schema.String),
272+});
273+const StaticPreviewOAuthFlowsSchema = Schema.Struct({
274+ authorizationCode: Schema.NullOr(StaticPreviewOAuthAuthorizationCodeFlowSchema),
275+ clientCredentials: Schema.NullOr(StaticPreviewOAuthClientCredentialsFlowSchema),
276+});
277+const StaticPreviewSecuritySchemeSchema = Schema.Struct({
278+ name: Schema.String,
279+ type: Schema.Literals(["http", "apiKey", "oauth2", "openIdConnect"]),
280+ scheme: Schema.NullOr(Schema.String),
281+ bearerFormat: Schema.NullOr(Schema.String),
282+ in: Schema.NullOr(Schema.Literals(["header", "query", "cookie"])),
283+ headerName: Schema.NullOr(Schema.String),
284+ description: Schema.NullOr(Schema.String),
285+ flows: Schema.NullOr(StaticPreviewOAuthFlowsSchema),
286+ openIdConnectUrl: Schema.NullOr(Schema.String),
287+});
288+const StaticPreviewOAuth2PresetSchema = Schema.Struct({
289+ label: Schema.String,
290+ securitySchemeName: Schema.String,
291+ flow: Schema.Literals(["authorizationCode", "clientCredentials"]),
292+ authorizationUrl: Schema.NullOr(Schema.String),
293+ tokenUrl: Schema.String,
294+ refreshUrl: Schema.NullOr(Schema.String),
295+ scopes: Schema.Record(Schema.String, Schema.String),
296+});
297+const StaticPreviewSpecOutputSchema = Schema.Struct({
298+ title: Schema.NullOr(Schema.String),
299+ version: Schema.NullOr(Schema.String),
300+ servers: Schema.Array(StaticPreviewServerSchema),
301+ operationCount: Schema.Number,
302+ tags: Schema.Array(Schema.String),
303+ securitySchemes: Schema.Array(StaticPreviewSecuritySchemeSchema),
304+ authStrategies: Schema.Array(Schema.Struct({ schemes: Schema.Array(Schema.String) })),
305+ headerPresets: Schema.Array(
306+ Schema.Struct({
307+ label: Schema.String,
308+ headers: Schema.Record(Schema.String, Schema.NullOr(Schema.String)),
309+ secretHeaders: Schema.Array(Schema.String),
310+ }),
311+ ),
312+ oauth2Presets: Schema.Array(StaticPreviewOAuth2PresetSchema),
313+});
314+type StaticPreviewSpecOutput = typeof StaticPreviewSpecOutputSchema.Type;
315+
250316 const OpenApiSpecInputSchema = Schema.Union([
251317 Schema.Struct({ kind: Schema.Literal("url"), url: Schema.String }),
252318 Schema.Struct({ kind: Schema.Literal("blob"), value: Schema.String }),
@@ -301,10 +367,16 @@ const OpenApiConfigureInputSchema = Schema.Struct({ · 48 unmodified lines
301367 oauth2Source: Schema.optional(OAuth2SourceConfig),
302368 });
303369 export type OpenApiConfigureInput = typeof OpenApiConfigureInputSchema.Type;
370+const OpenApiConfigureSourceInputSchema = Schema.Struct({
371+ source: Schema.Struct({
372+ id: Schema.String,
373+ scope: Schema.String,
374+ }),
375+ ...OpenApiConfigureInputSchema.fields,
376+});
304377 const OpenApiOAuthInputSchema = OAuth2SourceConfig;
305378
306379 const AddSourceInputSchema = Schema.Struct({
307− scope: Schema.String,
308380 spec: OpenApiSpecInputSchema,
309381 name: Schema.String,
310382 baseUrl: Schema.String,
@@ -322,18 +394,122 @@ const AddSourceInputSchema = Schema.Struct({ · 11 unmodified lines
322394
323395 const AddSourceOutputSchema = Schema.Struct({
324396 sourceId: Schema.String,
397+ source: Schema.Struct({
398+ id: Schema.String,
399+ scope: Schema.String,
400+ }),
325401 toolCount: Schema.Number,
326402 });
403+const GetSourceInputSchema = Schema.Struct({
404+ namespace: Schema.String,
405+ scope: Schema.String,
406+});
407+const GetSourceOutputSchema = Schema.Struct({
408+ source: Schema.NullOr(Schema.Unknown),
409+});
327410
328411 const PreviewSpecInputStandardSchema = Schema.toStandardSchemaV1(
329412 Schema.toStandardJSONSchemaV1(PreviewSpecInputSchema),
330413 );
414+const PreviewSpecOutputStandardSchema = Schema.toStandardSchemaV1(
415+ Schema.toStandardJSONSchemaV1(StaticPreviewSpecOutputSchema),
416+);
331417 const AddSourceInputStandardSchema = Schema.toStandardSchemaV1(
332418 Schema.toStandardJSONSchemaV1(AddSourceInputSchema),
333419 );
334420 const AddSourceOutputStandardSchema = Schema.toStandardSchemaV1(
335421 Schema.toStandardJSONSchemaV1(AddSourceOutputSchema),
336422 );
423+const OpenApiConfigureSourceInputStandardSchema = Schema.toStandardSchemaV1(
424+ Schema.toStandardJSONSchemaV1(OpenApiConfigureSourceInputSchema),
425+);
426+const OpenApiConfigureSourceOutputStandardSchema = Schema.toStandardSchemaV1(
427+ Schema.toStandardJSONSchemaV1(Schema.Struct({ result: Schema.Array(CredentialBindingRef) })),
428+);
429+const GetSourceInputStandardSchema = Schema.toStandardSchemaV1(
430+ Schema.toStandardJSONSchemaV1(GetSourceInputSchema),
431+);
432+const GetSourceOutputStandardSchema = Schema.toStandardSchemaV1(
433+ Schema.toStandardJSONSchemaV1(GetSourceOutputSchema),
434+);
435+
436+const openApiToolFailure = (code: string, message: string, details?: unknown) =>
437+ ToolResult.fail({
438+ code,
439+ message,
440+ ...(details === undefined ? {} : { details }),
441+ });
442+
443+const staticPreviewOutput = (preview: SpecPreview): StaticPreviewSpecOutput => ({
444+ title: Option.getOrNull(preview.title),
445+ version: Option.getOrNull(preview.version),
446+ servers: preview.servers.map((server) => ({
447+ url: server.url,
448+ description: Option.getOrNull(server.description),
449+ variables: Option.getOrNull(server.variables)
450+ ? Object.fromEntries(
451+ Object.entries(Option.getOrNull(server.variables) ?? {}).map(([name, variable]) => [
452+ name,
453+ {
454+ default: variable.default,
455+ enum: Option.getOrNull(variable.enum),
456+ description: Option.getOrNull(variable.description),
457+ },
458+ ]),
459+ )
460+ : null,
461+ })),
462+ operationCount: preview.operationCount,
463+ tags: preview.tags,
464+ securitySchemes: preview.securitySchemes.map((scheme) => ({
465+ name: scheme.name,
466+ type: scheme.type,
467+ scheme: Option.getOrNull(scheme.scheme),
468+ bearerFormat: Option.getOrNull(scheme.bearerFormat),
469+ in: Option.getOrNull(scheme.in),
470+ headerName: Option.getOrNull(scheme.headerName),
471+ description: Option.getOrNull(scheme.description),
472+ flows: Option.isSome(scheme.flows)
473+ ? {
474+ authorizationCode: Option.isSome(scheme.flows.value.authorizationCode)
475+ ? {
476+ authorizationUrl: scheme.flows.value.authorizationCode.value.authorizationUrl,
477+ tokenUrl: scheme.flows.value.authorizationCode.value.tokenUrl,
478+ refreshUrl: Option.getOrNull(scheme.flows.value.authorizationCode.value.refreshUrl),
479+ scopes: scheme.flows.value.authorizationCode.value.scopes,
480+ }
481+ : null,
482+ clientCredentials: Option.isSome(scheme.flows.value.clientCredentials)
483+ ? {
484+ tokenUrl: scheme.flows.value.clientCredentials.value.tokenUrl,
485+ refreshUrl: Option.getOrNull(scheme.flows.value.clientCredentials.value.refreshUrl),
486+ scopes: scheme.flows.value.clientCredentials.value.scopes,
487+ }
488+ : null,
489+ }
490+ : null,
491+ openIdConnectUrl: Option.getOrNull(scheme.openIdConnectUrl),
492+ })),
493+ authStrategies: preview.authStrategies,
494+ headerPresets: preview.headerPresets,
495+ oauth2Presets: preview.oauth2Presets.map((preset) => ({
496+ label: preset.label,
497+ securitySchemeName: preset.securitySchemeName,
498+ flow: preset.flow,
499+ authorizationUrl: Option.getOrNull(preset.authorizationUrl),
500+ tokenUrl: preset.tokenUrl,
501+ refreshUrl: Option.getOrNull(preset.refreshUrl),
502+ scopes: preset.scopes,
503+ })),
504+});
505+
506+const resolveStaticScopeInput = (
507+ ctx: { readonly scopes: readonly { readonly id: ScopeId; readonly name: string }[] },
508+ value: string,
509+): string =>
510+ String(
511+ ctx.scopes.find((scope) => scope.name === value || String(scope.id) === value)?.id ?? value,
512+ );
337513
338514 // ---------------------------------------------------------------------------
339515 // Helpers
@@ -1109,6 +1285,7 @@ export const openApiPlugin = definePlugin((options?: OpenApiPluginOptions) => { · 769 unmodified lines
11091285 return {
11101286 id: "openapi" as const,
11111287 packageName: "@executor-js/plugin-openapi",
1288+ sourcePresets: openApiPresets,
11121289 schema: openapiSchema,
11131290 storage: (deps): OpenapiStore => makeDefaultOpenapiStore(deps),
11141291
@@ -1236,20 +1413,95 @@ export const openApiPlugin = definePlugin((options?: OpenApiPluginOptions) => { · 121 unmodified lines
12361413 tools: [
12371414 tool({
12381415 name: "previewSpec",
1239− description: "Preview an OpenAPI document before adding it as a source",
1416+ description:
1417+ "Preview an OpenAPI document before adding it as a source. Call this first when the user provides a spec URL/blob so you can inspect servers, auth schemes, operation count, tags, and credential slots before `addSource`. This agent-facing preview intentionally omits the full operations list; use `operationCount` and `tags` for full-size specs. Do not collect API keys or OAuth client secrets in chat; use `executor.coreTools.secrets.create` for those values.",
12401418 inputSchema: PreviewSpecInputStandardSchema,
1241− execute: (input) => Effect.map(self.previewSpec(input), ToolResult.ok),
1419+ outputSchema: PreviewSpecOutputStandardSchema,
1420+ execute: (input) =>
1421+ self.previewSpec(input).pipe(
1422+ Effect.map((preview) => ToolResult.ok(staticPreviewOutput(preview))),
1423+ Effect.catchTags({
1424+ OpenApiParseError: ({ message }) =>
1425+ Effect.succeed(openApiToolFailure("openapi_parse_failed", message)),
1426+ OpenApiExtractionError: ({ message }) =>
1427+ Effect.succeed(openApiToolFailure("openapi_extraction_failed", message)),
1428+ OpenApiOAuthError: ({ message }) =>
1429+ Effect.succeed(openApiToolFailure("openapi_oauth_failed", message)),
1430+ }),
1431+ ),
1432+ }),
1433+ tool({
1434+ name: "getSource",
1435+ description:
1436+ "Inspect an existing OpenAPI source, including effective base URL, configured headers/query params, OAuth settings, and stored credential slots. Use this before repairing an existing source with `openapi.configureSource`, `secrets.create`, or `oauth.start`.",
1437+ inputSchema: GetSourceInputStandardSchema,
1438+ outputSchema: GetSourceOutputStandardSchema,
1439+ execute: (input, { ctx }) =>
1440+ Effect.map(
1441+ self.getSource(input.namespace, resolveStaticScopeInput(ctx, input.scope)),
1442+ (source) => ToolResult.ok({ source }),
1443+ ),
12421444 }),
12431445 tool({
12441446 name: "addSource",
1245− description: "Add an OpenAPI source and register its operations as tools",
1447+ description:
1448+ "Add an OpenAPI source and register its operations as tools. Executor chooses the source install scope (local scope locally, organization scope in cloud) and returns it as `source`. Recommended flow: call `previewSpec`, choose or confirm namespace/name/baseUrl from the preview (baseUrl is only needed when the spec cannot infer one or the user wants an override), declare credential slots here for sensitive headers/query params, then call `secrets.create` and `openapi.configureSource` with the user's chosen credential scope for per-scope bindings. Use `oauth.start` with `credentialScope` set to the user's chosen personal or organization credential scope for browser OAuth sign-in.",
12461449 annotations: {
12471450 requiresApproval: true,
12481451 approvalDescription: "Add an OpenAPI source",
12491452 },
12501453 inputSchema: AddSourceInputStandardSchema,
12511454 outputSchema: AddSourceOutputStandardSchema,
1252− execute: (input) => Effect.map(self.addSpec(input), ToolResult.ok),
1455+ execute: (input, { ctx }) => {
1456+ const sourceScope = defaultSourceInstallScopeId(ctx.scopes);
1457+ if (sourceScope === null) {
1458+ return Effect.succeed(
1459+ openApiToolFailure(
1460+ "source_scope_unavailable",
1461+ "Cannot add an OpenAPI source because this executor has no source install scope.",
1462+ ),
1463+ );
1464+ }
1465+ return self.addSpec({ ...input, scope: sourceScope }).pipe(
1466+ Effect.map((result) =>
1467+ ToolResult.ok({
1468+ ...result,
1469+ source: { id: result.sourceId, scope: sourceScope },
1470+ }),
1471+ ),
1472+ Effect.catchTags({
1473+ OpenApiParseError: ({ message }) =>
1474+ Effect.succeed(openApiToolFailure("openapi_parse_failed", message)),
1475+ OpenApiExtractionError: ({ message }) =>
1476+ Effect.succeed(openApiToolFailure("openapi_extraction_failed", message)),
1477+ OpenApiOAuthError: ({ message }) =>
1478+ Effect.succeed(openApiToolFailure("openapi_oauth_failed", message)),
1479+ }),
1480+ );
1481+ },
1482+ }),
1483+ tool({
1484+ name: "configureSource",
1485+ description:
1486+ 'Configure an existing OpenAPI source with concrete fields. Use `source` returned by `openapi.addSource` or `sources.list`. The top-level `scope` is the credential target scope for bindings; in cloud, choose the user or organization credential scope deliberately. Pass secret refs as `{kind:"secret", secretId}` and OAuth connections as `{kind:"connection", connectionId}`.',
1487+ annotations: {
1488+ requiresApproval: true,
1489+ approvalDescription: "Configure an OpenAPI source",
1490+ },
1491+ inputSchema: OpenApiConfigureSourceInputStandardSchema,
1492+ outputSchema: OpenApiConfigureSourceOutputStandardSchema,
1493+ execute: (input, { ctx }) => {
1494+ const { source, ...config } = input as typeof OpenApiConfigureSourceInputSchema.Type;
1495+ const sourceScope = resolveStaticScopeInput(ctx, source.scope);
1496+ const targetScope = resolveStaticScopeInput(ctx, config.scope);
1497+ return Effect.map(
1498+ self.configure(
1499+ { id: source.id, scope: sourceScope },
1500+ { ...config, scope: targetScope },
1501+ ),
1502+ (result) => ToolResult.ok({ result }),
1503+ );
1504+ },
12531505 }),
12541506 ],
12551507 },
packages/react/src/components/mcp-install-card.test.ts+14−0
@@ -72,6 +72,20 @@ describe("MCP install command rendering", () => { · 71 unmodified lines
7272 ).toBe("npx add-mcp 'executor mcp' --name executor");
7373 });
7474
75+ it("pins dev stdio install commands to the repo cwd", () => {
76+ expect(
77+ buildMcpInstallCommand({
78+ mode: "stdio",
79+ isDev: true,
80+ origin: null,
81+ scopeDir: "/Users/rhyssullivan/src/executor/apps/local",
82+ devCliCwd: "/Users/rhyssullivan/src/executor",
83+ }),
84+ ).toBe(
85+ "npx add-mcp 'bun run --cwd /Users/rhyssullivan/src/executor dev:cli mcp --scope /Users/rhyssullivan/src/executor/apps/local' --name executor",
86+ );
87+ });
88+
7589 it("passes browser approval through stdio install commands when explicitly selected", () => {
7690 expect(
7791 buildMcpInstallCommand({
packages/react/src/components/mcp-install-card.tsx+9−2
@@ -21,6 +21,7 @@ const SUPPORTED_AGENTS = [ · 20 unmodified lines
2121 ] as const;
2222
2323 const isDev = import.meta.env.DEV;
24+const devCliCwd = import.meta.env.VITE_EXECUTOR_DEV_CLI_CWD as string | undefined;
2425 const isLocal =
2526 typeof window !== "undefined" &&
2627 (window.location.hostname === "localhost" ||
@@ -87,6 +88,7 @@ export const buildMcpInstallCommand = (input: { · 60 unmodified lines
8788 readonly password: string;
8889 } | null;
8990 readonly elicitationMode?: McpElicitationMode;
91+ readonly devCliCwd?: string;
9092 }): string => {
9193 if (input.mode === "http") {
9294 const endpoint = buildMcpHttpEndpoint({
@@ -105,7 +107,11 @@ export const buildMcpInstallCommand = (input: { · 12 unmodified lines
105107 return parts.join(" ");
106108 }
107109
108− const innerArgs = input.isDev ? ["bun", "run", "dev:cli", "mcp"] : ["executor", "mcp"];
110+ const innerArgs = input.isDev
111+ ? input.devCliCwd
112+ ? ["bun", "run", "--cwd", input.devCliCwd, "dev:cli", "mcp"]
113+ : ["bun", "run", "dev:cli", "mcp"]
114+ : ["executor", "mcp"];
109115 if (input.scopeDir) {
110116 innerArgs.push("--scope", input.scopeDir);
111117 }
@@ -149,12 +155,13 @@ export function McpInstallCard(props: { className?: string }) { · 37 unmodified lines
149155 scopeDir: scopeInfo.dir,
150156 desktop,
151157 elicitationMode,
158+ devCliCwd,
152159 });
153160
154161 const subtitle =
155162 mode === "stdio"
156163 ? isDev
157− ? "Uses the repo-local dev CLI. Run from the repository root."
164+ ? "Uses the repo-local dev CLI from any agent working directory."
158165 : "Requires the executor CLI on your PATH."
159166 : "Connect to executor as a remote MCP server over streamable HTTP.";
160167
packages/react/src/pages/secrets.test.ts+18−0
@@ -0,0 +1,18 @@
1+import { describe, expect, it } from "@effect/vitest";
2+import { ScopeId } from "@executor-js/sdk/shared";
3+
4+import { secretFormScopeId } from "./secrets";
5+
6+describe("secretFormScopeId", () => {
7+ it("uses the current route scope without an agent handoff target", () => {
8+ const current = ScopeId.make("current-scope");
9+
10+ expect(secretFormScopeId(current)).toBe(current);
11+ });
12+
13+ it("uses the agent handoff scope when one is present", () => {
14+ expect(secretFormScopeId(ScopeId.make("current-scope"), { scope: "target-scope" })).toBe(
15+ "target-scope",
16+ );
17+ });
18+});
packages/react/src/pages/secrets.tsx+102−17
@@ -8,7 +8,7 @@ import { toast } from "sonner"; · 7 unmodified lines
88 import { removeSecretOptimistic, secretsOptimisticAtom, secretUsagesAtom } from "../api/atoms";
99 import { secretWriteKeys } from "../api/reactivity-keys";
1010 import { useSecretProviderPlugins } from "@executor-js/sdk/client";
11−import { SecretId, SecretInUseError, type ScopeId } from "@executor-js/sdk/shared";
11+import { ScopeId, SecretId, SecretInUseError } from "@executor-js/sdk/shared";
1212 import { SecretForm } from "../plugins/secret-form";
1313 import { useScope } from "../hooks/use-scope";
1414 import { useScopeStack } from "../api/scope-context";
@@ -22,6 +22,14 @@ import { · 7 unmodified lines
2222 DialogClose,
2323 } from "../components/dialog";
2424 import { Button } from "../components/button";
25+import {
26+ Select,
27+ SelectContent,
28+ SelectItem,
29+ SelectTrigger,
30+ SelectValue,
31+} from "../components/select";
32+import { Label } from "../components/label";
2533 import {
2634 DropdownMenu,
2735 DropdownMenuContent,
@@ -39,12 +47,18 @@ import { · 11 unmodified lines
3947 CardStackHeader,
4048 } from "../components/card-stack";
4149 import { Badge } from "../components/badge";
50+import { cn } from "../lib/utils";
4251
4352 type SecretStorageOption = {
4453 readonly label: string;
4554 readonly value: string;
4655 };
4756
57+type SecretScopeOption = {
58+ readonly label: string;
59+ readonly value: ScopeId;
60+};
61+
4862 const defaultStorageOptions: readonly SecretStorageOption[] = [
4963 { value: "auto", label: "Auto" },
5064 { value: "keychain", label: "Keychain" },
@@ -62,13 +76,25 @@ const isSecretInUseError = Schema.is(SecretInUseError); · 11 unmodified lines
6276 // state always starts fresh — no manual reset.
6377 // ---------------------------------------------------------------------------
6478
79+interface SecretPrefill {
80+ readonly name?: string;
81+ readonly secretId?: string;
82+ readonly provider?: string;
83+ readonly scope?: string;
84+}
85+
86+export const secretFormScopeId = (currentScopeId: ScopeId, prefill?: SecretPrefill): ScopeId =>
87+ prefill?.scope ? ScopeId.make(prefill.scope) : currentScopeId;
88+
6589 function AddSecretDialog(props: {
6690 open: boolean;
6791 onOpenChange: (v: boolean) => void;
6892 description: string;
6993 storageOptions: readonly SecretStorageOption[];
70− existingSecretIds: readonly string[];
94+ existingSecrets: readonly { readonly id: string; readonly scopeId: ScopeId }[];
7195 scopeId: ScopeId;
96+ scopeOptions: readonly SecretScopeOption[];
97+ prefill?: SecretPrefill;
7298 }) {
7399 return (
74100 <Dialog open={props.open} onOpenChange={props.onOpenChange}>
@@ -77,8 +103,10 @@ function AddSecretDialog(props: { · 2 unmodified lines
77103 key="open"
78104 description={props.description}
79105 storageOptions={props.storageOptions}
80− existingSecretIds={props.existingSecretIds}
106+ existingSecrets={props.existingSecrets}
81107 scopeId={props.scopeId}
108+ scopeOptions={props.scopeOptions}
109+ prefill={props.prefill}
82110 onClose={() => props.onOpenChange(false)}
83111 />
84112 )}
@@ -89,17 +117,31 @@ function AddSecretDialog(props: { · 4 unmodified lines
89117 function AddSecretDialogContent(props: {
90118 description: string;
91119 storageOptions: readonly SecretStorageOption[];
92− existingSecretIds: readonly string[];
120+ existingSecrets: readonly { readonly id: string; readonly scopeId: ScopeId }[];
93121 scopeId: ScopeId;
122+ scopeOptions: readonly SecretScopeOption[];
123+ prefill?: SecretPrefill;
94124 onClose: () => void;
95125 }) {
96− const initialProvider = props.storageOptions[0]?.value ?? "auto";
126+ const initialProvider = props.prefill?.provider ?? props.storageOptions[0]?.value ?? "auto";
127+ const [targetScope, setTargetScope] = useState(props.scopeId);
128+ const existingSecretIds = useMemo(
129+ () =>
130+ props.existingSecrets
131+ .filter((secret) => secret.scopeId === targetScope)
132+ .map((secret) => secret.id),
133+ [props.existingSecrets, targetScope],
134+ );
135+ const controlFieldClassName =
136+ "[&_[data-slot=field-label]]:h-5 [&_[data-slot=field-label]]:items-start [&_[data-slot=field-label]]:leading-none [&_[data-slot=input]]:h-9";
97137
98138 return (
99139 <SecretForm.Provider
100− existingSecretIds={props.existingSecretIds}
140+ existingSecretIds={existingSecretIds}
141+ suggestedName={props.prefill?.name}
142+ initialIdOverride={props.prefill?.secretId}
101143 initialProvider={initialProvider}
102− scopeId={props.scopeId}
144+ scopeId={targetScope}
103145 onCreated={props.onClose}
104146 >
105147 <DialogContent className="sm:max-w-[440px]">
@@ -111,11 +153,37 @@ function AddSecretDialogContent(props: { · 5 unmodified lines
111153 </DialogHeader>
112154
113155 <div className="grid gap-5 py-3">
114− <div className="grid grid-cols-2 gap-3">
115− <SecretForm.NameField />
116− <SecretForm.IdField />
156+ <div className="grid grid-cols-2 items-start gap-3">
157+ <div className={controlFieldClassName}>
158+ <SecretForm.NameField />
159+ </div>
160+ <div className={controlFieldClassName}>
161+ <SecretForm.IdField />
162+ </div>
163+ </div>
164+ <div className="grid grid-cols-2 items-start gap-3">
165+ <div className={controlFieldClassName}>
166+ <SecretForm.ValueField />
167+ </div>
168+ <div className={cn("grid min-w-0 gap-3", controlFieldClassName)}>
169+ <Label className="h-5 text-sm font-medium leading-none">Scope</Label>
170+ <Select
171+ value={targetScope}
172+ onValueChange={(value) => setTargetScope(ScopeId.make(value))}
173+ >
174+ <SelectTrigger className="h-9 w-full min-w-0 text-sm">
175+ <SelectValue />
176+ </SelectTrigger>
177+ <SelectContent>
178+ {props.scopeOptions.map((option) => (
179+ <SelectItem key={option.value} value={option.value}>
180+ {option.label}
181+ </SelectItem>
182+ ))}
183+ </SelectContent>
184+ </Select>
185+ </div>
117186 </div>
118− <SecretForm.ValueField />
119187 <SecretForm.ProviderField options={props.storageOptions} />
120188 <SecretForm.ErrorBanner />
121189 </div>
@@ -232,6 +300,11 @@ export function SecretsPage(props: { · 110 unmodified lines
232300 addSecretDescription?: string;
233301 showProviderInfo?: boolean;
234302 storageOptions?: readonly SecretStorageOption[];
303+ /** Pre-fill values for the add-secret modal and auto-open it. Set by
304+ * the route when the URL carries `?openAdd=1&name=…&secretId=…`,
305+ * which is how the agent-facing `secrets.create` tool hands a user
306+ * off to this page. */
307+ prefill?: SecretPrefill;
235308 }) {
236309 const storageOptions = props.storageOptions ?? defaultStorageOptions;
237310 const showProviderInfo = props.showProviderInfo ?? true;
@@ -239,8 +312,9 @@ export function SecretsPage(props: { · 1 unmodified line
239312 props.addSecretDescription ??
240313 "Store a credential or API key. Values are kept in your system keychain when available, with a local encrypted file fallback.";
241314 const secretProviderPlugins = useSecretProviderPlugins();
242− const [addOpen, setAddOpen] = useState(false);
315+ const [addOpen, setAddOpen] = useState(props.prefill != null);
243316 const scopeId = useScope();
317+ const formScopeId = secretFormScopeId(scopeId, props.prefill);
244318 const scopeStack = useScopeStack();
245319 const secrets = useAtomValue(secretsOptimisticAtom(scopeId));
246320 const scopeLabel = (secretScopeId: ScopeId): string => {
@@ -252,12 +326,21 @@ export function SecretsPage(props: { · 5 unmodified lines
252326 const existingSecretIds = useMemo(
253327 () =>
254328 AsyncResult.match(secrets, {
255− onInitial: () => [] as string[],
256− onFailure: () => [] as string[],
257− onSuccess: ({ value }) => value.map((secret) => secret.id),
329+ onInitial: () => [] as { readonly id: string; readonly scopeId: ScopeId }[],
330+ onFailure: () => [] as { readonly id: string; readonly scopeId: ScopeId }[],
331+ onSuccess: ({ value }) =>
332+ value.map((secret) => ({ id: secret.id, scopeId: secret.scopeId })),
258333 }),
259334 [secrets],
260335 );
336+ const scopeOptions = useMemo(
337+ () =>
338+ scopeStack.map((entry, index) => ({
339+ value: entry.id,
340+ label: index === 0 ? "Personal" : entry.name || "Organization",
341+ })),
342+ [scopeStack],
343+ );
261344 const doRemove = useAtomSet(removeSecretOptimistic(scopeId), {
262345 mode: "promiseExit",
263346 });
@@ -393,8 +476,10 @@ export function SecretsPage(props: { · 129 unmodified lines
393476 onOpenChange={setAddOpen}
394477 description={addSecretDescription}
395478 storageOptions={storageOptions}
396− existingSecretIds={existingSecretIds}
397− scopeId={scopeId}
479+ existingSecrets={existingSecretIds}
480+ scopeId={formScopeId}
481+ scopeOptions={scopeOptions}
482+ prefill={props.prefill}
398483 />
399484 </div>
400485 </div>
packages/react/src/plugins/secret-form.tsx+6−1
@@ -90,6 +90,10 @@ interface SecretFormProviderProps { · 89 unmodified lines
9090 readonly existingSecretIds: readonly string[];
9191 readonly suggestedName?: string;
9292 readonly fallbackId?: string;
93+ /** Force the secret id to a pre-allocated value (e.g. when the agent's
94+ * `secrets.create` tool generated a UUID up front and the user is
95+ * just here to provide the value). */
96+ readonly initialIdOverride?: string;
9397 readonly initialProvider?: string;
9498 readonly scopeId: ScopeId;
9599 readonly onCreated: (secretId: string) => void;
@@ -101,6 +105,7 @@ function SecretFormProvider(props: SecretFormProviderProps) { · 5 unmodified lines
101105 existingSecretIds,
102106 suggestedName = "",
103107 fallbackId = "secret",
108+ initialIdOverride,
104109 initialProvider = "auto",
105110 scopeId,
106111 onCreated,
@@ -112,7 +117,7 @@ function SecretFormProvider(props: SecretFormProviderProps) { · 5 unmodified lines
112117 const [state, setState] = useState<SecretFormState>(() => ({
113118 name: suggestedName,
114119 value: "",
115− idOverride: null,
120+ idOverride: initialIdOverride ?? null,
116121 provider: initialProvider,
117122 revealed: false,
118123 status: { kind: "idle" },
scripts/agent-config-smoke.ts+340−0
@@ -0,0 +1,340 @@
1+#!/usr/bin/env bun
2+/**
3+ * End-to-end smoke for agent-driven Executor configuration.
4+ *
5+ * This intentionally drives the public dev CLI for agent actions, while using
6+ * the local HTTP browser/API boundary for sensitive values and OAuth callback
7+ * completion. Fake test credentials are used, but the shape matches the real
8+ * flow: agents get handoff URLs, users/browsers enter secrets and complete
9+ * OAuth outside the context window, then agents verify and bind the resulting
10+ * ids.
11+ */
12+import { mkdtemp, mkdir, rm } from "node:fs/promises";
13+import { tmpdir } from "node:os";
14+import { dirname, join, resolve } from "node:path";
15+import { fileURLToPath } from "node:url";
16+
17+import { serveOAuthTestServer, type OAuthTestServerShape } from "../packages/core/sdk/src/testing";
18+import {
19+ type GraphqlTestServerShape,
20+ makeGreetingGraphqlSchema,
21+ serveGraphqlTestServer,
22+} from "../packages/plugins/graphql/src/testing/index";
23+import { Effect } from "effect";
24+
25+const repoRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
26+const cliEntrypoint = join(repoRoot, "apps/cli/src/main.ts");
27+
28+type CliContext = {
29+ readonly dataDir: string;
30+ readonly scopeDir: string;
31+ readonly baseUrl: string;
32+};
33+
34+type CliResult = {
35+ readonly stdout: string;
36+ readonly stderr: string;
37+ readonly text: string;
38+ readonly exitCode: number;
39+};
40+
41+const assert = (condition: unknown, message: string): asserts condition => {
42+ if (!condition) throw new Error(message);
43+};
44+
45+const runCli = async (
46+ ctx: CliContext,
47+ args: readonly string[],
48+ options: { readonly allowFailure?: boolean } = {},
49+): Promise<CliResult> => {
50+ const proc = Bun.spawn([process.execPath, "run", cliEntrypoint, ...args], {
51+ cwd: repoRoot,
52+ env: {
53+ ...process.env,
54+ EXECUTOR_DEV: "1",
55+ EXECUTOR_DATA_DIR: ctx.dataDir,
56+ EXECUTOR_SCOPE_DIR: ctx.scopeDir,
57+ },
58+ stdout: "pipe",
59+ stderr: "pipe",
60+ });
61+
62+ const [stdout, stderr, exitCode] = await Promise.all([
63+ new Response(proc.stdout).text(),
64+ new Response(proc.stderr).text(),
65+ proc.exited,
66+ ]);
67+ const result = { stdout, stderr, text: `${stdout}${stderr}`, exitCode };
68+
69+ if (exitCode !== 0 && !options.allowFailure) {
70+ throw new Error(`CLI failed (${exitCode}) for ${args.join(" ")}\n${result.text}`);
71+ }
72+
73+ return result;
74+};
75+
76+const parseJsonOutput = <T>(result: CliResult): T => {
77+ const start = result.stdout.indexOf("{");
78+ const end = result.stdout.lastIndexOf("}");
79+ assert(start >= 0 && end > start, `CLI output did not contain JSON:\n${result.text}`);
80+ return JSON.parse(result.stdout.slice(start, end + 1)) as T;
81+};
82+
83+const toolData = <T>(value: unknown): T => {
84+ const result = value as { readonly ok?: boolean; readonly data?: T; readonly error?: unknown };
85+ assert(result.ok === true, `Tool returned failure: ${JSON.stringify(value)}`);
86+ return result.data as T;
87+};
88+
89+const extractExecutionId = (text: string): string => {
90+ const match = /executionId:\s*(exec_[A-Za-z0-9_]+)/.exec(text);
91+ assert(match?.[1], `CLI output did not contain an execution id:\n${text}`);
92+ return match[1];
93+};
94+
95+const callTool = (ctx: CliContext, path: readonly string[], args: unknown = {}) =>
96+ runCli(ctx, [
97+ "call",
98+ ...path,
99+ JSON.stringify(args),
100+ "--base-url",
101+ ctx.baseUrl,
102+ "--scope",
103+ ctx.scopeDir,
104+ ]);
105+
106+const approvePausedCall = async (ctx: CliContext, paused: CliResult): Promise<CliResult> => {
107+ const executionId = extractExecutionId(paused.text);
108+ return await runCli(ctx, [
109+ "resume",
110+ "--execution-id",
111+ executionId,
112+ "--base-url",
113+ ctx.baseUrl,
114+ "--scope",
115+ ctx.scopeDir,
116+ ]);
117+};
118+
119+const postJson = async (url: string, payload: unknown): Promise<unknown> => {
120+ const response = await fetch(url, {
121+ method: "POST",
122+ headers: { "content-type": "application/json" },
123+ body: JSON.stringify(payload),
124+ });
125+ const bodyText = await response.text();
126+ if (!response.ok) {
127+ throw new Error(`POST ${url} failed with HTTP ${response.status}: ${bodyText}`);
128+ }
129+ return bodyText.length > 0 ? JSON.parse(bodyText) : null;
130+};
131+
132+const firstScope = (value: unknown): { readonly id: string; readonly name: string } => {
133+ const data = toolData<{
134+ readonly scopes: readonly { readonly id: string; readonly name: string }[];
135+ }>(value);
136+ const scopes = data.scopes;
137+ const scope = scopes?.[0];
138+ assert(scope, `scopes.list returned no scopes: ${JSON.stringify(value)}`);
139+ return scope;
140+};
141+
142+const createSecretPlaceholder = async (
143+ ctx: CliContext,
144+ scope: string,
145+ expectedHandoffScope: string,
146+ name: string,
147+) => {
148+ const result = toolData<{ readonly id: string; readonly url: string }>(
149+ parseJsonOutput(
150+ await callTool(ctx, ["executor", "coreTools", "secrets", "create"], { name, scope }),
151+ ),
152+ );
153+ const handoff = new URL(result.url);
154+ assert(handoff.pathname === "/secrets", `Expected /secrets handoff URL, got ${result.url}`);
155+ assert(
156+ handoff.searchParams.get("scope") === expectedHandoffScope,
157+ `Secret handoff omitted scope: ${result.url}`,
158+ );
159+ return result;
160+};
161+
162+const setSecretViaBrowserBoundary = async (
163+ ctx: CliContext,
164+ browserBaseUrl: string,
165+ scopeId: string,
166+ input: { readonly id: string; readonly name: string; readonly value: string },
167+) => {
168+ await postJson(`${browserBaseUrl}/api/scopes/${encodeURIComponent(scopeId)}/secrets`, input);
169+ const status = toolData<{ readonly status: "resolved" | "missing" }>(
170+ parseJsonOutput(
171+ await callTool(ctx, ["executor", "coreTools", "secrets", "status"], { id: input.id }),
172+ ),
173+ );
174+ assert(status.status === "resolved", `Secret ${input.id} was not resolved`);
175+};
176+
177+const runSmoke = async (oauth: OAuthTestServerShape, graph: GraphqlTestServerShape) => {
178+ const root = await mkdtemp(join(tmpdir(), "executor-agent-config-smoke-"));
179+ const ctx: CliContext = {
180+ dataDir: join(root, "data"),
181+ scopeDir: join(root, "scope"),
182+ baseUrl: `http://127.0.0.1:${64180 + Math.floor(Math.random() * 1000)}`,
183+ };
184+ await mkdir(ctx.dataDir, { recursive: true });
185+ await mkdir(ctx.scopeDir, { recursive: true });
186+
187+ try {
188+ console.log("[agent-config-smoke] start dev CLI daemon");
189+ const port = new URL(ctx.baseUrl).port;
190+ await runCli(ctx, ["daemon", "run", "--port", port, "--scope", ctx.scopeDir]);
191+
192+ console.log("[agent-config-smoke] discover scope");
193+ const scope = firstScope(
194+ parseJsonOutput(await callTool(ctx, ["executor", "coreTools", "scopes", "list"])),
195+ );
196+
197+ console.log("[agent-config-smoke] create browser secret handoffs");
198+ const clientId = await createSecretPlaceholder(ctx, ctx.scopeDir, scope.id, "OAuth client id");
199+ const clientSecret = await createSecretPlaceholder(
200+ ctx,
201+ ctx.scopeDir,
202+ scope.id,
203+ "OAuth client secret",
204+ );
205+ const browserBaseUrl = new URL(clientId.url).origin;
206+ await setSecretViaBrowserBoundary(ctx, browserBaseUrl, scope.id, {
207+ id: clientId.id,
208+ name: "OAuth client id",
209+ value: "test-client",
210+ });
211+ await setSecretViaBrowserBoundary(ctx, browserBaseUrl, scope.id, {
212+ id: clientSecret.id,
213+ name: "OAuth client secret",
214+ value: "test-secret",
215+ });
216+
217+ console.log("[agent-config-smoke] start OAuth handoff through core tool");
218+ const oauthStart = toolData<{
219+ readonly sessionId: string;
220+ readonly authorizationUrl: string | null;
221+ }>(
222+ parseJsonOutput(
223+ await callTool(ctx, ["executor", "coreTools", "oauth", "start"], {
224+ scope: ctx.scopeDir,
225+ endpoint: oauth.resourceUrl,
226+ connectionId: "agent-smoke-oauth",
227+ pluginId: "graphql",
228+ identityLabel: "Agent Smoke OAuth",
229+ strategy: {
230+ kind: "authorization-code",
231+ authorizationEndpoint: oauth.authorizationEndpoint,
232+ tokenEndpoint: oauth.tokenEndpoint,
233+ clientIdSecretId: clientId.id,
234+ clientSecretSecretId: clientSecret.id,
235+ scopes: ["read"],
236+ },
237+ }),
238+ ),
239+ );
240+ assert(oauthStart.authorizationUrl, "OAuth start did not return an authorization URL");
241+
242+ console.log("[agent-config-smoke] complete OAuth callback through browser URL");
243+ const callback = await Effect.runPromise(
244+ oauth.completeAuthorizationCodeFlow({
245+ authorizationUrl: oauthStart.authorizationUrl,
246+ }),
247+ );
248+ const callbackResponse = await fetch(callback.callbackUrl);
249+ const callbackHtml = await callbackResponse.text();
250+ assert(callbackResponse.ok, `OAuth callback failed: ${callbackHtml}`);
251+ assert(
252+ callbackHtml.includes("Authentication complete"),
253+ "OAuth callback did not render success",
254+ );
255+
256+ const callbackBaseUrl = new URL(callback.callbackUrl).origin;
257+ const pollResponse = await fetch(
258+ `${callbackBaseUrl}/api/oauth/await/${encodeURIComponent(callback.state)}`,
259+ );
260+ const pollResult = (await pollResponse.json()) as { readonly ok?: boolean };
261+ assert(pollResult.ok === true, `OAuth await result was not ok: ${JSON.stringify(pollResult)}`);
262+
263+ const connections = toolData<{
264+ readonly connections: readonly { readonly id: string }[];
265+ }>(parseJsonOutput(await callTool(ctx, ["executor", "coreTools", "connections", "list"])));
266+ assert(
267+ connections.connections.some((connection) => connection.id === "agent-smoke-oauth"),
268+ `OAuth connection was not listed: ${JSON.stringify(connections)}`,
269+ );
270+
271+ console.log("[agent-config-smoke] add OAuth-backed GraphQL source through approval flow");
272+ const addSource = await approvePausedCall(
273+ ctx,
274+ await callTool(ctx, ["executor", "graphql", "addSource"], {
275+ scope: ctx.scopeDir,
276+ endpoint: graph.endpoint,
277+ name: "Agent Smoke GraphQL",
278+ namespace: "agent_smoke_graphql",
279+ oauth2: {
280+ kind: "oauth2",
281+ securitySchemeName: "OAuth2",
282+ flow: "authorizationCode",
283+ tokenUrl: oauth.tokenEndpoint,
284+ authorizationUrl: oauth.authorizationEndpoint,
285+ clientIdSlot: "auth:oauth2:client-id",
286+ clientSecretSlot: null,
287+ connectionSlot: "auth:oauth2:connection",
288+ scopes: ["read"],
289+ },
290+ credentials: {
291+ scope: scope.id,
292+ auth: {
293+ oauth2: {
294+ connection: { kind: "connection", connectionId: "agent-smoke-oauth" },
295+ },
296+ },
297+ },
298+ }),
299+ );
300+ const added = parseJsonOutput<{ readonly ok: boolean }>(addSource);
301+ assert(added.ok === true, `GraphQL addSource failed: ${addSource.text}`);
302+
303+ console.log("[agent-config-smoke] invoke configured OAuth-backed tool");
304+ const invoked = parseJsonOutput<{ readonly ok: boolean; readonly data?: unknown }>(
305+ await callTool(ctx, ["agent_smoke_graphql", "query", "hello"], { name: "Ada" }),
306+ );
307+ assert(
308+ invoked.ok === true &&
309+ JSON.stringify(invoked.data) === JSON.stringify({ hello: "Hello Ada" }),
310+ `GraphQL invocation failed: ${JSON.stringify(invoked)}`,
311+ );
312+
313+ console.log("[agent-config-smoke] passed");
314+ } finally {
315+ await runCli(ctx, ["daemon", "stop", "--base-url", ctx.baseUrl], {
316+ allowFailure: true,
317+ });
318+ await rm(root, { recursive: true, force: true });
319+ }
320+};
321+
322+const main = async () => {
323+ await Effect.runPromise(
324+ Effect.scoped(
325+ Effect.gen(function* () {
326+ const oauth = yield* serveOAuthTestServer();
327+ const graph = yield* serveGraphqlTestServer({
328+ schema: makeGreetingGraphqlSchema(),
329+ auth: {
330+ validateAuthorization: oauth.acceptsAuthorizationHeader,
331+ wwwAuthenticate: `Bearer resource_metadata="${oauth.protectedResourceMetadataUrl}/graphql"`,
332+ },
333+ });
334+ yield* Effect.promise(() => runSmoke(oauth, graph));
335+ }),
336+ ),
337+ );
338+};
339+
340+await main();

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t