History

feat(v2): add mcp/graphql sources and cloudflare runtime wiring

Rhys Sullivan committed 8 months ago

Commit e0ea8b41 parent 06e173056 files · +2688 −739Browse files

Unified · Split

56 files
  1. .env.example +15 −0
  2. executor/scripts/workos-vault/latency.ts +146 −0
  3. executor/scripts/workos-vault/read.ts +55 −0
  4. executor/scripts/workos-vault/shared.ts +172 −0
  5. executor/scripts/workos-vault/write.ts +60 −0
  6. package.json +3 −0
  7. v2/apps/convex/convex/_generated/api.d.ts +2 −0
  8. v2/apps/convex/convex/control_plane/actor.ts +61 −2
  9. v2/apps/convex/convex/control_plane/credentials.ts +217 −81
  10. v2/apps/convex/convex/control_plane/openapi_ingest.ts +2 −2
  11. v2/apps/convex/convex/control_plane/organizations.ts +38 −2
  12. v2/apps/convex/convex/control_plane/service.ts +1 −1
  13. v2/apps/convex/convex/control_plane/storage.ts +3 −3
  14. v2/apps/convex/convex/control_plane/workspaces.ts +2 −5
  15. v2/apps/convex/convex/credential_crypto.ts +102 −0
  16. v2/apps/convex/convex/credential_resolver.ts +32 −3
  17. v2/apps/convex/convex/executor.test.ts +100 −10
  18. v2/apps/convex/convex/mcp.ts +1 −5
  19. v2/apps/convex/convex/runtime_adapter.ts +2 −2
  20. v2/apps/convex/convex/runtime_execution_port.ts +7 −7
  21. v2/apps/convex/convex/source_tool_registry.ts +1 −1
  22. v2/apps/convex/package.json +3 −3
  23. v2/apps/pm/src/credentials-service.ts +7 −4
  24. v2/apps/pm/src/main.ts +7 −1
  25. v2/apps/pm/src/organizations-service.ts +41 −3
  26. v2/apps/pm/src/storage-service.test.ts +1 −1
  27. v2/apps/pm/src/storage-service.ts +3 −4
  28. v2/apps/pm/src/workspaces-service.ts +1 −4
  29. v2/apps/web/README.md +8 −3
  30. v2/apps/web/app/(console)/tools/page.tsx +24 −1
  31. v2/apps/web/app/api/control-plane/[...path]/route.ts +0 −314
  32. v2/apps/web/components/settings/settings-view.tsx +45 −17
  33. v2/apps/web/components/shell/app-shell.tsx +3 −11
  34. v2/apps/web/components/shell/workspace-selector.tsx +341 −182
  35. v2/apps/web/components/tools/tools-view.tsx +23 −4
  36. v2/apps/web/lib/control-plane/atoms/settings.ts +2 −2
  37. v2/apps/web/lib/control-plane/client.ts +13 −4
  38. v2/bun.lock +2 −1
  39. v2/packages/engine/package.json +1 −0
  40. v2/packages/engine/src/graphql-provider.test.ts +210 −0
  41. v2/packages/engine/src/graphql-provider.ts +195 −0
  42. v2/packages/engine/src/index.ts +2 −0
  43. v2/packages/engine/src/mcp-provider.test.ts +143 −0
  44. v2/packages/engine/src/mcp-provider.ts +389 −0
  45. v2/packages/engine/src/source-config.ts +143 −0
  46. v2/packages/management-api/src/auth/workspace-membership.ts +13 −15
  47. v2/packages/management-api/src/credentials/api.ts +7 −1
  48. v2/packages/management-api/src/organizations/api.ts +1 −1
  49. v2/packages/management-api/src/organizations/http.ts +15 −1
  50. v2/packages/management-api/src/workspaces/api.ts +2 −2
  51. v2/packages/management-api/src/workspaces/http.ts +8 −32
  52. v2/packages/runtime-cloudflare-worker-loader/src/index.ts +1 −1
  53. v2/packages/schema/src/enums.ts +4 −0
  54. v2/packages/schema/src/models/source-credential-binding.ts +6 −1
  55. v2/packages/schema/src/models/workspace.ts +1 −1
  56. v2/packages/state-local-file/src/state-store.test.ts +1 −1
.env.example+15−0
@@ -17,6 +17,14 @@ CONVEX_SITE_URL=https://your-deployment.convex.site · 16 unmodified lines
1717 # When enabled, local Bun execution is allowed.
1818 # Leave unset in production to default to Cloudflare runtime.
1919 # DANGEROUSLY_ALLOW_LOCAL_VM=1
20+# Secret encryption key for v2 Convex credential storage (required when using v2 Convex control plane)
21+# CREDENTIAL_ENCRYPTION_KEY=change-me-to-a-long-random-string
22+# Cloudflare worker loader runtime (required for v2 Convex code execution)
23+# CLOUDFLARE_SANDBOX_RUN_URL=http://127.0.0.1:8789/v1/runs
24+# CLOUDFLARE_SANDBOX_AUTH_TOKEN=sandbox-token
25+# CLOUDFLARE_SANDBOX_CALLBACK_URL=http://127.0.0.1:8788/v1/runtime/tool-call
26+# Optional callback signature secret:
27+# CLOUDFLARE_SANDBOX_CALLBACK_SECRET=change-me
2028
2129 # ── Agent storage backend (optional) ──
2230 # Default: agentfs-local
@@ -38,6 +46,13 @@ CONVEX_SITE_URL=https://your-deployment.convex.site · 15 unmodified lines
3846 # WORKOS_COOKIE_PASSWORD=<32+ char random string, e.g. openssl rand -base64 32>
3947 # WORKOS_WEBHOOK_SECRET=...
4048 # WORKOS_FORCE_ENABLED=1
49+# WorkOS Vault script helpers (optional):
50+# WORKOS_VAULT_OBJECT_ID=secret_...
51+# WORKOS_VAULT_CONTEXT_JSON={"workspace_id":"local"}
52+# WORKOS_VAULT_ITERATIONS=10
53+# WORKOS_VAULT_WARMUP_ITERATIONS=1
54+# WORKOS_VAULT_VALUE_BYTES=256
55+# WORKOS_VAULT_DELETE_AFTER=1
4156
4257 # ── Anonymous JWT Auth (optional — enables anonymous bearer auth via Convex Auth) ──
4358 # Generate an ES256 key pair (PKCS8 private + SPKI public), then set both PEM values.
executor/scripts/workos-vault/latency.ts+146−0
@@ -0,0 +1,146 @@
1+#!/usr/bin/env bun
2+
3+import {
4+ buildObjectName,
5+ buildRandomValue,
6+ formatMs,
7+ getArg,
8+ hasFlag,
9+ measureLatency,
10+ printStats,
11+ readBoolean,
12+ readEnv,
13+ readInt,
14+ resolveContext,
15+ resolveWorkosClient,
16+} from "./shared";
17+
18+function printHelp(): void {
19+ console.log("Measure WorkOS Vault write and read latency.");
20+ console.log("");
21+ console.log("Usage:");
22+ console.log(" bun run executor/scripts/workos-vault/latency.ts [--iterations <n>] [--warmup <n>] [--object-id <id>] [--value-bytes <n>] [--no-delete]");
23+ console.log("");
24+ console.log("Env:");
25+ console.log(" WORKOS_API_KEY Required");
26+ console.log(" WORKOS_VAULT_OBJECT_ID Optional existing object id");
27+ console.log(" WORKOS_VAULT_CONTEXT_JSON Optional JSON object for create context");
28+ console.log(" WORKOS_VAULT_ITERATIONS Optional, default 10");
29+ console.log(" WORKOS_VAULT_WARMUP_ITERATIONS Optional, default 1");
30+ console.log(" WORKOS_VAULT_VALUE_BYTES Optional, default 256");
31+ console.log(" WORKOS_VAULT_DELETE_AFTER Optional, default true");
32+}
33+
34+async function main(): Promise<void> {
35+ if (hasFlag("help")) {
36+ printHelp();
37+ return;
38+ }
39+
40+ const workos = resolveWorkosClient();
41+
42+ const iterations = Math.max(
43+ 1,
44+ readInt(getArg("iterations") ?? readEnv("WORKOS_VAULT_ITERATIONS"), 10),
45+ );
46+ const warmupIterations = Math.max(
47+ 0,
48+ readInt(getArg("warmup") ?? readEnv("WORKOS_VAULT_WARMUP_ITERATIONS"), 1),
49+ );
50+ const valueBytes = Math.max(
51+ 16,
52+ readInt(getArg("value-bytes") ?? readEnv("WORKOS_VAULT_VALUE_BYTES"), 256),
53+ );
54+ const context = resolveContext(readEnv("WORKOS_VAULT_CONTEXT_JSON"));
55+
56+ const shouldDeleteAfter = hasFlag("no-delete")
57+ ? false
58+ : readBoolean(readEnv("WORKOS_VAULT_DELETE_AFTER"), true);
59+
60+ const providedObjectId = getArg("object-id") ?? readEnv("WORKOS_VAULT_OBJECT_ID");
61+
62+ let objectId = providedObjectId;
63+ let createdObject = false;
64+
65+ if (!objectId) {
66+ const initialValue = buildRandomValue(valueBytes);
67+ const objectName = buildObjectName("executor-vault-latency");
68+ const created = await workos.vault.createObject({
69+ name: objectName,
70+ value: initialValue,
71+ context,
72+ });
73+ objectId = created.id;
74+ createdObject = true;
75+ }
76+
77+ if (!objectId) {
78+ throw new Error("Failed to resolve a WorkOS Vault object id");
79+ }
80+
81+ const writeLatencies: number[] = [];
82+ const readLatencies: number[] = [];
83+ const roundtripLatencies: number[] = [];
84+
85+ for (let i = 0; i < warmupIterations; i += 1) {
86+ const value = buildRandomValue(valueBytes);
87+ await workos.vault.updateObject({
88+ id: objectId,
89+ value,
90+ });
91+ await workos.vault.readObject({
92+ id: objectId,
93+ });
94+ }
95+
96+ for (let i = 0; i < iterations; i += 1) {
97+ const value = buildRandomValue(valueBytes);
98+ const roundtripStartedAt = performance.now();
99+
100+ const writeResult = await measureLatency(() =>
101+ workos.vault.updateObject({
102+ id: objectId,
103+ value,
104+ })
105+ );
106+ const readResult = await measureLatency(() =>
107+ workos.vault.readObject({
108+ id: objectId,
109+ })
110+ );
111+
112+ const readValue = typeof readResult.value.value === "string" ? readResult.value.value : "";
113+ if (readValue !== value) {
114+ throw new Error(`Read-back mismatch on iteration ${i + 1}`);
115+ }
116+
117+ writeLatencies.push(writeResult.durationMs);
118+ readLatencies.push(readResult.durationMs);
119+ roundtripLatencies.push(performance.now() - roundtripStartedAt);
120+ }
121+
122+ let cleanupLatencyMs: number | null = null;
123+ if (createdObject && shouldDeleteAfter) {
124+ const cleanup = await measureLatency(() =>
125+ workos.vault.deleteObject({
126+ id: objectId,
127+ })
128+ );
129+ cleanupLatencyMs = cleanup.durationMs;
130+ }
131+
132+ console.log("workos vault latency benchmark complete");
133+ console.log(`objectId: ${objectId}${createdObject ? " (created by script)" : " (provided)"}`);
134+ console.log(`iterations: ${iterations}`);
135+ console.log(`warmupIterations: ${warmupIterations}`);
136+ console.log(`valueBytes: ${valueBytes}`);
137+ console.log(`cleanup: ${createdObject ? (shouldDeleteAfter ? "deleted" : "kept") : "not-applicable"}`);
138+ if (cleanupLatencyMs !== null) {
139+ console.log(`cleanupLatency: ${formatMs(cleanupLatencyMs)}`);
140+ }
141+ printStats("write", writeLatencies);
142+ printStats("read", readLatencies);
143+ printStats("roundtrip", roundtripLatencies);
144+}
145+
146+await main();
executor/scripts/workos-vault/read.ts+55−0
@@ -0,0 +1,55 @@
1+#!/usr/bin/env bun
2+
3+import {
4+ formatMs,
5+ getArg,
6+ hasFlag,
7+ measureLatency,
8+ readEnv,
9+ resolveWorkosClient,
10+} from "./shared";
11+
12+function printHelp(): void {
13+ console.log("Read one object from WorkOS Vault and print latency.");
14+ console.log("");
15+ console.log("Usage:");
16+ console.log(" bun run executor/scripts/workos-vault/read.ts --object-id <id> [--show-value]");
17+ console.log("");
18+ console.log("Env:");
19+ console.log(" WORKOS_API_KEY Required");
20+ console.log(" WORKOS_VAULT_OBJECT_ID Required when --object-id is not provided");
21+}
22+
23+async function main(): Promise<void> {
24+ if (hasFlag("help")) {
25+ printHelp();
26+ return;
27+ }
28+
29+ const workos = resolveWorkosClient();
30+ const objectId = getArg("object-id") ?? readEnv("WORKOS_VAULT_OBJECT_ID");
31+ if (!objectId) {
32+ throw new Error("Missing object id. Pass --object-id <id> or set WORKOS_VAULT_OBJECT_ID.");
33+ }
34+
35+ const { value: object, durationMs } = await measureLatency(() =>
36+ workos.vault.readObject({
37+ id: objectId,
38+ })
39+ );
40+
41+ const value = typeof object.value === "string" ? object.value : "";
42+ const showValue = hasFlag("show-value");
43+
44+ console.log("workos vault read complete");
45+ console.log(`objectId: ${object.id}`);
46+ console.log(`name: ${object.name}`);
47+ console.log(`valueLength: ${value.length}`);
48+ console.log(`latency: ${formatMs(durationMs)}`);
49+
50+ if (showValue) {
51+ console.log(`value: ${value}`);
52+ }
53+}
54+
55+await main();
executor/scripts/workos-vault/shared.ts+172−0
@@ -0,0 +1,172 @@
1+import { WorkOS } from "@workos-inc/node";
2+
3+export interface LatencyStats {
4+ minMs: number;
5+ p50Ms: number;
6+ p95Ms: number;
7+ maxMs: number;
8+ avgMs: number;
9+}
10+
11+export function getArg(name: string): string | undefined {
12+ const prefixed = `--${name}=`;
13+ for (const arg of process.argv.slice(2)) {
14+ if (arg.startsWith(prefixed)) {
15+ return arg.slice(prefixed.length);
16+ }
17+ }
18+
19+ const exact = `--${name}`;
20+ const index = process.argv.indexOf(exact);
21+ if (index === -1) {
22+ return undefined;
23+ }
24+
25+ const next = process.argv[index + 1];
26+ if (!next || next.startsWith("--")) {
27+ return undefined;
28+ }
29+
30+ return next;
31+}
32+
33+export function hasFlag(name: string): boolean {
34+ const exact = `--${name}`;
35+ return process.argv.includes(exact);
36+}
37+
38+export function readEnv(name: string): string | undefined {
39+ const value = process.env[name];
40+ if (!value) {
41+ return undefined;
42+ }
43+
44+ const trimmed = value.trim();
45+ return trimmed.length > 0 ? trimmed : undefined;
46+}
47+
48+export function readRequiredEnv(name: string): string {
49+ const value = readEnv(name);
50+ if (!value) {
51+ throw new Error(`Missing required env var: ${name}`);
52+ }
53+ return value;
54+}
55+
56+export function readInt(value: string | undefined, fallback: number): number {
57+ if (!value) {
58+ return fallback;
59+ }
60+
61+ const parsed = Number.parseInt(value, 10);
62+ if (!Number.isFinite(parsed)) {
63+ return fallback;
64+ }
65+
66+ return parsed;
67+}
68+
69+export function readBoolean(value: string | undefined, fallback: boolean): boolean {
70+ if (!value) {
71+ return fallback;
72+ }
73+
74+ const normalized = value.trim().toLowerCase();
75+ if (["1", "true", "yes", "on"].includes(normalized)) {
76+ return true;
77+ }
78+
79+ if (["0", "false", "no", "off"].includes(normalized)) {
80+ return false;
81+ }
82+
83+ return fallback;
84+}
85+
86+export function resolveContext(raw: string | undefined): Record<string, unknown> {
87+ if (!raw) {
88+ return { workspace_id: "local" };
89+ }
90+
91+ let parsed: unknown;
92+ try {
93+ parsed = JSON.parse(raw);
94+ } catch (error) {
95+ throw new Error(`Failed to parse context JSON: ${error instanceof Error ? error.message : String(error)}`);
96+ }
97+
98+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
99+ throw new Error("WORKOS_VAULT_CONTEXT_JSON must be a JSON object");
100+ }
101+
102+ return parsed as Record<string, unknown>;
103+}
104+
105+export function resolveWorkosClient(): WorkOS {
106+ const apiKey = readRequiredEnv("WORKOS_API_KEY");
107+ return new WorkOS(apiKey);
108+}
109+
110+export async function measureLatency<T>(operation: () => Promise<T>): Promise<{ value: T; durationMs: number }> {
111+ const startedAt = performance.now();
112+ const value = await operation();
113+ const durationMs = performance.now() - startedAt;
114+ return { value, durationMs };
115+}
116+
117+function percentile(sortedValues: readonly number[], quantile: number): number {
118+ if (sortedValues.length === 0) {
119+ return 0;
120+ }
121+
122+ const normalized = Math.min(1, Math.max(0, quantile));
123+ const index = Math.ceil(sortedValues.length * normalized) - 1;
124+ const clampedIndex = Math.min(sortedValues.length - 1, Math.max(0, index));
125+ return sortedValues[clampedIndex] ?? 0;
126+}
127+
128+export function computeStats(samples: readonly number[]): LatencyStats {
129+ if (samples.length === 0) {
130+ return {
131+ minMs: 0,
132+ p50Ms: 0,
133+ p95Ms: 0,
134+ maxMs: 0,
135+ avgMs: 0,
136+ };
137+ }
138+
139+ const sorted = [...samples].sort((a, b) => a - b);
140+ const sum = sorted.reduce((total, value) => total + value, 0);
141+
142+ return {
143+ minMs: sorted[0] ?? 0,
144+ p50Ms: percentile(sorted, 0.5),
145+ p95Ms: percentile(sorted, 0.95),
146+ maxMs: sorted[sorted.length - 1] ?? 0,
147+ avgMs: sum / sorted.length,
148+ };
149+}
150+
151+export function formatMs(value: number): string {
152+ return `${value.toFixed(2)}ms`;
153+}
154+
155+export function buildObjectName(prefix: string): string {
156+ return `${prefix}-${Date.now()}-${crypto.randomUUID().slice(0, 8)}`;
157+}
158+
159+export function buildRandomValue(byteLength: number): string {
160+ const target = Math.max(16, byteLength);
161+ const suffix = crypto.randomUUID();
162+ const head = `bench-${Date.now()}-${suffix}-`;
163+ const fillerLength = Math.max(0, target - head.length);
164+ return `${head}${"x".repeat(fillerLength)}`;
165+}
166+
167+export function printStats(label: string, samples: readonly number[]): void {
168+ const stats = computeStats(samples);
169+ console.log(
170+ `${label}: min=${formatMs(stats.minMs)} p50=${formatMs(stats.p50Ms)} p95=${formatMs(stats.p95Ms)} max=${formatMs(stats.maxMs)} avg=${formatMs(stats.avgMs)}`,
171+ );
172+}
executor/scripts/workos-vault/write.ts+60−0
@@ -0,0 +1,60 @@
1+#!/usr/bin/env bun
2+
3+import {
4+ buildObjectName,
5+ buildRandomValue,
6+ formatMs,
7+ getArg,
8+ hasFlag,
9+ measureLatency,
10+ readEnv,
11+ resolveContext,
12+ resolveWorkosClient,
13+} from "./shared";
14+
15+function printHelp(): void {
16+ console.log("Write one object to WorkOS Vault and print latency.");
17+ console.log("");
18+ console.log("Usage:");
19+ console.log(" bun run executor/scripts/workos-vault/write.ts [--name <name>] [--value <secret>] [--context-json <json>]");
20+ console.log("");
21+ console.log("Env:");
22+ console.log(" WORKOS_API_KEY Required");
23+ console.log(" WORKOS_VAULT_OBJECT_NAME Optional object name");
24+ console.log(" WORKOS_VAULT_SECRET_VALUE Optional secret value");
25+ console.log(" WORKOS_VAULT_CONTEXT_JSON Optional JSON object (default: {\"workspace_id\":\"local\"})");
26+}
27+
28+async function main(): Promise<void> {
29+ if (hasFlag("help")) {
30+ printHelp();
31+ return;
32+ }
33+
34+ const workos = resolveWorkosClient();
35+
36+ const name = getArg("name")
37+ ?? readEnv("WORKOS_VAULT_OBJECT_NAME")
38+ ?? buildObjectName("executor-vault-write");
39+ const value = getArg("value")
40+ ?? readEnv("WORKOS_VAULT_SECRET_VALUE")
41+ ?? buildRandomValue(256);
42+ const contextRaw = getArg("context-json") ?? readEnv("WORKOS_VAULT_CONTEXT_JSON");
43+ const context = resolveContext(contextRaw);
44+
45+ const { value: created, durationMs } = await measureLatency(() =>
46+ workos.vault.createObject({
47+ name,
48+ value,
49+ context,
50+ })
51+ );
52+
53+ console.log("workos vault write complete");
54+ console.log(`objectId: ${created.id}`);
55+ console.log(`name: ${name}`);
56+ console.log(`valueLength: ${value.length}`);
57+ console.log(`latency: ${formatMs(durationMs)}`);
58+}
59+
60+await main();
package.json+3−0
@@ -12,6 +12,9 @@ · 11 unmodified lines
1212 "scripts": {
1313 "with-env": "bun run --env-file=.env --",
1414 "dev": "bun run dev.ts",
15+ "workos:vault:write": "bun run with-env bun run executor/scripts/workos-vault/write.ts",
16+ "workos:vault:read": "bun run with-env bun run executor/scripts/workos-vault/read.ts",
17+ "workos:vault:latency": "bun run with-env bun run executor/scripts/workos-vault/latency.ts",
1518 "test": "bun run test:executor && bun run test:assistant",
1619 "test:executor": "bun run --cwd executor test",
1720 "test:executor:integration": "bun run --cwd executor test:integration",
v2/apps/convex/convex/_generated/api.d.ts+2−0
@@ -23,6 +23,7 @@ import type * as control_plane_storage from "../control_plane/storage.js"; · 22 unmodified lines
2323 import type * as control_plane_tool_registry from "../control_plane/tool_registry.js";
2424 import type * as control_plane_tools from "../control_plane/tools.js";
2525 import type * as control_plane_workspaces from "../control_plane/workspaces.js";
26+import type * as credential_crypto from "../credential_crypto.js";
2627 import type * as credential_resolver from "../credential_resolver.js";
2728 import type * as executor from "../executor.js";
2829 import type * as http from "../http.js";
@@ -58,6 +59,7 @@ declare const fullApi: ApiFromModules<{ · 29 unmodified lines
5859 "control_plane/tool_registry": typeof control_plane_tool_registry;
5960 "control_plane/tools": typeof control_plane_tools;
6061 "control_plane/workspaces": typeof control_plane_workspaces;
62+ credential_crypto: typeof credential_crypto;
6163 credential_resolver: typeof credential_resolver;
6264 executor: typeof executor;
6365 http: typeof http;
v2/apps/convex/convex/control_plane/actor.ts+61−2
@@ -33,6 +33,17 @@ const stripConvexSystemFields = ( · 32 unmodified lines
3333 return rest;
3434 };
3535
36+const toOrganizationSlug = (accountId: string): string => {
37+ const slug = accountId
38+ .trim()
39+ .toLowerCase()
40+ .replace(/[^a-z0-9]+/g, "-")
41+ .replace(/^-+/, "")
42+ .replace(/-+$/, "");
43+
44+ return slug.length > 0 ? `acct-${slug}` : `acct-${crypto.randomUUID().slice(0, 8)}`;
45+};
46+
3647 export const getWorkspaceForActor = internalQuery({
3748 args: {
3849 workspaceId: v.string(),
@@ -107,6 +118,49 @@ export const ensureWorkspaceForActor = internalMutation({ · 68 unmodified lines
107118 handler: async (ctx, args): Promise<Workspace> => {
108119 const now = Date.now();
109120
121+ const ensureOrganizationMembership = async (organizationId: string) => {
122+ const existingOrganization = await ctx.db
123+ .query("organizations")
124+ .withIndex("by_domainId", (q) => q.eq("id", organizationId))
125+ .first();
126+
127+ if (existingOrganization === null) {
128+ await ctx.db.insert("organizations", {
129+ id: organizationId,
130+ slug: toOrganizationSlug(args.accountId),
131+ name: `${args.accountId} Organization`,
132+ status: "active",
133+ createdByAccountId: args.accountId,
134+ createdAt: now,
135+ updatedAt: now,
136+ });
137+ }
138+
139+ const existingMembership = await ctx.db
140+ .query("organizationMemberships")
141+ .withIndex("by_organizationId_accountId", (q) =>
142+ q.eq("organizationId", organizationId).eq("accountId", args.accountId)
143+ )
144+ .first();
145+
146+ if (existingMembership !== null) {
147+ return;
148+ }
149+
150+ await ctx.db.insert("organizationMemberships", {
151+ id: `org_member_${crypto.randomUUID()}`,
152+ organizationId,
153+ accountId: args.accountId,
154+ role: "owner",
155+ status: "active",
156+ billable: false,
157+ invitedByAccountId: null,
158+ joinedAt: now,
159+ createdAt: now,
160+ updatedAt: now,
161+ });
162+ };
163+
110164 const existing = await ctx.db
111165 .query("workspaces")
112166 .withIndex("by_domainId", (q) => q.eq("id", args.workspaceId))
@@ -117,6 +171,8 @@ export const ensureWorkspaceForActor = internalMutation({ · 4 unmodified lines
117171 stripConvexSystemFields(existing as unknown as Record<string, unknown>),
118172 );
119173
174+ await ensureOrganizationMembership(existingWorkspace.organizationId);
175+
120176 if (existingWorkspace.createdByAccountId !== null) {
121177 return existingWorkspace;
122178 }
@@ -133,9 +189,12 @@ export const ensureWorkspaceForActor = internalMutation({ · 10 unmodified lines
133189 });
134190 }
135191
192+ const organizationId = `org_${args.accountId}`;
193+ await ensureOrganizationMembership(organizationId);
194+
136195 await ctx.db.insert("workspaces", {
137196 id: args.workspaceId,
138− organizationId: null,
197+ organizationId,
139198 name: args.workspaceId,
140199 createdByAccountId: args.accountId,
141200 createdAt: now,
@@ -144,7 +203,7 @@ export const ensureWorkspaceForActor = internalMutation({ · 2 unmodified lines
144203
145204 return decodeWorkspace({
146205 id: args.workspaceId,
147− organizationId: null,
206+ organizationId,
148207 name: args.workspaceId,
149208 createdByAccountId: args.accountId,
150209 createdAt: now,
v2/apps/convex/convex/control_plane/credentials.ts+217−81
@@ -12,7 +12,12 @@ import { · 11 unmodified lines
1212 import { v } from "convex/values";
1313 import * as Schema from "effect/Schema";
1414
15+import { internal } from "../_generated/api";
16+import { decryptSecretValue, encryptSecretValue } from "../credential_crypto";
1517 import {
18+ action,
19+ internalAction,
20+ internalMutation,
1621 internalQuery,
1722 mutation,
1823 query,
@@ -20,6 +25,8 @@ import { · 1 unmodified line
2025 type QueryCtx,
2126 } from "../_generated/server";
2227
28+const runtimeInternal = internal as any;
29+
2330 const decodeSourceCredentialBinding = Schema.decodeUnknownSync(
2431 SourceCredentialBindingSchema,
2532 );
@@ -44,12 +51,27 @@ const credentialProviderValidator = v.union( · 18 unmodified lines
4451 v.literal("custom"),
4552 );
4653
54+const credentialSecretProviderValidator = v.literal("local");
55+
4756 const credentialScopeTypeValidator = v.union(
4857 v.literal("workspace"),
4958 v.literal("organization"),
5059 v.literal("account"),
5160 );
5261
62+const sourceCredentialBindingPayloadValidator = v.object({
63+ id: v.optional(v.string()),
64+ credentialId: v.string(),
65+ scopeType: credentialScopeTypeValidator,
66+ sourceKey: v.string(),
67+ provider: credentialProviderValidator,
68+ secretProvider: v.optional(credentialSecretProviderValidator),
69+ secretRef: v.string(),
70+ accountId: v.optional(v.union(v.string(), v.null())),
71+ additionalHeadersJson: v.optional(v.union(v.string(), v.null())),
72+ boundAuthFingerprint: v.optional(v.union(v.string(), v.null())),
73+});
74+
5375 const sortSourceCredentialBindings = (
5476 bindings: ReadonlyArray<SourceCredentialBinding>,
5577 ): Array<SourceCredentialBinding> =>
@@ -73,11 +95,11 @@ const resolveWorkspaceOrganizationId = async ( · 17 unmodified lines
7395 .withIndex("by_domainId", (q) => q.eq("id", workspaceId))
7496 .unique();
7597
76− if (workspace?.organizationId !== null && workspace?.organizationId !== undefined) {
77− return workspace.organizationId;
98+ if (!workspace) {
99+ throw new Error(`Workspace not found: ${workspaceId}`);
78100 }
79101
80− return `org_${workspaceId}`;
102+ return workspace.organizationId;
81103 };
82104
83105 const canAccessSourceCredentialBinding = (
@@ -197,83 +219,162 @@ const selectBestIngestBinding = ( · 113 unmodified lines
197219 return ranked[0]?.binding ?? null;
198220 };
199221
200−export const resolveSourceCredentialHeadersForIngest = internalQuery({
222+const requireLocalSecretProvider = (
223+ secretProvider: SourceCredentialBinding["secretProvider"],
224+): "local" => {
225+ if (secretProvider !== "local") {
226+ throw new Error("Convex credentials require secretProvider 'local'");
227+ }
228+
229+ return "local";
230+};
231+
232+const defaultSecretProvider = (): "local" => "local";
233+
234+const resolveSecretRefForHeaders = async (
235+ binding: SourceCredentialBinding,
236+): Promise<string> => {
237+ requireLocalSecretProvider(binding.secretProvider);
238+ return await decryptSecretValue(binding.secretRef);
239+};
240+
241+const resolveIngestSelection = async (
242+ ctx: QueryCtx,
201243 args: {
202− workspaceId: v.string(),
203− sourceId: v.string(),
204− sourceName: v.string(),
205− sourceEndpoint: v.string(),
244+ workspaceId: string;
245+ sourceId: string;
246+ sourceName: string;
247+ sourceEndpoint: string;
206248 },
207− handler: async (ctx, args): Promise<{
208− headers: Record<string, string>;
209− }> => {
210− const organizationId = await resolveWorkspaceOrganizationId(ctx, args.workspaceId);
211− const sourceKeys = sourceKeyCandidatesForIngest({
212− sourceId: args.sourceId,
213− sourceName: args.sourceName,
214− sourceEndpoint: args.sourceEndpoint,
215− });
216−
217− const candidateRows = await Promise.all(
218− sourceKeys.map((sourceKey) =>
219− ctx.db
220− .query("sourceCredentialBindings")
221− .withIndex("by_sourceKey", (q) => q.eq("sourceKey", sourceKey))
222− .collect()
223− .then((rows) =>
224− rows.map((row) => ({
225− binding: toSourceCredentialBinding(row as unknown as Record<string, unknown>),
226− sourceKey,
227− })),
228− ),
229− ),
230− );
249+): Promise<{
250+ binding: SourceCredentialBinding | null;
251+ oauthAccessToken: string | null;
252+}> => {
253+ const organizationId = await resolveWorkspaceOrganizationId(ctx, args.workspaceId);
254+ const sourceKeys = sourceKeyCandidatesForIngest({
255+ sourceId: args.sourceId,
256+ sourceName: args.sourceName,
257+ sourceEndpoint: args.sourceEndpoint,
258+ });
231259
232− const flattened = candidateRows.flat();
233− const dedupedById = new Map<string, { binding: SourceCredentialBinding; sourceKey: string }>();
234− for (const candidate of flattened) {
235− if (!dedupedById.has(candidate.binding.id)) {
236− dedupedById.set(candidate.binding.id, candidate);
237− }
260+ const candidateRows = await Promise.all(
261+ sourceKeys.map((sourceKey) =>
262+ ctx.db
263+ .query("sourceCredentialBindings")
264+ .withIndex("by_sourceKey", (q) => q.eq("sourceKey", sourceKey))
265+ .collect()
266+ .then((rows) =>
267+ rows.map((row) => ({
268+ binding: toSourceCredentialBinding(row as unknown as Record<string, unknown>),
269+ sourceKey,
270+ })),
271+ ),
272+ ),
273+ );
274+
275+ const flattened = candidateRows.flat();
276+ const dedupedById = new Map<string, { binding: SourceCredentialBinding; sourceKey: string }>();
277+ for (const candidate of flattened) {
278+ if (!dedupedById.has(candidate.binding.id)) {
279+ dedupedById.set(candidate.binding.id, candidate);
238280 }
281+ }
239282
240− const sourceKeyRankByKey = new Map<string, number>();
241− sourceKeys.forEach((sourceKey, index) => {
242− sourceKeyRankByKey.set(sourceKey, sourceKeys.length - index);
243− });
283+ const sourceKeyRankByKey = new Map<string, number>();
284+ sourceKeys.forEach((sourceKey, index) => {
285+ sourceKeyRankByKey.set(sourceKey, sourceKeys.length - index);
286+ });
244287
245− const binding = selectBestIngestBinding(
246− [...dedupedById.values()].map((candidate) => ({
247− binding: candidate.binding,
248− sourceKeyRank: sourceKeyRankByKey.get(candidate.sourceKey) ?? 0,
249− })),
250− {
288+ const binding = selectBestIngestBinding(
289+ [...dedupedById.values()].map((candidate) => ({
290+ binding: candidate.binding,
291+ sourceKeyRank: sourceKeyRankByKey.get(candidate.sourceKey) ?? 0,
292+ })),
293+ {
294+ workspaceId: args.workspaceId,
295+ organizationId,
296+ },
297+ );
298+
299+ if (!binding || !canAccessSourceCredentialBinding(binding, { workspaceId: args.workspaceId, organizationId })) {
300+ return {
301+ binding: null,
302+ oauthAccessToken: null,
303+ };
304+ }
305+
306+ const oauthTokens = binding.provider === "oauth2"
307+ ? (await ctx.db
308+ .query("oauthTokens")
309+ .withIndex("by_sourceId", (q) => q.eq("sourceId", args.sourceId))
310+ .collect()).map((row) => toOAuthToken(row as unknown as Record<string, unknown>))
311+ : [];
312+
313+ const oauthAccessToken = binding.provider === "oauth2"
314+ ? selectOAuthAccessToken(oauthTokens, {
251315 workspaceId: args.workspaceId,
252316 organizationId,
253− },
254− );
317+ accountId: null,
318+ sourceKey: binding.sourceKey,
319+ }, args.sourceId)
320+ : null;
321+
322+ return {
323+ binding,
324+ oauthAccessToken,
325+ };
326+};
255327
256− if (!binding || !canAccessSourceCredentialBinding(binding, { workspaceId: args.workspaceId, organizationId })) {
257− return { headers: {} };
258− }
328+const withDecryptedSecret = async (
329+ binding: SourceCredentialBinding,
330+): Promise<SourceCredentialBinding> => {
331+ const secretRef = await resolveSecretRefForHeaders(binding);
332+ return {
333+ ...binding,
334+ secretProvider: "local",
335+ secretRef,
336+ };
337+};
259338
260− const oauthTokens = binding.provider === "oauth2"
261− ? (await ctx.db
262− .query("oauthTokens")
263− .withIndex("by_sourceId", (q) => q.eq("sourceId", args.sourceId))
264− .collect()).map((row) => toOAuthToken(row as unknown as Record<string, unknown>))
265− : [];
339+export const resolveSourceCredentialSelectionForIngest = internalQuery({
340+ args: {
341+ workspaceId: v.string(),
342+ sourceId: v.string(),
343+ sourceName: v.string(),
344+ sourceEndpoint: v.string(),
345+ },
346+ handler: async (ctx, args) => resolveIngestSelection(ctx, args),
347+});
266348
267− const oauthAccessToken = binding.provider === "oauth2"
268− ? selectOAuthAccessToken(oauthTokens, {
269− workspaceId: args.workspaceId,
270− organizationId,
271− accountId: null,
272− sourceKey: binding.sourceKey,
273− }, args.sourceId)
274− : null;
349+export const resolveSourceCredentialHeadersForIngest = internalAction({
350+ args: {
351+ workspaceId: v.string(),
352+ sourceId: v.string(),
353+ sourceName: v.string(),
354+ sourceEndpoint: v.string(),
355+ },
356+ handler: async (ctx, args): Promise<{
357+ headers: Record<string, string>;
358+ }> => {
359+ const selected = await ctx.runQuery(
360+ runtimeInternal.control_plane.credentials.resolveSourceCredentialSelectionForIngest,
361+ args,
362+ ) as {
363+ binding: SourceCredentialBinding | null;
364+ oauthAccessToken: string | null;
365+ };
366+
367+ if (!selected.binding) {
368+ return {
369+ headers: {},
370+ };
371+ }
275372
276− const headers = buildCredentialHeaders(binding, { oauthAccessToken });
373+ const decrypted = await withDecryptedSecret(selected.binding);
374+
375+ const headers = buildCredentialHeaders(decrypted, {
376+ oauthAccessToken: selected.oauthAccessToken,
377+ });
277378
278379 return { headers };
279380 },
@@ -311,24 +412,18 @@ export const listCredentialBindings = query({ · 31 unmodified lines
311412 new Map(bindings.map((binding) => [binding.id, binding])).values(),
312413 );
313414
314− return sortSourceCredentialBindings(uniqueBindings);
415+ const decryptedBindings = await Promise.all(
416+ uniqueBindings.map((binding) => withDecryptedSecret(binding)),
417+ );
418+
419+ return sortSourceCredentialBindings(decryptedBindings);
315420 },
316421 });
317422
318−export const upsertCredentialBinding = mutation({
423+export const upsertCredentialBindingRecord = internalMutation({
319424 args: {
320425 workspaceId: v.string(),
321− payload: v.object({
322− id: v.optional(v.string()),
323− credentialId: v.string(),
324− scopeType: credentialScopeTypeValidator,
325− sourceKey: v.string(),
326− provider: credentialProviderValidator,
327− secretRef: v.string(),
328− accountId: v.optional(v.union(v.string(), v.null())),
329− additionalHeadersJson: v.optional(v.union(v.string(), v.null())),
330− boundAuthFingerprint: v.optional(v.union(v.string(), v.null())),
331− }),
426+ payload: sourceCredentialBindingPayloadValidator,
332427 },
333428 handler: async (ctx, args): Promise<SourceCredentialBinding> => {
334429 const payload = args.payload as UpsertCredentialBindingPayload;
@@ -360,6 +455,12 @@ export const upsertCredentialBinding = mutation({ · 25 unmodified lines
360455 throw new Error(`Credential binding not found: ${bindingId}`);
361456 }
362457
458+ const secretProvider = requireLocalSecretProvider(
459+ payload.secretProvider
460+ ?? existingBinding?.secretProvider
461+ ?? defaultSecretProvider(),
462+ );
463+
363464 const nextBinding = decodeSourceCredentialBinding({
364465 id: bindingId,
365466 credentialId: payload.credentialId,
@@ -369,6 +470,7 @@ export const upsertCredentialBinding = mutation({ · 3 unmodified lines
369470 scopeType: payload.scopeType,
370471 sourceKey: payload.sourceKey,
371472 provider: payload.provider,
473+ secretProvider,
372474 secretRef: payload.secretRef,
373475 additionalHeadersJson: payload.additionalHeadersJson ?? null,
374476 boundAuthFingerprint: payload.boundAuthFingerprint ?? null,
@@ -386,6 +488,40 @@ export const upsertCredentialBinding = mutation({ · 11 unmodified lines
386488 },
387489 });
388490
491+export const upsertCredentialBinding = action({
492+ args: {
493+ workspaceId: v.string(),
494+ payload: sourceCredentialBindingPayloadValidator,
495+ },
496+ handler: async (ctx, args): Promise<SourceCredentialBinding> => {
497+ const payload = args.payload as UpsertCredentialBindingPayload;
498+ const requestedSecretRef = payload.secretRef.trim();
499+ if (requestedSecretRef.length === 0) {
500+ throw new Error("Credential secret is required");
501+ }
502+
503+ const encryptedSecretRef = await encryptSecretValue(requestedSecretRef);
504+
505+ const written = await ctx.runMutation(
506+ runtimeInternal.control_plane.credentials.upsertCredentialBindingRecord,
507+ {
508+ workspaceId: args.workspaceId,
509+ payload: {
510+ ...payload,
511+ secretProvider: "local",
512+ secretRef: encryptedSecretRef,
513+ },
514+ },
515+ ) as SourceCredentialBinding;
516+
517+ return {
518+ ...written,
519+ secretProvider: "local",
520+ secretRef: requestedSecretRef,
521+ };
522+ },
523+});
524+
389525 export const removeCredentialBinding = mutation({
390526 args: {
391527 workspaceId: v.string(),
v2/apps/convex/convex/control_plane/openapi_ingest.ts+2−2
@@ -1049,7 +1049,7 @@ const ingestGraphqlSource = ( · 1048 unmodified lines
10491049 headers: Record<string, string>;
10501050 }>(
10511051 () =>
1052− ctx.runQuery(runtimeInternal.control_plane.credentials.resolveSourceCredentialHeadersForIngest, {
1052+ ctx.runAction(runtimeInternal.control_plane.credentials.resolveSourceCredentialHeadersForIngest, {
10531053 workspaceId: source.workspaceId,
10541054 sourceId: source.id,
10551055 sourceName: source.name,
@@ -1206,7 +1206,7 @@ const ingestMcpSource = ( · 150 unmodified lines
12061206 headers: Record<string, string>;
12071207 }>(
12081208 () =>
1209− ctx.runQuery(runtimeInternal.control_plane.credentials.resolveSourceCredentialHeadersForIngest, {
1209+ ctx.runAction(runtimeInternal.control_plane.credentials.resolveSourceCredentialHeadersForIngest, {
12101210 workspaceId: source.workspaceId,
12111211 sourceId: source.id,
12121212 sourceName: source.name,
v2/apps/convex/convex/control_plane/organizations.ts+38−2
@@ -1,5 +1,9 @@
11 import { type UpsertOrganizationPayload } from "@executor-v2/management-api";
2−import { OrganizationSchema, type Organization } from "@executor-v2/schema";
2+import {
3+ OrganizationSchema,
4+ type Organization,
5+ type OrganizationMembership,
6+} from "@executor-v2/schema";
37 import { v } from "convex/values";
48 import * as Schema from "effect/Schema";
59
@@ -55,6 +59,7 @@ export const upsertOrganization = mutation({ · 49 unmodified lines
5559 slug: v.string(),
5660 name: v.string(),
5761 status: v.optional(organizationStatusValidator),
62+ createdByAccountId: v.optional(v.union(v.string(), v.null())),
5863 }),
5964 },
6065 handler: async (ctx, args): Promise<Organization> => {
@@ -72,7 +77,10 @@ export const upsertOrganization = mutation({ · 11 unmodified lines
7277 slug: payload.slug,
7378 name: payload.name,
7479 status: payload.status ?? existing?.status ?? "active",
75− createdByAccountId: existing?.createdByAccountId ?? null,
80+ createdByAccountId:
81+ existing?.createdByAccountId
82+ ?? payload.createdByAccountId
83+ ?? null,
7684 createdAt: existing?.createdAt ?? now,
7785 updatedAt: now,
7886 });
@@ -81,6 +89,34 @@ export const upsertOrganization = mutation({ · 2 unmodified lines
8189 await ctx.db.patch(existing._id, nextOrganization);
8290 } else {
8391 await ctx.db.insert("organizations", nextOrganization);
92+
93+ if (nextOrganization.createdByAccountId !== null) {
94+ const existingMembership = await ctx.db
95+ .query("organizationMemberships")
96+ .withIndex("by_organizationId_accountId", (q) =>
97+ q
98+ .eq("organizationId", nextOrganization.id)
99+ .eq("accountId", nextOrganization.createdByAccountId as string)
100+ )
101+ .first();
102+
103+ if (!existingMembership) {
104+ const membership: OrganizationMembership = {
105+ id: `org_member_${crypto.randomUUID()}` as OrganizationMembership["id"],
106+ organizationId: nextOrganization.id,
107+ accountId: nextOrganization.createdByAccountId,
108+ role: "owner",
109+ status: "active",
110+ billable: false,
111+ invitedByAccountId: null,
112+ joinedAt: now,
113+ createdAt: now,
114+ updatedAt: now,
115+ };
116+
117+ await ctx.db.insert("organizationMemberships", membership);
118+ }
119+ }
84120 }
85121
86122 return nextOrganization;
v2/apps/convex/convex/control_plane/service.ts+1−1
@@ -50,7 +50,7 @@ export const makeConvexControlPlaneService = ( · 49 unmodified lines
5050 upsertCredentialBinding: (input) =>
5151 Effect.tryPromise({
5252 try: () =>
53− ctx.runMutation(api.controlPlane.upsertCredentialBinding, {
53+ ctx.runAction(api.controlPlane.upsertCredentialBinding, {
5454 workspaceId: input.workspaceId,
5555 payload: input.payload,
5656 }),
v2/apps/convex/convex/control_plane/storage.ts+3−3
@@ -119,11 +119,11 @@ const resolveWorkspaceOrganizationId = async ( · 118 unmodified lines
119119 .withIndex("by_domainId", (q) => q.eq("id", workspaceId))
120120 .unique();
121121
122− if (workspace?.organizationId !== null && workspace?.organizationId !== undefined) {
123− return workspace.organizationId;
122+ if (!workspace) {
123+ throw new Error(`Workspace not found: ${workspaceId}`);
124124 }
125125
126− return `org_${workspaceId}`;
126+ return workspace.organizationId;
127127 };
128128
129129 const canAccessStorageInstance = (
v2/apps/convex/convex/control_plane/workspaces.ts+2−5
@@ -44,7 +44,7 @@ export const upsertWorkspace = mutation({ · 43 unmodified lines
4444 args: {
4545 payload: v.object({
4646 id: v.optional(v.string()),
47− organizationId: v.optional(v.union(v.string(), v.null())),
47+ organizationId: v.string(),
4848 name: v.string(),
4949 }),
5050 },
@@ -60,10 +60,7 @@ export const upsertWorkspace = mutation({ · 9 unmodified lines
6060
6161 const nextWorkspace = decodeWorkspace({
6262 id: workspaceId,
63− organizationId:
64− payload.organizationId !== undefined
65− ? payload.organizationId
66− : existing?.organizationId ?? null,
63+ organizationId: payload.organizationId,
6764 name: payload.name,
6865 createdByAccountId: existing?.createdByAccountId ?? null,
6966 createdAt: existing?.createdAt ?? now,
v2/apps/convex/convex/credential_crypto.ts+102−0
@@ -0,0 +1,102 @@
1+const encryptedPrefix = "enc:v1:";
2+
3+const encoder = new TextEncoder();
4+const decoder = new TextDecoder();
5+
6+const bytesToBase64 = (bytes: Uint8Array): string => {
7+ let binary = "";
8+ for (const byte of bytes) {
9+ binary += String.fromCharCode(byte);
10+ }
11+ return btoa(binary);
12+};
13+
14+const base64ToBytes = (base64: string): Uint8Array => {
15+ const binary = atob(base64);
16+ const bytes = new Uint8Array(binary.length);
17+ for (let i = 0; i < binary.length; i += 1) {
18+ bytes[i] = binary.charCodeAt(i);
19+ }
20+ return bytes;
21+};
22+
23+const resolveEncryptionPassphrase = (): string => {
24+ const passphrase = process.env.CREDENTIAL_ENCRYPTION_KEY?.trim() ?? "";
25+ if (passphrase.length === 0) {
26+ throw new Error("Encrypted credential storage requires CREDENTIAL_ENCRYPTION_KEY");
27+ }
28+
29+ return passphrase;
30+};
31+
32+const deriveAesKey = async (): Promise<CryptoKey> => {
33+ const passphraseBytes = encoder.encode(resolveEncryptionPassphrase());
34+ const hashBuffer = await crypto.subtle.digest("SHA-256", passphraseBytes);
35+ return await crypto.subtle.importKey(
36+ "raw",
37+ hashBuffer,
38+ {
39+ name: "AES-GCM",
40+ },
41+ false,
42+ ["encrypt", "decrypt"],
43+ );
44+};
45+
46+const parseEncryptedValue = (value: string): { iv: Uint8Array; cipher: Uint8Array } | null => {
47+ if (!value.startsWith(encryptedPrefix)) {
48+ return null;
49+ }
50+
51+ const payload = value.slice(encryptedPrefix.length);
52+ const parts = payload.split(":");
53+ if (parts.length !== 2) {
54+ return null;
55+ }
56+
57+ try {
58+ return {
59+ iv: base64ToBytes(parts[0] ?? ""),
60+ cipher: base64ToBytes(parts[1] ?? ""),
61+ };
62+ } catch {
63+ return null;
64+ }
65+};
66+
67+export const isEncryptedSecret = (value: string): boolean =>
68+ value.startsWith(encryptedPrefix);
69+
70+export const encryptSecretValue = async (plainText: string): Promise<string> => {
71+ const key = await deriveAesKey();
72+ const iv = crypto.getRandomValues(new Uint8Array(12));
73+ const encrypted = await crypto.subtle.encrypt(
74+ {
75+ name: "AES-GCM",
76+ iv,
77+ },
78+ key,
79+ encoder.encode(plainText),
80+ );
81+
82+ return `${encryptedPrefix}${bytesToBase64(iv)}:${bytesToBase64(new Uint8Array(encrypted))}`;
83+};
84+
85+export const decryptSecretValue = async (storedValue: string): Promise<string> => {
86+ const parsed = parseEncryptedValue(storedValue);
87+ if (parsed === null) {
88+ throw new Error("Credential secret is not encrypted");
89+ }
90+
91+ const key = await deriveAesKey();
92+ const decrypted = await crypto.subtle.decrypt(
93+ {
94+ name: "AES-GCM",
95+ iv: parsed.iv as unknown as BufferSource,
96+ },
97+ key,
98+ parsed.cipher as unknown as BufferSource,
99+ );
100+
101+ return decoder.decode(decrypted);
102+};
v2/apps/convex/convex/credential_resolver.ts+32−3
@@ -20,6 +20,7 @@ import * as Schema from "effect/Schema"; · 19 unmodified lines
2020
2121 import { api } from "./_generated/api";
2222 import { query, type ActionCtx } from "./_generated/server";
23+import { decryptSecretValue } from "./credential_crypto";
2324
2425 const decodeSourceCredentialBinding = Schema.decodeUnknownSync(
2526 SourceCredentialBindingSchema,
@@ -114,6 +115,16 @@ const runQueryEffect = <T>( · 88 unmodified lines
114115 ),
115116 });
116117
118+const requireLocalSecretProvider = (
119+ secretProvider: SourceCredentialBinding["secretProvider"],
120+): "local" => {
121+ if (secretProvider !== "local") {
122+ throw new Error("Convex credentials require secretProvider 'local'");
123+ }
124+
125+ return "local";
126+};
127+
117128 export const createConvexResolveToolCredentials = (
118129 ctx: ActionCtx,
119130 ): ResolveToolCredentials =>
@@ -160,10 +171,28 @@ export const createConvexResolveToolCredentials = ( · 40 unmodified lines
160171 )
161172 : null;
162173
174+ requireLocalSecretProvider(binding.secretProvider);
175+
176+ const secretRef = yield* Effect.tryPromise({
177+ try: () => decryptSecretValue(binding.secretRef),
178+ catch: (cause) =>
179+ toCredentialResolverError(
180+ "decrypt_credential_secret",
181+ "Convex credential decryption failed",
182+ String(cause),
183+ ),
184+ });
185+
163186 return {
164− headers: buildCredentialHeaders(binding, {
165− oauthAccessToken,
166− }),
187+ headers: buildCredentialHeaders(
188+ {
189+ ...binding,
190+ secretRef,
191+ },
192+ {
193+ oauthAccessToken,
194+ },
195+ ),
167196 };
168197 }),
169198 );
v2/apps/convex/convex/executor.test.ts+100−10
@@ -27,15 +27,91 @@ const setup = () => · 26 unmodified lines
2727 "./_generated/api.js": () => import("./_generated/api.js"),
2828 });
2929
30+const ensureWorkspace = async (
31+ t: ReturnType<typeof setup>,
32+ workspaceId: string,
33+ organizationId: string,
34+): Promise<void> => {
35+ await t.mutation(api.controlPlane.upsertWorkspace, {
36+ payload: {
37+ id: workspaceId,
38+ organizationId,
39+ name: workspaceId,
40+ },
41+ });
42+};
43+
3044 describe("Convex executor and control-plane", () => {
3145 it.effect("executes code via executeRunImpl", () =>
3246 Effect.gen(function* () {
33− const result = yield* executeRunImpl({
34− code: "return 6 * 7;",
35− });
47+ const originalEnv = {
48+ runUrl: process.env.CLOUDFLARE_SANDBOX_RUN_URL,
49+ authToken: process.env.CLOUDFLARE_SANDBOX_AUTH_TOKEN,
50+ callbackUrl: process.env.CLOUDFLARE_SANDBOX_CALLBACK_URL,
51+ };
52+ const originalFetch = globalThis.fetch;
3653
37− expect(result.status).toBe("completed");
38− expect(result.result).toBe(42);
54+ try {
55+ process.env.CLOUDFLARE_SANDBOX_RUN_URL = "https://sandbox.local/run";
56+ process.env.CLOUDFLARE_SANDBOX_AUTH_TOKEN = "sandbox-token";
57+ process.env.CLOUDFLARE_SANDBOX_CALLBACK_URL = "https://convex.local/callback";
58+
59+ globalThis.fetch = (async (
60+ input: RequestInfo | URL,
61+ init?: RequestInit,
62+ ) => {
63+ const url = typeof input === "string" ? input : input.toString();
64+ if (url !== "https://sandbox.local/run") {
65+ throw new Error(`Unexpected URL: ${url}`);
66+ }
67+
68+ expect(init?.method).toBe("POST");
69+ const headers = new Headers(init?.headers as HeadersInit | undefined);
70+ expect(headers.get("authorization")).toBe(
71+ "Bearer sandbox-token",
72+ );
73+
74+ return new Response(
75+ JSON.stringify({
76+ status: "completed",
77+ result: 42,
78+ }),
79+ {
80+ status: 200,
81+ headers: {
82+ "content-type": "application/json",
83+ },
84+ },
85+ );
86+ }) as unknown as typeof fetch;
87+
88+ const result = yield* executeRunImpl({
89+ code: "return 6 * 7;",
90+ });
91+
92+ expect(result.status).toBe("completed");
93+ expect(result.result).toBe(42);
94+ } finally {
95+ globalThis.fetch = originalFetch;
96+
97+ if (originalEnv.runUrl === undefined) {
98+ delete process.env.CLOUDFLARE_SANDBOX_RUN_URL;
99+ } else {
100+ process.env.CLOUDFLARE_SANDBOX_RUN_URL = originalEnv.runUrl;
101+ }
102+
103+ if (originalEnv.authToken === undefined) {
104+ delete process.env.CLOUDFLARE_SANDBOX_AUTH_TOKEN;
105+ } else {
106+ process.env.CLOUDFLARE_SANDBOX_AUTH_TOKEN = originalEnv.authToken;
107+ }
108+
109+ if (originalEnv.callbackUrl === undefined) {
110+ delete process.env.CLOUDFLARE_SANDBOX_CALLBACK_URL;
111+ } else {
112+ process.env.CLOUDFLARE_SANDBOX_CALLBACK_URL = originalEnv.callbackUrl;
113+ }
114+ }
39115 }),
40116 );
41117
@@ -44,7 +120,7 @@ describe("Convex executor and control-plane", () => { · 2 unmodified lines
44120 const t = setup();
45121
46122 const added = (yield* Effect.tryPromise(() =>
47− t.action(api.controlPlane.upsertSource, {
123+ t.action(api.controlPlane.upsertSource as any, {
48124 workspaceId: "ws_1",
49125 payload: {
50126 id: "src_1",
@@ -106,8 +182,10 @@ describe("Convex executor and control-plane", () => { · 55 unmodified lines
106182 Effect.gen(function* () {
107183 const t = setup();
108184
185+ yield* Effect.tryPromise(() => ensureWorkspace(t, "ws_1", "org_1"));
186+
109187 const addedCredential = (yield* Effect.tryPromise(() =>
110− t.mutation(api.controlPlane.upsertCredentialBinding, {
188+ t.action(api.controlPlane.upsertCredentialBinding, {
111189 workspaceId: "ws_1",
112190 payload: {
113191 id: "credential_binding_1",
@@ -448,7 +526,7 @@ describe("Convex executor and control-plane", () => { · 334 unmodified lines
448526 }),
449527 )) as {
450528 id: string;
451− organizationId: string | null;
529+ organizationId: string;
452530 };
453531
454532 expect(workspace.id).toBe("ws_1");
@@ -559,6 +637,7 @@ describe("Convex executor and control-plane", () => { · 104 unmodified lines
559637 rows: manifest.tools.map((tool) => ({
560638 toolId: tool.toolId,
561639 protocol: "openapi",
640+ method: tool.method,
562641 path: `weather_api_src_1.${tool.toolId}`,
563642 name: tool.name,
564643 description: tool.description,
@@ -683,6 +762,7 @@ describe("Convex executor and control-plane", () => { · 118 unmodified lines
683762 {
684763 toolId: "linear.graphql",
685764 protocol: "graphql",
765+ method: "post",
686766 path: "linear_api_phql_1.linear.graphql",
687767 name: "Linear GraphQL",
688768 description: "Run raw GraphQL queries against Linear",
@@ -694,6 +774,7 @@ describe("Convex executor and control-plane", () => { · 5 unmodified lines
694774 {
695775 toolId: "linear.query.viewer",
696776 protocol: "graphql",
777+ method: "post",
697778 path: "linear_api_phql_1.linear.query.viewer",
698779 name: "viewer",
699780 description: "Current viewer",
@@ -811,6 +892,7 @@ describe("Convex executor and control-plane", () => { · 111 unmodified lines
811892 {
812893 toolId: "deepwiki.mcp.search_docs",
813894 protocol: "mcp",
895+ method: "post",
814896 path: "deepwiki_mcp_1.deepwiki.mcp.search_docs",
815897 name: "search_docs",
816898 description: "Search docs",
@@ -863,6 +945,8 @@ describe("Convex executor and control-plane", () => { · 46 unmodified lines
863945 const t = setup();
864946 const originalFetch = globalThis.fetch;
865947
948+ yield* Effect.tryPromise(() => ensureWorkspace(t, "ws_auth", "org_auth"));
949+
866950 globalThis.fetch = (async () =>
867951 new Response(
868952 JSON.stringify({
@@ -932,6 +1016,8 @@ describe("Convex executor and control-plane", () => { · 63 unmodified lines
9321016 const t = setup();
9331017 const originalFetch = globalThis.fetch;
9341018
1019+ yield* Effect.tryPromise(() => ensureWorkspace(t, "ws_cred", "org_cred"));
1020+
9351021 globalThis.fetch = (async (_input: unknown, init?: RequestInit) => {
9361022 const authHeader = new Headers(init?.headers).get("authorization");
9371023 if (authHeader !== "Bearer linear_token") {
@@ -1026,7 +1112,7 @@ describe("Convex executor and control-plane", () => { · 88 unmodified lines
10261112 const now = Date.now();
10271113
10281114 yield* Effect.tryPromise(() =>
1029− t.mutation(api.controlPlane.upsertCredentialBinding, {
1115+ t.action(api.controlPlane.upsertCredentialBinding, {
10301116 workspaceId: "ws_cred",
10311117 payload: {
10321118 id: "credential_binding_linear",
@@ -1102,6 +1188,10 @@ describe("Convex executor and control-plane", () => { · 69 unmodified lines
11021188 const t = setup();
11031189 const originalFetch = globalThis.fetch;
11041190
1191+ yield* Effect.tryPromise(() =>
1192+ ensureWorkspace(t, "ws_mcp_ingest", "org_mcp_ingest")
1193+ );
1194+
11051195 globalThis.fetch = (async (_input: unknown, init?: RequestInit) => {
11061196 const authHeader = new Headers(init?.headers).get("authorization");
11071197 if (authHeader !== "Bearer mcp_token") {
@@ -1215,7 +1305,7 @@ describe("Convex executor and control-plane", () => { · 107 unmodified lines
12151305 const now = Date.now();
12161306
12171307 yield* Effect.tryPromise(() =>
1218− t.mutation(api.controlPlane.upsertCredentialBinding, {
1308+ t.action(api.controlPlane.upsertCredentialBinding, {
12191309 workspaceId: "ws_mcp_ingest",
12201310 payload: {
12211311 id: "credential_binding_mcp",
v2/apps/convex/convex/mcp.ts+1−5
@@ -71,7 +71,7 @@ const hasWorkspaceAccess = async ( · 70 unmodified lines
7171 runtimeInternal.control_plane.actor.getWorkspaceForActor,
7272 { workspaceId },
7373 )) as {
74− organizationId: string | null;
74+ organizationId: string;
7575 createdByAccountId: string | null;
7676 } | null;
7777
@@ -83,10 +83,6 @@ const hasWorkspaceAccess = async ( · 5 unmodified lines
8383 return true;
8484 }
8585
86− if (!workspace.organizationId) {
87− return false;
88− }
89−
9086 const memberships = (await ctx.runQuery(
9187 runtimeInternal.control_plane.actor.listOrganizationMembershipsForActor,
9288 { accountId },
v2/apps/convex/convex/runtime_adapter.ts+2−2
@@ -3,8 +3,8 @@ import { · 2 unmodified lines
33 type RuntimeExecuteError,
44 type RuntimeExecuteInput,
55 } from "@executor-v2/engine";
6−import { makeLocalInProcessRuntimeAdapter } from "@executor-v2/runtime-local-inproc";
6+import { makeCloudflareWorkerLoaderRuntimeAdapter } from "@executor-v2/runtime-cloudflare-worker-loader";
77
88 export type { RuntimeAdapter, RuntimeExecuteError, RuntimeExecuteInput };
99
10−export { makeLocalInProcessRuntimeAdapter };
10+export { makeCloudflareWorkerLoaderRuntimeAdapter };
v2/apps/convex/convex/runtime_execution_port.ts+7−7
@@ -8,13 +8,9 @@ import { · 7 unmodified lines
88 makeRuntimeAdapterRegistry,
99 type RuntimeExecuteError,
1010 } from "@executor-v2/engine";
11−import { makeLocalInProcessRuntimeAdapter } from "@executor-v2/runtime-local-inproc";
11+import { makeCloudflareWorkerLoaderRuntimeAdapter } from "@executor-v2/runtime-cloudflare-worker-loader";
1212 import * as Effect from "effect/Effect";
1313
14−const convexRuntimeAdapter = makeLocalInProcessRuntimeAdapter();
15−
16−const runtimeAdapters = makeRuntimeAdapterRegistry([convexRuntimeAdapter]);
17−
1814 export type ConvexRuntimeExecutionPortOptions = {
1915 toolRegistry?: ToolRegistry;
2016 };
@@ -22,6 +18,9 @@ export type ConvexRuntimeExecutionPortOptions = { · 1 unmodified line
2218 export const createExecuteRuntimeRunInConvex = (
2319 options: ConvexRuntimeExecutionPortOptions = {},
2420 ): ExecuteRuntimeRun => {
21+ const convexRuntimeAdapter = makeCloudflareWorkerLoaderRuntimeAdapter();
22+ const runtimeAdapters = makeRuntimeAdapterRegistry([convexRuntimeAdapter]);
23+
2524 const toolRegistry =
2625 options.toolRegistry ??
2726 createStaticToolRegistry({
@@ -46,8 +45,9 @@ export const createExecuteRuntimeRunInConvex = ( · 18 unmodified lines
4645 if (!isAvailable) {
4746 return yield* new RuntimeExecutionPortError({
4847 operation: "runtime_available",
49− message: `Runtime '${convexRuntimeAdapter.kind}' is not available in this convex process.`,
50− details: null,
48+ message: `Runtime '${convexRuntimeAdapter.kind}' is not configured in this convex process.`,
49+ details:
50+ "Set CLOUDFLARE_SANDBOX_RUN_URL, CLOUDFLARE_SANDBOX_AUTH_TOKEN, and CLOUDFLARE_SANDBOX_CALLBACK_URL.",
5151 });
5252 }
5353
v2/apps/convex/convex/source_tool_registry.ts+1−1
@@ -268,7 +268,7 @@ const resolveSourceCredentialHeadersForInvocation = async ( · 267 unmodified lines
268268 source: Source,
269269 ): Promise<Record<string, string>> => {
270270 try {
271− const resolved = (await ctx.runQuery(
271+ const resolved = (await ctx.runAction(
272272 runtimeInternal.control_plane.credentials.resolveSourceCredentialHeadersForIngest,
273273 {
274274 workspaceId: source.workspaceId,
v2/apps/convex/package.json+3−3
@@ -3,8 +3,8 @@ · 2 unmodified lines
33 "private": true,
44 "type": "module",
55 "scripts": {
6− "dev": "bunx convex dev",
7− "test": "bunx vitest run --no-watch convex/*.test.ts",
6+ "dev": "CREDENTIAL_ENCRYPTION_KEY=dev-credential-encryption-key bunx convex dev",
7+ "test": "CREDENTIAL_ENCRYPTION_KEY=test-credential-encryption-key bunx vitest run --no-watch convex/*.test.ts",
88 "typecheck": "bunx tsc --noEmit -p tsconfig.json",
99 "convex:codegen": "bunx convex codegen"
1010 },
@@ -16,7 +16,7 @@ · 5 unmodified lines
1616 "@executor-v2/management-api": "workspace:*",
1717 "@executor-v2/mcp-gateway": "workspace:*",
1818 "@executor-v2/persistence-ports": "workspace:*",
19− "@executor-v2/runtime-local-inproc": "workspace:*",
19+ "@executor-v2/runtime-cloudflare-worker-loader": "workspace:*",
2020 "@executor-v2/schema": "workspace:*",
2121 "@executor-v2/sdk": "workspace:*",
2222 "convex": "catalog:",
v2/apps/pm/src/credentials-service.ts+7−4
@@ -41,13 +41,12 @@ const resolveWorkspaceOrganizationId = ( · 40 unmodified lines
4141 workspaceId: WorkspaceId,
4242 ): OrganizationId => {
4343 const workspace = snapshot.workspaces.find((item) => item.id === workspaceId);
44− const organizationId = workspace?.organizationId;
4544
46− if (organizationId !== null && organizationId !== undefined) {
47− return organizationId;
45+ if (!workspace) {
46+ throw new Error(`Workspace not found: ${workspaceId}`);
4847 }
4948
50− return (`org_${workspaceId}`) as OrganizationId;
49+ return workspace.organizationId;
5150 };
5251
5352 const sortCredentialBindings = (
@@ -200,6 +199,10 @@ export const createPmCredentialsService = ( · 146 unmodified lines
200199 scopeType: input.payload.scopeType,
201200 sourceKey: input.payload.sourceKey,
202201 provider: input.payload.provider,
202+ secretProvider:
203+ input.payload.secretProvider
204+ ?? existing?.secretProvider
205+ ?? "local",
203206 secretRef: input.payload.secretRef,
204207 additionalHeadersJson: input.payload.additionalHeadersJson ?? null,
205208 boundAuthFingerprint: input.payload.boundAuthFingerprint ?? null,
v2/apps/pm/src/main.ts+7−1
@@ -10,6 +10,8 @@ import { · 9 unmodified lines
1010 } from "@executor-v2/management-api";
1111 import {
1212 RuntimeAdapterError,
13+ makeGraphqlToolProvider,
14+ makeMcpToolProvider,
1315 createRunExecutor,
1416 createSourceToolRegistry,
1517 defaultExecuteToolExposureMode,
@@ -175,7 +177,11 @@ const controlPlaneWebHandler = makeControlPlaneWebHandler( · 159 unmodified lines
175177 PmActorLive(localStateStore),
176178 );
177179
178−const toolProviderRegistry = makeToolProviderRegistry([makeOpenApiToolProvider()]);
180+const toolProviderRegistry = makeToolProviderRegistry([
181+ makeOpenApiToolProvider(),
182+ makeMcpToolProvider(),
183+ makeGraphqlToolProvider(),
184+]);
179185 const persistentApprovalPolicy = createPmPersistentToolApprovalPolicy(localStateStore, {
180186 requireApprovals: requireToolApprovals,
181187 });
v2/apps/pm/src/organizations-service.ts+41−3
@@ -8,7 +8,10 @@ import { · 7 unmodified lines
88 type LocalStateStore,
99 type LocalStateStoreError,
1010 } from "@executor-v2/persistence-local";
11−import { type Organization } from "@executor-v2/schema";
11+import {
12+ type Organization,
13+ type OrganizationMembership,
14+} from "@executor-v2/schema";
1215 import * as Effect from "effect/Effect";
1316 import * as Option from "effect/Option";
1417
@@ -70,6 +73,15 @@ const appendOrganization = ( · 55 unmodified lines
7073 organizations: [...snapshot.organizations, organization],
7174 });
7275
76+const appendOrganizationMembership = (
77+ snapshot: LocalStateSnapshot,
78+ membership: OrganizationMembership,
79+): LocalStateSnapshot => ({
80+ ...snapshot,
81+ generatedAt: Date.now(),
82+ organizationMemberships: [...snapshot.organizationMemberships, membership],
83+});
84+
7385 export const createPmOrganizationsService = (
7486 localStateStore: LocalStateStore,
7587 ): ControlPlaneOrganizationsServiceShape =>
@@ -122,15 +134,41 @@ export const createPmOrganizationsService = ( · 46 unmodified lines
122134 slug: input.payload.slug,
123135 name: input.payload.name,
124136 status: input.payload.status ?? existing?.status ?? "active",
125− createdByAccountId: existing?.createdByAccountId ?? null,
137+ createdByAccountId:
138+ existing?.createdByAccountId
139+ ?? input.payload.createdByAccountId
140+ ?? null,
126141 createdAt: existing?.createdAt ?? now,
127142 updatedAt: now,
128143 };
129144
130− const nextSnapshot = existingIndex >= 0
145+ let nextSnapshot = existingIndex >= 0
131146 ? replaceOrganizationAt(snapshot, existingIndex, nextOrganization)
132147 : appendOrganization(snapshot, nextOrganization);
133148
149+ if (existing === null && nextOrganization.createdByAccountId !== null) {
150+ const existingMembership = nextSnapshot.organizationMemberships.find(
151+ (membership) =>
152+ membership.organizationId === nextOrganization.id
153+ && membership.accountId === nextOrganization.createdByAccountId,
154+ );
155+
156+ if (!existingMembership) {
157+ nextSnapshot = appendOrganizationMembership(nextSnapshot, {
158+ id: `org_member_${crypto.randomUUID()}` as OrganizationMembership["id"],
159+ organizationId: nextOrganization.id,
160+ accountId: nextOrganization.createdByAccountId,
161+ role: "owner",
162+ status: "active",
163+ billable: false,
164+ invitedByAccountId: null,
165+ joinedAt: now,
166+ createdAt: now,
167+ updatedAt: now,
168+ });
169+ }
170+ }
171+
134172 yield* localStateStore.writeSnapshot(nextSnapshot).pipe(
135173 Effect.mapError((error) =>
136174 toSourceStoreErrorFromLocalState("organizations.upsert_write", error),
v2/apps/pm/src/storage-service.test.ts+1−1
@@ -29,7 +29,7 @@ const createTestSnapshot = (): LocalStateSnapshot => · 28 unmodified lines
2929 workspaces: [
3030 {
3131 id: "ws_local",
32− organizationId: null,
32+ organizationId: "org_local",
3333 name: "Local Workspace",
3434 createdByAccountId: null,
3535 createdAt: Date.now(),
v2/apps/pm/src/storage-service.ts+3−4
@@ -97,13 +97,12 @@ const resolveWorkspaceOrganizationId = ( · 96 unmodified lines
9797 workspaceId: WorkspaceId,
9898 ): OrganizationId => {
9999 const workspace = snapshot.workspaces.find((item) => item.id === workspaceId);
100− const organizationId = workspace?.organizationId;
101100
102− if (organizationId !== null && organizationId !== undefined) {
103− return organizationId;
101+ if (!workspace) {
102+ throw new Error(`Workspace not found: ${workspaceId}`);
104103 }
105104
106− return (`org_${workspaceId}`) as OrganizationId;
105+ return workspace.organizationId;
107106 };
108107
109108 const canAccessStorageInstance = (
v2/apps/pm/src/workspaces-service.ts+1−4
@@ -113,10 +113,7 @@ export const createPmWorkspacesService = ( · 112 unmodified lines
113113
114114 const nextWorkspace: Workspace = {
115115 id: existing?.id ?? (input.payload.id ?? (`ws_${crypto.randomUUID()}` as Workspace["id"])),
116− organizationId:
117− input.payload.organizationId !== undefined
118− ? input.payload.organizationId
119− : existing?.organizationId ?? null,
116+ organizationId: input.payload.organizationId,
120117 name: input.payload.name,
121118 createdByAccountId: existing?.createdByAccountId ?? null,
122119 createdAt: existing?.createdAt ?? now,
v2/apps/web/README.md+8−3
@@ -4,15 +4,20 @@ Basic Next.js frontend for Executor v2 control plane. · 3 unmodified lines
44
55 - Uses `@executor-v2/control-plane` Effect HttpApi client
66 - Uses Effect Atom (`@effect-atom/atom`, `@effect-atom/atom-react`) for query state
7−- Proxies backend calls through `/api/control-plane/*` via `next.config.ts` rewrites
87
98 Run:
109
1110 - `bun run --cwd apps/web dev`
1211 - Open `http://127.0.0.1:3000`
1312
14−By default, control-plane proxy target is `http://127.0.0.1:8788`.
15−Override with `CONTROL_PLANE_UPSTREAM_URL`.
13+By default, control-plane API calls go directly to `http://127.0.0.1:8788`.
14+Override with `NEXT_PUBLIC_CONTROL_PLANE_BASE_URL` (and optionally `CONTROL_PLANE_SERVER_BASE_URL` for SSR).
15+
16+MCP install URL generation:
17+
18+- Derives from existing control-plane/frontend config.
19+- Prioritizes server-side `CONTROL_PLANE_UPSTREAM_URL` (or server/base control-plane URL) when available.
20+- In local dev, defaults to direct Convex MCP URL: `http://127.0.0.1:8788/v1/mcp?...`
1621
1722 WorkOS auth setup (optional but recommended):
1823
v2/apps/web/app/(console)/tools/page.tsx+24−1
@@ -1,5 +1,28 @@
11 import { ToolsView } from "../../../components/tools/tools-view";
22
3−const ToolsPage = () => <ToolsView />;
3+const resolveMcpBaseUrl = (): string | null => {
4+ const candidates = [
5+ process.env.CONTROL_PLANE_UPSTREAM_URL,
6+ process.env.CONTROL_PLANE_SERVER_BASE_URL,
7+ process.env.NEXT_PUBLIC_CONTROL_PLANE_BASE_URL,
8+ ];
9+
10+ for (const candidate of candidates) {
11+ const value = candidate?.trim();
12+ if (!value) {
13+ continue;
14+ }
15+
16+ try {
17+ return new URL(value).origin;
18+ } catch {
19+ // ignore invalid URL and continue
20+ }
21+ }
22+
23+ return null;
24+};
25+
26+const ToolsPage = () => <ToolsView mcpBaseUrl={resolveMcpBaseUrl()} />;
427
528 export default ToolsPage;
v2/apps/web/app/api/control-plane/[...path]/route.ts+0−314
@@ -1,314 +0,0 @@
1−import { ControlPlaneAuthHeaders } from "@executor-v2/management-api";
2−import { withAuth } from "@workos-inc/authkit-nextjs";
3−import { type NextRequest } from "next/server";
4−
5−import { isLocalControlPlaneUpstream, isWorkosEnabled } from "../../../../lib/workos";
6−
7−const controlPlaneUpstream =
8− process.env.CONTROL_PLANE_UPSTREAM_URL ?? "http://127.0.0.1:8788";
9−
10−type TaggedControlPlaneError = {
11− _tag:
12− | "ControlPlaneBadRequestError"
13− | "ControlPlaneUnauthorizedError"
14− | "ControlPlaneForbiddenError"
15− | "ControlPlaneStorageError";
16− operation: string;
17− message: string;
18− details: string;
19−};
20−
21−const readOptionalHeader = (headers: Headers, name: string): string | null => {
22− const value = headers.get(name);
23− if (value === null) {
24− return null;
25− }
26−
27− const trimmed = value.trim();
28− return trimmed.length > 0 ? trimmed : null;
29−};
30−
31−const isRecord = (value: unknown): value is Record<string, unknown> =>
32− typeof value === "object" && value !== null;
33−
34−const readOptionalString = (record: Record<string, unknown>, key: string): string | null => {
35− const value = record[key];
36− return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
37−};
38−
39−const tagForStatus = (status: number): TaggedControlPlaneError["_tag"] => {
40− switch (status) {
41− case 400:
42− return "ControlPlaneBadRequestError";
43− case 401:
44− return "ControlPlaneUnauthorizedError";
45− case 403:
46− return "ControlPlaneForbiddenError";
47− default:
48− return "ControlPlaneStorageError";
49− }
50−};
51−
52−const responseStatusForTag = (status: number): number => {
53− switch (status) {
54− case 400:
55− case 401:
56− case 403:
57− return status;
58− default:
59− return 500;
60− }
61−};
62−
63−const toTaggedErrorPayload = (input: {
64− status: number;
65− operation: string;
66− message: string;
67− details: string;
68−}): TaggedControlPlaneError => ({
69− _tag: tagForStatus(input.status),
70− operation: input.operation,
71− message: input.message,
72− details: input.details,
73−});
74−
75−const unauthorizedResponse = (): Response =>
76− Response.json(
77− toTaggedErrorPayload({
78− status: 401,
79− operation: "control-plane.proxy",
80− message: "Authentication required",
81− details: "Sign in with WorkOS before calling control-plane APIs",
82− }),
83− { status: 401 },
84− );
85−
86−const internalErrorResponse = (operation: string, cause: unknown): Response =>
87− Response.json(
88− toTaggedErrorPayload({
89− status: 500,
90− operation,
91− message: "Control plane proxy failed",
92− details: cause instanceof Error ? cause.message : String(cause),
93− }),
94− { status: 500 },
95− );
96−
97−const toProxyUrl = (request: NextRequest, path: ReadonlyArray<string>): URL => {
98− const joinedPath = path.join("/");
99− const suffix = joinedPath.length > 0 ? `/${joinedPath}` : "";
100− return new URL(`${controlPlaneUpstream}${suffix}${request.nextUrl.search}`);
101−};
102−
103−const buildProxyHeaders = (request: NextRequest): Headers => {
104− const headers = new Headers();
105−
106− const contentType = readOptionalHeader(request.headers, "content-type");
107− if (contentType !== null) {
108− headers.set("content-type", contentType);
109− }
110−
111− const accept = readOptionalHeader(request.headers, "accept");
112− if (accept !== null) {
113− headers.set("accept", accept);
114− }
115−
116− const acceptEncoding = readOptionalHeader(request.headers, "accept-encoding");
117− if (acceptEncoding !== null) {
118− headers.set("accept-encoding", acceptEncoding);
119− }
120−
121− return headers;
122−};
123−
124−const toDisplayName = (user: {
125− firstName?: string | null;
126− lastName?: string | null;
127−}): string | null => {
128− const first = user.firstName?.trim() ?? "";
129− const last = user.lastName?.trim() ?? "";
130− const fullName = `${first} ${last}`.trim();
131− return fullName.length > 0 ? fullName : null;
132−};
133−
134−const resolvePrincipalAccountId = (
135− request: NextRequest,
136− userId: string | null,
137−): string | null => {
138− if (userId !== null) {
139− return userId;
140− }
141−
142− return readOptionalHeader(request.headers, ControlPlaneAuthHeaders.accountId);
143−};
144−
145−const normalizeControlPlaneErrorResponse = async (
146− upstreamResponse: Response,
147−): Promise<Response> => {
148− const contentType = upstreamResponse.headers.get("content-type")?.toLowerCase() ?? "";
149− const isJson = contentType.includes("application/json");
150−
151− const payload = isJson
152− ? await upstreamResponse
153− .json()
154− .catch(() => null)
155− : null;
156−
157− if (isRecord(payload)) {
158− const tagged = readOptionalString(payload, "_tag");
159− const operation = readOptionalString(payload, "operation");
160− const message = readOptionalString(payload, "message");
161− const details = readOptionalString(payload, "details");
162−
163− if (
164− tagged !== null
165− && operation !== null
166− && message !== null
167− && details !== null
168− && (
169− tagged === "ControlPlaneBadRequestError"
170− || tagged === "ControlPlaneUnauthorizedError"
171− || tagged === "ControlPlaneForbiddenError"
172− || tagged === "ControlPlaneStorageError"
173− )
174− ) {
175− return Response.json(
176− {
177− _tag: tagged,
178− operation,
179− message,
180− details,
181− } satisfies TaggedControlPlaneError,
182− { status: upstreamResponse.status },
183− );
184− }
185−
186− if (isRecord(payload.error)) {
187− const operationFromCode = readOptionalString(payload.error, "code");
188− const messageFromError = readOptionalString(payload.error, "message");
189− const detailsFromError = readOptionalString(payload.error, "details");
190−
191− return Response.json(
192− toTaggedErrorPayload({
193− status: upstreamResponse.status,
194− operation: operationFromCode ?? "control-plane.proxy",
195− message: messageFromError ?? "Control plane request failed",
196− details: detailsFromError ?? (upstreamResponse.statusText || "Request failed"),
197− }),
198− { status: responseStatusForTag(upstreamResponse.status) },
199− );
200− }
201− }
202−
203− const textBody = await upstreamResponse
204− .text()
205− .catch(() => "");
206−
207− return Response.json(
208− toTaggedErrorPayload({
209− status: upstreamResponse.status,
210− operation: "control-plane.proxy",
211− message: "Control plane request failed",
212− details:
213− textBody.trim().length > 0
214− ? textBody.trim()
215− : upstreamResponse.statusText || "Request failed",
216− }),
217− { status: responseStatusForTag(upstreamResponse.status) },
218− );
219−};
220−
221−const normalizeSuccessResponse = (
222− upstreamResponse: Response,
223−): Response => {
224− const contentType = upstreamResponse.headers.get("content-type")?.toLowerCase() ?? "";
225−
226− const headers = new Headers();
227− if (contentType.length > 0) {
228− headers.set("content-type", contentType);
229− }
230−
231− return new Response(upstreamResponse.body, {
232− status: upstreamResponse.status,
233− headers,
234− });
235−};
236−
237−const proxyControlPlaneRequest = async (
238− request: NextRequest,
239− path: ReadonlyArray<string>,
240−): Promise<Response> => {
241− try {
242− const workosEnabled = isWorkosEnabled();
243− const user = workosEnabled ? (await withAuth()).user : null;
244−
245− let principalAccountId = resolvePrincipalAccountId(request, user?.id ?? null);
246−
247− if (workosEnabled && user === null) {
248− return unauthorizedResponse();
249− }
250−
251− if (principalAccountId === null && !workosEnabled && isLocalControlPlaneUpstream()) {
252− const localAccountId = process.env.CONTROL_PLANE_LOCAL_ACCOUNT_ID?.trim();
253− principalAccountId = localAccountId && localAccountId.length > 0
254− ? localAccountId
255− : "local-dev";
256− }
257−
258− if (principalAccountId === null) {
259− return unauthorizedResponse();
260− }
261−
262− const headers = buildProxyHeaders(request);
263−
264− headers.set(ControlPlaneAuthHeaders.accountId, principalAccountId);
265− headers.set(ControlPlaneAuthHeaders.principalProvider, user ? "workos" : "local");
266− headers.set(
267− ControlPlaneAuthHeaders.principalSubject,
268− user ? `workos:${user.id}` : `local:${principalAccountId}`,
269− );
270−
271− const email = user?.email?.trim();
272− if (email) {
273− headers.set(ControlPlaneAuthHeaders.principalEmail, email);
274− }
275−
276− const displayName = user ? toDisplayName(user) : null;
277− if (displayName) {
278− headers.set(ControlPlaneAuthHeaders.principalDisplayName, displayName);
279− }
280−
281− const body =
282− request.method === "GET" || request.method === "HEAD"
283− ? undefined
284− : await request.arrayBuffer();
285−
286− const upstreamResponse = await fetch(toProxyUrl(request, path), {
287− method: request.method,
288− headers,
289− body,
290− cache: "no-store",
291− });
292−
293− if (!upstreamResponse.ok) {
294− return normalizeControlPlaneErrorResponse(upstreamResponse);
295− }
296−
297− return normalizeSuccessResponse(upstreamResponse);
298− } catch (cause) {
299− return internalErrorResponse("control-plane.proxy", cause);
300− }
301−};
302−
303−type RouteParams = {
304− params: Promise<{ path: Array<string> }>;
305−};
306−
307−export const GET = async (request: NextRequest, context: RouteParams) =>
308− proxyControlPlaneRequest(request, (await context.params).path);
309−
310−export const POST = async (request: NextRequest, context: RouteParams) =>
311− proxyControlPlaneRequest(request, (await context.params).path);
312−
313−export const DELETE = async (request: NextRequest, context: RouteParams) =>
314− proxyControlPlaneRequest(request, (await context.params).path);
v2/apps/web/components/settings/settings-view.tsx+45−17
@@ -60,6 +60,17 @@ const defaultWorkspaceForm = (): WorkspaceForm => ({ · 59 unmodified lines
6060 organizationId: "",
6161 });
6262
63+const createOrganizationId = (): Organization["id"] =>
64+ `org_${crypto.randomUUID()}` as Organization["id"];
65+
66+const createWorkspaceId = (): Workspace["id"] =>
67+ `ws_${crypto.randomUUID()}` as Workspace["id"];
68+
69+const errorMessage = (cause: unknown, fallback: string): string =>
70+ cause instanceof Error && cause.message.trim().length > 0
71+ ? cause.message
72+ : fallback;
73+
6374 const organizationStatusVariant = (
6475 status: Organization["status"],
6576 ): "approved" | "pending" | "denied" | "outline" => {
@@ -106,7 +117,7 @@ export default function SettingsView() { · 40 unmodified lines
106117 ...current,
107118 id: currentWorkspace.id,
108119 name: currentWorkspace.name,
109− organizationId: currentWorkspace.organizationId ?? "",
120+ organizationId: currentWorkspace.organizationId,
110121 }));
111122 }, [workspaceId, workspaceForm.name, workspaces.items]);
112123
@@ -116,7 +127,7 @@ export default function SettingsView() { · 3 unmodified lines
116127 }
117128
118129 const currentWorkspace = workspaces.items.find((workspace) => workspace.id === workspaceId);
119− if (!currentWorkspace?.organizationId) {
130+ if (!currentWorkspace) {
120131 return;
121132 }
122133
@@ -141,6 +152,9 @@ export default function SettingsView() { · 18 unmodified lines
141152 const slug = organizationForm.slug.trim();
142153 const name = organizationForm.name.trim();
143154 const inputId = organizationForm.id.trim();
155+ const organizationId = inputId.length > 0
156+ ? (inputId as Organization["id"])
157+ : createOrganizationId();
144158
145159 if (slug.length === 0 || name.length === 0) {
146160 setOrganizationStatusText("Organization slug and name are required.");
@@ -148,7 +162,7 @@ export default function SettingsView() { · 1 unmodified line
148162 }
149163
150164 const payload = toOrganizationUpsertPayload({
151− id: inputId.length > 0 ? (inputId as Organization["id"]) : undefined,
165+ id: organizationId,
152166 slug,
153167 name,
154168 status: organizationForm.status,
@@ -164,8 +178,8 @@ export default function SettingsView() { · 9 unmodified lines
164178 status: organization.status,
165179 });
166180 })
167− .catch(() => {
168− setOrganizationStatusText("Organization save failed.");
181+ .catch((cause) => {
182+ setOrganizationStatusText(errorMessage(cause, "Organization save failed."));
169183 });
170184 };
171185
@@ -175,16 +189,24 @@ export default function SettingsView() { · 3 unmodified lines
175189 const name = workspaceForm.name.trim();
176190 const inputId = workspaceForm.id.trim();
177191 const organizationId = workspaceForm.organizationId.trim();
192+ const workspaceId = inputId.length > 0
193+ ? (inputId as Workspace["id"])
194+ : createWorkspaceId();
178195
179196 if (name.length === 0) {
180197 setWorkspaceStatusText("Workspace name is required.");
181198 return;
182199 }
183200
201+ if (organizationId.length === 0) {
202+ setWorkspaceStatusText("Workspace organization is required.");
203+ return;
204+ }
205+
184206 const payload = toWorkspaceUpsertPayload({
185− id: inputId.length > 0 ? (inputId as Workspace["id"]) : undefined,
207+ id: workspaceId,
186208 name,
187− organizationId: organizationId.length > 0 ? (organizationId as Workspace["organizationId"]) : null,
209+ organizationId: organizationId as Workspace["organizationId"],
188210 });
189211
190212 void runUpsertWorkspace({ payload })
@@ -193,12 +215,12 @@ export default function SettingsView() { · 2 unmodified lines
193215 setWorkspaceForm({
194216 id: workspace.id,
195217 name: workspace.name,
196− organizationId: workspace.organizationId ?? "",
218+ organizationId: workspace.organizationId,
197219 });
198220 setWorkspaceId(workspace.id);
199221 })
200− .catch(() => {
201− setWorkspaceStatusText("Workspace save failed.");
222+ .catch((cause) => {
223+ setWorkspaceStatusText(errorMessage(cause, "Workspace save failed."));
202224 });
203225 };
204226
@@ -216,7 +238,7 @@ export default function SettingsView() { · 11 unmodified lines
216238 setWorkspaceForm({
217239 id: workspace.id,
218240 name: workspace.name,
219− organizationId: workspace.organizationId ?? "",
241+ organizationId: workspace.organizationId,
220242 });
221243 setWorkspaceId(workspace.id);
222244 setWorkspaceStatusText(`Loaded workspace ${workspace.id}.`);
@@ -376,7 +398,7 @@ export default function SettingsView() { · 153 unmodified lines
376398 <CardHeader className="pb-3">
377399 <CardTitle>Workspace Profile</CardTitle>
378400 <CardDescription>
379− Create or update workspace records and their optional organization id.
401+ Create or update workspace records scoped to an organization.
380402 </CardDescription>
381403 </CardHeader>
382404
@@ -413,9 +435,9 @@ export default function SettingsView() { · 30 unmodified lines
413435 </div>
414436 <div className="grid gap-1.5">
415437 <label className="text-xs text-muted-foreground" htmlFor="workspace-organization-id">
416− Organization ID
438+ Organization
417439 </label>
418− <Input
440+ <Select
419441 id="workspace-organization-id"
420442 value={workspaceForm.organizationId}
421443 onChange={(event) =>
@@ -424,9 +446,15 @@ export default function SettingsView() { · 2 unmodified lines
424446 organizationId: event.target.value,
425447 }))
426448 }
427− placeholder="org_local (optional)"
428449 disabled={workspacesLoading}
429− />
450+ >
451+ <option value="">Select organization</option>
452+ {organizations.items.map((organization) => (
453+ <option key={organization.id} value={organization.id}>
454+ {organization.name}
455+ </option>
456+ ))}
457+ </Select>
430458 </div>
431459
432460 <div className="flex gap-2">
@@ -466,7 +494,7 @@ export default function SettingsView() { · 33 unmodified lines
466494 <p className="truncate text-sm font-medium">{workspace.name}</p>
467495 <div className="flex flex-wrap items-center gap-1.5 text-xs text-muted-foreground">
468496 <span className="break-all">{workspace.id}</span>
469− <span className="break-all">org {workspace.organizationId ?? "-"}</span>
497+ <span className="break-all">org {workspace.organizationId}</span>
470498 </div>
471499 </div>
472500 <Button
v2/apps/web/components/shell/app-shell.tsx+3−11
@@ -128,18 +128,10 @@ export function AppShell({ · 127 unmodified lines
128128 {/* ---- Sidebar ---- */}
129129 <aside className="flex w-[220px] shrink-0 flex-col border-r border-sidebar-border bg-sidebar">
130130 {/* Logo / brand */}
131− <div className="flex h-12 items-center gap-2 border-b border-sidebar-border px-4">
132− <div className="flex size-6 items-center justify-center rounded bg-primary/90 text-[10px] font-bold text-primary-foreground">
133− Ex
131+ <div className="border-b border-sidebar-border px-3 py-2">
132+ <div className="min-w-0">
133+ <WorkspaceSelector />
134134 </div>
135− <span className="text-[13px] font-semibold tracking-tight text-sidebar-foreground">
136− Executor v2
137− </span>
138− </div>
139−
140− {/* Workspace selector */}
141− <div className="border-b border-sidebar-border px-3 py-2.5">
142− <WorkspaceSelector />
143135 </div>
144136
145137 {/* Nav items */}
v2/apps/web/components/shell/workspace-selector.tsx+341−182
@@ -1,6 +1,6 @@
11 "use client";
22
3−import { useEffect, useMemo, useState, type FormEvent } from "react";
3+import { useEffect, useMemo, useRef, useState, type FormEvent } from "react";
44 import { useAtomSet, useAtomValue } from "@effect-atom/atom-react";
55 import type { Organization, Workspace } from "@executor-v2/schema";
66
@@ -13,23 +13,34 @@ import { · 6 unmodified lines
1313 workspacesState,
1414 } from "../../lib/control-plane/atoms";
1515 import { useWorkspace } from "../../lib/hooks/use-workspace";
16+import { cn } from "../../lib/utils";
1617 import { Button } from "../ui/button";
1718 import { Input } from "../ui/input";
18−import { Select } from "../ui/select";
1919
2020 type StatusState = {
2121 message: string | null;
2222 variant: "info" | "error";
2323 };
2424
25−type WorkspaceGroup = {
26− key: string;
25+type OrganizationGroup = {
26+ organizationId: Organization["id"];
2727 label: string;
2828 workspaces: Array<Workspace>;
2929 };
3030
3131 const defaultStatus = (): StatusState => ({ message: null, variant: "info" });
3232
33+const createWorkspaceId = (): Workspace["id"] =>
34+ `ws_${crypto.randomUUID()}` as Workspace["id"];
35+
36+const createOrganizationId = (): Organization["id"] =>
37+ `org_${crypto.randomUUID()}` as Organization["id"];
38+
39+const errorMessage = (cause: unknown, fallback: string): string =>
40+ cause instanceof Error && cause.message.trim().length > 0
41+ ? cause.message
42+ : fallback;
43+
3344 const slugify = (value: string): string =>
3445 value
3546 .trim()
@@ -39,14 +50,34 @@ const slugify = (value: string): string => · 3 unmodified lines
3950 .replace(/-+$/, "")
4051 .replace(/-{2,}/g, "-");
4152
53+const CheckIcon = ({ className }: { className?: string }) => (
54+ <svg viewBox="0 0 16 16" fill="none" className={className}>
55+ <path d="M3.5 8.5l3 3 6-7" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
56+ </svg>
57+);
58+
59+const PlusIcon = ({ className }: { className?: string }) => (
60+ <svg viewBox="0 0 16 16" fill="none" className={className}>
61+ <path d="M8 3v10M3 8h10" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" />
62+ </svg>
63+);
64+
65+const ChevronsIcon = ({ className }: { className?: string }) => (
66+ <svg viewBox="0 0 16 16" fill="none" className={className}>
67+ <path d="M5 6l3-3 3 3M11 10l-3 3-3-3" stroke="currentColor" strokeWidth="1.3" strokeLinecap="round" strokeLinejoin="round" />
68+ </svg>
69+);
70+
4271 export function WorkspaceSelector() {
4372 const { workspaceId, setWorkspaceId } = useWorkspace();
4473 const organizations = useAtomValue(organizationsState);
4574 const workspaces = useAtomValue(workspacesState);
4675 const runUpsertOrganization = useAtomSet(upsertOrganization, { mode: "promise" });
4776 const runUpsertWorkspace = useAtomSet(upsertWorkspace, { mode: "promise" });
77+ const containerRef = useRef<HTMLDivElement | null>(null);
4878
4979 const [activeForm, setActiveForm] = useState<"workspace" | "organization" | null>(null);
80+ const [menuOpen, setMenuOpen] = useState(false);
5081 const [workspaceName, setWorkspaceName] = useState("");
5182 const [workspaceOrganizationId, setWorkspaceOrganizationId] = useState("");
5283 const [organizationName, setOrganizationName] = useState("");
@@ -68,44 +99,53 @@ export function WorkspaceSelector() { · 15 unmodified lines
6899 [workspaces.items, workspaceId],
69100 );
70101
71− const currentOrganizationLabel = useMemo(() => {
72− if (!currentWorkspace?.organizationId) {
73− return "No organization";
74− }
102+ const currentWorkspaceLabel = currentWorkspace?.name ?? "Select workspace";
103+ const hasOrganizations = organizations.items.length > 0;
75104
76− return organizationNameById.get(currentWorkspace.organizationId)
77− ?? currentWorkspace.organizationId;
78− }, [currentWorkspace, organizationNameById]);
105+ const currentOrganizationLabel = useMemo(
106+ () =>
107+ currentWorkspace
108+ ? organizationNameById.get(currentWorkspace.organizationId) ?? currentWorkspace.organizationId
109+ : null,
110+ [currentWorkspace, organizationNameById],
111+ );
79112
80− const workspaceGroups = useMemo((): Array<WorkspaceGroup> => {
81− const byGroup = new Map<string, WorkspaceGroup>();
113+ const organizationGroups = useMemo((): Array<OrganizationGroup> => {
114+ const workspacesByOrganization = new Map<string, Array<Workspace>>();
82115
83116 for (const workspace of workspaces.items) {
84− const key = workspace.organizationId ?? "__none__";
85− const label =
86− workspace.organizationId === null
87− ? "No organization"
88− : organizationNameById.get(workspace.organizationId) ?? workspace.organizationId;
89−
90− const existing = byGroup.get(key);
117+ const existing = workspacesByOrganization.get(workspace.organizationId);
91118 if (existing) {
92− existing.workspaces.push(workspace);
119+ existing.push(workspace);
120+ } else {
121+ workspacesByOrganization.set(workspace.organizationId, [workspace]);
122+ }
123+ }
124+
125+ const groups = organizations.items
126+ .map((organization) => ({
127+ organizationId: organization.id,
128+ label: organization.name,
129+ workspaces: [...(workspacesByOrganization.get(organization.id) ?? [])].sort((a, b) =>
130+ a.name.localeCompare(b.name),
131+ ),
132+ }))
133+ .sort((left, right) => left.label.localeCompare(right.label));
134+
135+ for (const [organizationId, groupedWorkspaces] of workspacesByOrganization.entries()) {
136+ if (organizationNameById.has(organizationId)) {
93137 continue;
94138 }
95139
96− byGroup.set(key, {
97− key,
98− label,
99− workspaces: [workspace],
140+ groups.push({
141+ organizationId: organizationId as Organization["id"],
142+ label: organizationId,
143+ workspaces: [...groupedWorkspaces].sort((a, b) => a.name.localeCompare(b.name)),
100144 });
101145 }
102146
103− return [...byGroup.values()].sort((left, right) => {
104− if (left.key === "__none__") return -1;
105− if (right.key === "__none__") return 1;
106− return left.label.localeCompare(right.label);
107− });
108− }, [organizationNameById, workspaces.items]);
147+ return groups;
148+ }, [organizationNameById, organizations.items, workspaces.items]);
109149
110150 useEffect(() => {
111151 if (workspaces.state !== "ready") {
@@ -125,9 +165,49 @@ export function WorkspaceSelector() { · 13 unmodified lines
125165 }
126166 }, [setWorkspaceId, workspaceId, workspaces.items, workspaces.state]);
127167
128− const openWorkspaceForm = () => {
168+ useEffect(() => {
169+ if (!menuOpen) {
170+ return;
171+ }
172+
173+ const onPointerDown = (event: MouseEvent | TouchEvent) => {
174+ if (!containerRef.current?.contains(event.target as Node)) {
175+ setMenuOpen(false);
176+ }
177+ };
178+
179+ const onKeyDown = (event: KeyboardEvent) => {
180+ if (event.key === "Escape") {
181+ setMenuOpen(false);
182+ }
183+ };
184+
185+ document.addEventListener("mousedown", onPointerDown);
186+ document.addEventListener("touchstart", onPointerDown);
187+ document.addEventListener("keydown", onKeyDown);
188+
189+ return () => {
190+ document.removeEventListener("mousedown", onPointerDown);
191+ document.removeEventListener("touchstart", onPointerDown);
192+ document.removeEventListener("keydown", onKeyDown);
193+ };
194+ }, [menuOpen]);
195+
196+ const selectWorkspace = (nextWorkspaceId: Workspace["id"]) => {
197+ setWorkspaceId(nextWorkspaceId);
129198 setStatus(defaultStatus());
130− if (activeForm === "workspace") {
199+ setActiveForm(null);
200+ setMenuOpen(false);
201+ };
202+
203+ const openWorkspaceForm = (organizationId?: Organization["id"]) => {
204+ setStatus(defaultStatus());
205+
206+ if (!menuOpen) {
207+ setMenuOpen(true);
208+ }
209+
210+ if (activeForm === "workspace" && organizationId === workspaceOrganizationId) {
131211 setActiveForm(null);
132212 return;
133213 }
@@ -135,7 +215,21 @@ export function WorkspaceSelector() { · 1 unmodified line
135215 setActiveForm("workspace");
136216 setWorkspaceName("");
137217
138− if (currentWorkspace?.organizationId) {
218+ if (organizations.items.length === 0) {
219+ setWorkspaceOrganizationId("");
220+ setStatus({
221+ message: "Create an organization first.",
222+ variant: "error",
223+ });
224+ return;
225+ }
226+
227+ if (organizationId) {
228+ setWorkspaceOrganizationId(organizationId);
229+ return;
230+ }
231+
232+ if (currentWorkspace) {
139233 setWorkspaceOrganizationId(currentWorkspace.organizationId);
140234 return;
141235 }
@@ -145,6 +239,11 @@ export function WorkspaceSelector() { · 3 unmodified lines
145239
146240 const openOrganizationForm = () => {
147241 setStatus(defaultStatus());
242+
243+ if (!menuOpen) {
244+ setMenuOpen(true);
245+ }
246+
148247 if (activeForm === "organization") {
149248 setActiveForm(null);
150249 return;
@@ -169,28 +268,36 @@ export function WorkspaceSelector() { · 18 unmodified lines
169268 return;
170269 }
171270
271+ if (organizationId.length === 0) {
272+ setStatus({
273+ message: "Select an organization first.",
274+ variant: "error",
275+ });
276+ return;
277+ }
278+
172279 setCreatingWorkspace(true);
173280
174281 void runUpsertWorkspace({
175282 payload: toWorkspaceUpsertPayload({
283+ id: createWorkspaceId(),
176284 name,
177− organizationId: organizationId.length > 0
178− ? (organizationId as Workspace["organizationId"])
179− : null,
285+ organizationId: organizationId as Workspace["organizationId"],
180286 }),
181287 })
182288 .then((workspace) => {
183289 setWorkspaceId(workspace.id);
184290 setWorkspaceName("");
185291 setActiveForm(null);
292+ setMenuOpen(false);
186293 setStatus({
187294 message: `Created workspace ${workspace.name}.`,
188295 variant: "info",
189296 });
190297 })
191− .catch(() => {
298+ .catch((cause) => {
192299 setStatus({
193− message: "Workspace creation failed.",
300+ message: errorMessage(cause, "Workspace creation failed."),
194301 variant: "error",
195302 });
196303 })
@@ -225,34 +332,48 @@ export function WorkspaceSelector() { · 28 unmodified lines
225332
226333 setCreatingOrganization(true);
227334
335+ const organizationId = createOrganizationId();
336+
228337 void runUpsertOrganization({
229338 payload: toOrganizationUpsertPayload({
339+ id: organizationId,
230340 name,
231341 slug,
232342 status: "active",
233343 }),
234344 })
235345 .then(async (organization) => {
236− const workspace = await runUpsertWorkspace({
237− payload: toWorkspaceUpsertPayload({
238− name,
239− organizationId: organization.id as Workspace["organizationId"],
240− }),
241− });
242−
243− setWorkspaceId(workspace.id);
244− setWorkspaceOrganizationId(organization.id);
245− setOrganizationName("");
246− setOrganizationSlug("");
247− setActiveForm(null);
248− setStatus({
249− message: `Created organization ${organization.name} with workspace ${workspace.name}.`,
250− variant: "info",
251− });
346+ try {
347+ const workspace = await runUpsertWorkspace({
348+ payload: toWorkspaceUpsertPayload({
349+ id: createWorkspaceId(),
350+ name,
351+ organizationId: organization.id as Workspace["organizationId"],
352+ }),
353+ });
354+
355+ setWorkspaceId(workspace.id);
356+ setWorkspaceOrganizationId(organization.id);
357+ setOrganizationName("");
358+ setOrganizationSlug("");
359+ setActiveForm(null);
360+ setMenuOpen(false);
361+ setStatus({
362+ message: `Created organization ${organization.name} with workspace ${workspace.name}.`,
363+ variant: "info",
364+ });
365+ } catch {
366+ setWorkspaceOrganizationId(organization.id);
367+ setActiveForm("workspace");
368+ setStatus({
369+ message: `Created organization ${organization.name}, but workspace creation failed.`,
370+ variant: "error",
371+ });
372+ }
252373 })
253− .catch(() => {
374+ .catch((cause) => {
254375 setStatus({
255− message: "Organization creation failed.",
376+ message: errorMessage(cause, "Organization creation failed."),
256377 variant: "error",
257378 });
258379 })
@@ -261,137 +382,175 @@ export function WorkspaceSelector() { · 2 unmodified lines
261382 });
262383 };
263384
264− const selectorDisabled = workspaces.state === "loading" || workspaces.items.length === 0;
385+ const workspaceCreationDisabled = creatingWorkspace || !hasOrganizations;
386+ const showEmptyState = workspaces.state !== "loading" && organizationGroups.length === 0;
387+ const selectedOrganizationLabel =
388+ workspaceOrganizationId.length > 0
389+ ? organizationNameById.get(workspaceOrganizationId) ?? workspaceOrganizationId
390+ : null;
265391
266392 return (
267− <div className="space-y-2">
268− <div>
269− <label className="block text-[10px] uppercase tracking-widest text-sidebar-foreground/50">
270− Workspace
271− </label>
272− <p className="mt-0.5 truncate text-[10px] text-sidebar-foreground/50">
273− {currentWorkspace ? currentOrganizationLabel : "Create your first workspace"}
274− </p>
275− </div>
276−
277− <Select
278− value={workspaceId}
279− onChange={(event) => {
280− setWorkspaceId(event.target.value);
393+ <div ref={containerRef} className="relative">
394+ <button
395+ type="button"
396+ className="flex h-10 w-full items-center justify-between rounded-lg border border-sidebar-border bg-sidebar-active/55 px-2.5 text-left text-sidebar-foreground transition-colors hover:bg-sidebar-active/75"
397+ onClick={() => {
281398 setStatus(defaultStatus());
399+ setMenuOpen((open) => !open);
282400 }}
283− disabled={selectorDisabled}
284− className="h-8 border-sidebar-border bg-sidebar-active/50 px-2 text-[12px] text-sidebar-foreground"
285401 >
286− {workspaces.state === "loading" ? (
287− <option value="">Loading workspaces...</option>
288− ) : null}
289−
290− {workspaces.state !== "loading" && workspaces.items.length === 0 ? (
291− <option value="">No workspaces available</option>
292− ) : null}
293−
294− {workspaceGroups.map((group) => (
295− <optgroup key={group.key} label={group.label}>
296− {group.workspaces.map((workspace) => (
297− <option key={workspace.id} value={workspace.id}>
298− {workspace.name}
299− </option>
402+ <span className="flex min-w-0 items-center gap-2">
403+ <span className="flex size-6 shrink-0 items-center justify-center rounded bg-sidebar-active text-[10px] font-semibold text-sidebar-foreground/80">
404+ {(currentWorkspaceLabel[0] ?? "W").toUpperCase()}
405+ </span>
406+ <span className="min-w-0">
407+ <span className="block truncate text-[10px] text-sidebar-foreground/55">
408+ {currentOrganizationLabel ?? "Create your first organization"}
409+ </span>
410+ <span className="block truncate text-[12px] font-medium">
411+ {currentWorkspaceLabel}
412+ </span>
413+ </span>
414+ </span>
415+ <ChevronsIcon className="ml-2 size-3.5 shrink-0 text-sidebar-foreground/60" />
416+ </button>
417+
418+ {menuOpen ? (
419+ <div className="absolute left-0 top-[calc(100%+6px)] z-50 w-[300px] max-w-[calc(100vw-24px)] rounded-lg border border-sidebar-border bg-sidebar p-2 shadow-lg">
420+ <div className="max-h-56 space-y-2 overflow-y-auto">
421+ {workspaces.state === "loading" ? (
422+ <p className="px-1 text-[11px] text-sidebar-foreground/60">Loading workspaces...</p>
423+ ) : null}
424+
425+ {showEmptyState ? (
426+ <p className="px-1 text-[11px] text-sidebar-foreground/60">No workspaces yet.</p>
427+ ) : null}
428+
429+ {organizationGroups.map((group) => (
430+ <div key={group.organizationId} className="space-y-1 rounded-md border border-sidebar-border/70 p-1.5">
431+ <div className="flex items-center justify-between gap-2 px-1">
432+ <p className="truncate text-[10px] uppercase tracking-wider text-sidebar-foreground/45">
433+ {group.label}
434+ </p>
435+ <button
436+ type="button"
437+ className="inline-flex h-5 items-center gap-1 rounded border border-sidebar-border px-1.5 text-[10px] text-sidebar-foreground/70 transition-colors hover:bg-sidebar-active hover:text-sidebar-foreground"
438+ onClick={() => openWorkspaceForm(group.organizationId)}
439+ >
440+ <PlusIcon className="size-2.5" />
441+ Workspace
442+ </button>
443+ </div>
444+
445+ {group.workspaces.length === 0 ? (
446+ <p className="px-2 py-1 text-[11px] text-sidebar-foreground/55">No workspaces yet.</p>
447+ ) : null}
448+
449+ {group.workspaces.map((workspace) => (
450+ <button
451+ key={workspace.id}
452+ type="button"
453+ className={cn(
454+ "flex h-7 w-full items-center gap-1.5 rounded px-2 text-[12px] text-sidebar-foreground transition-colors",
455+ workspace.id === workspaceId
456+ ? "bg-sidebar-active"
457+ : "hover:bg-sidebar-active/65",
458+ )}
459+ onClick={() => selectWorkspace(workspace.id)}
460+ >
461+ <CheckIcon
462+ className={cn(
463+ "size-3.5 shrink-0",
464+ workspace.id === workspaceId ? "opacity-100" : "opacity-0",
465+ )}
466+ />
467+ <span className="truncate">{workspace.name}</span>
468+ </button>
469+ ))}
470+ </div>
300471 ))}
301− </optgroup>
302− ))}
303− </Select>
304−
305− <div className="flex gap-1">
306− <Button
307− type="button"
308− size="sm"
309− variant={activeForm === "workspace" ? "secondary" : "ghost"}
310− className="h-7 flex-1 px-2 text-[11px]"
311− onClick={openWorkspaceForm}
312− >
313− + Workspace
314− </Button>
315− <Button
316− type="button"
317− size="sm"
318− variant={activeForm === "organization" ? "secondary" : "ghost"}
319− className="h-7 flex-1 px-2 text-[11px]"
320− onClick={openOrganizationForm}
321− >
322− + Org
323− </Button>
324− </div>
325−
326− {activeForm === "workspace" ? (
327− <form className="space-y-1.5 rounded-md border border-sidebar-border p-2" onSubmit={handleCreateWorkspace}>
328− <Input
329− value={workspaceName}
330− onChange={(event) => setWorkspaceName(event.target.value)}
331− placeholder="Workspace name"
332− className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]"
333− maxLength={64}
334− />
335− <Select
336− value={workspaceOrganizationId}
337− onChange={(event) => setWorkspaceOrganizationId(event.target.value)}
338− className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]"
339− >
340− <option value="">No organization</option>
341− {organizations.items.map((organization) => (
342− <option key={organization.id} value={organization.id}>
343− {organization.name}
344− </option>
345− ))}
346− </Select>
347− <Button
348− type="submit"
349− size="sm"
350− className="h-7 w-full text-[11px]"
351− disabled={creatingWorkspace}
352− >
353− {creatingWorkspace ? "Creating..." : "Create workspace"}
354− </Button>
355− </form>
356− ) : null}
357−
358− {activeForm === "organization" ? (
359− <form className="space-y-1.5 rounded-md border border-sidebar-border p-2" onSubmit={handleCreateOrganization}>
360− <Input
361− value={organizationName}
362− onChange={(event) => setOrganizationName(event.target.value)}
363− placeholder="Organization name"
364− className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]"
365− maxLength={64}
366− />
367− <Input
368− value={organizationSlug}
369− onChange={(event) => setOrganizationSlug(event.target.value)}
370− placeholder="Slug (optional)"
371− className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]"
372− maxLength={64}
373− />
374− <Button
375− type="submit"
376− size="sm"
377− className="h-7 w-full text-[11px]"
378− disabled={creatingOrganization}
379− >
380− {creatingOrganization ? "Creating..." : "Create organization"}
381− </Button>
382− </form>
383− ) : null}
384−
385− {workspaces.state === "error" ? (
386− <p className="text-[11px] text-destructive">{workspaces.message}</p>
387− ) : null}
388− {organizations.state === "error" ? (
389− <p className="text-[11px] text-destructive">{organizations.message}</p>
390− ) : null}
391− {status.message ? (
392− <p className={status.variant === "error" ? "text-[11px] text-destructive" : "text-[11px] text-sidebar-foreground/70"}>
393− {status.message}
394− </p>
472+ </div>
473+
474+ <div className="mt-2 space-y-1 border-t border-sidebar-border pt-2">
475+ <Button
476+ type="button"
477+ size="sm"
478+ variant={activeForm === "organization" ? "secondary" : "ghost"}
479+ className="h-7 w-full px-2 text-[11px]"
480+ onClick={openOrganizationForm}
481+ >
482+ <PlusIcon className="mr-1 size-3" />
483+ New organization
484+ </Button>
485+
486+ {activeForm === "workspace" ? (
487+ <form className="space-y-1.5 rounded-md border border-sidebar-border p-2" onSubmit={handleCreateWorkspace}>
488+ <p className="truncate text-[10px] uppercase tracking-wider text-sidebar-foreground/45">
489+ {selectedOrganizationLabel ? `Create in ${selectedOrganizationLabel}` : "Select organization"}
490+ </p>
491+ <Input
492+ value={workspaceName}
493+ onChange={(event) => setWorkspaceName(event.target.value)}
494+ placeholder="Workspace name"
495+ className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]"
496+ maxLength={64}
497+ />
498+ <Button
499+ type="submit"
500+ size="sm"
501+ className="h-7 w-full text-[11px]"
502+ disabled={workspaceCreationDisabled}
503+ >
504+ {creatingWorkspace ? "Creating..." : "Create workspace"}
505+ </Button>
506+ </form>
507+ ) : null}
508+
509+ {activeForm === "organization" ? (
510+ <form className="space-y-1.5 rounded-md border border-sidebar-border p-2" onSubmit={handleCreateOrganization}>
511+ <Input
512+ value={organizationName}
513+ onChange={(event) => setOrganizationName(event.target.value)}
514+ placeholder="Organization name"
515+ className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]"
516+ maxLength={64}
517+ />
518+ <Input
519+ value={organizationSlug}
520+ onChange={(event) => setOrganizationSlug(event.target.value)}
521+ placeholder="Slug (optional)"
522+ className="h-8 border-sidebar-border bg-sidebar px-2 text-[12px]"
523+ maxLength={64}
524+ />
525+ <Button
526+ type="submit"
527+ size="sm"
528+ className="h-7 w-full text-[11px]"
529+ disabled={creatingOrganization}
530+ >
531+ {creatingOrganization ? "Creating..." : "Create organization"}
532+ </Button>
533+ </form>
534+ ) : null}
535+ </div>
536+
537+ {workspaces.state === "error" ? (
538+ <p className="mt-2 text-[11px] text-destructive">{workspaces.message}</p>
539+ ) : null}
540+ {organizations.state === "error" ? (
541+ <p className="mt-2 text-[11px] text-destructive">{organizations.message}</p>
542+ ) : null}
543+ {status.message ? (
544+ <p className={cn(
545+ "mt-2 text-[11px]",
546+ status.variant === "error"
547+ ? "text-destructive"
548+ : "text-sidebar-foreground/70",
549+ )}>
550+ {status.message}
551+ </p>
552+ ) : null}
553+ </div>
395554 ) : null}
396555 </div>
397556 );
v2/apps/web/components/tools/tools-view.tsx+23−4
@@ -65,6 +65,9 @@ type SourceGroup = { · 64 unmodified lines
6565 toolCount: number;
6666 };
6767
68+const configuredControlPlaneBaseUrl =
69+ process.env.NEXT_PUBLIC_CONTROL_PLANE_BASE_URL?.trim() ?? "";
70+
6871 // ---------------------------------------------------------------------------
6972 // Search helpers (ported from old executor explorer-derived.ts)
7073 // ---------------------------------------------------------------------------
@@ -317,7 +320,9 @@ const TOOL_DESCRIPTION_CLASSES = [ · 246 unmodified lines
317320 // ToolsView (main export)
318321 // ---------------------------------------------------------------------------
319322
320−export function ToolsView() {
323+export function ToolsView(props: {
324+ mcpBaseUrl: string | null;
325+}) {
321326 const { workspaceId } = useWorkspace();
322327
323328 // --- Data ---
@@ -366,14 +371,28 @@ export function ToolsView() { · 42 unmodified lines
366371 const totalToolCount = workspaceTools.items.length;
367372
368373 const mcpUrl = useMemo(() => {
374+ if (props.mcpBaseUrl) {
375+ const configured = new URL(props.mcpBaseUrl);
376+ configured.pathname = "/v1/mcp";
377+ configured.searchParams.set("workspaceId", workspaceId);
378+ return configured.toString();
379+ }
380+
381+ if (configuredControlPlaneBaseUrl.length > 0 && /^https?:\/\//i.test(configuredControlPlaneBaseUrl)) {
382+ const configured = new URL(configuredControlPlaneBaseUrl);
383+ configured.pathname = "/v1/mcp";
384+ configured.searchParams.set("workspaceId", workspaceId);
385+ return configured.toString();
386+ }
387+
369388 if (typeof window === "undefined") {
370− return `/v1/mcp?workspaceId=${encodeURIComponent(workspaceId)}`;
389+ return `http://127.0.0.1:8788/v1/mcp?workspaceId=${encodeURIComponent(workspaceId)}`;
371390 }
372391
373− const url = new URL("/v1/mcp", window.location.origin);
392+ const url = new URL("/v1/mcp", "http://127.0.0.1:8788");
374393 url.searchParams.set("workspaceId", workspaceId);
375394 return url.toString();
376− }, [workspaceId]);
395+ }, [props.mcpBaseUrl, workspaceId]);
377396
378397 const installConfig = useMemo(
379398 () => getAddMcpInstallConfig(mcpUrl, inferServerName(workspaceId)),
v2/apps/web/lib/control-plane/atoms/settings.ts+2−2
@@ -66,11 +66,11 @@ export const upsertWorkspace = controlPlaneClient.mutation("workspaces", "upsert · 65 unmodified lines
6666
6767 export const toWorkspaceUpsertPayload = (input: {
6868 id?: Workspace["id"];
69− organizationId?: Workspace["organizationId"];
69+ organizationId: Workspace["organizationId"];
7070 name: string;
7171 }): UpsertWorkspacePayload => ({
7272 ...(input.id ? { id: input.id } : {}),
73− ...(input.organizationId !== undefined ? { organizationId: input.organizationId } : {}),
73+ organizationId: input.organizationId,
7474 name: input.name,
7575 });
7676
v2/apps/web/lib/control-plane/client.ts+13−4
@@ -1,12 +1,21 @@
11 import { createControlPlaneAtomClient } from "@executor-v2/management-api/client";
22 import { ControlPlaneAuthHeaders } from "@executor-v2/management-api/auth/principal";
33
4+const trim = (value: string | undefined): string | undefined => {
5+ const candidate = value?.trim();
6+ return candidate && candidate.length > 0 ? candidate : undefined;
7+};
8+
9+const defaultControlPlaneBaseUrl = "http://127.0.0.1:8788";
10+
411 const controlPlaneBaseUrl =
512 typeof window === "undefined"
6− ? process.env.CONTROL_PLANE_SERVER_BASE_URL ??
7− process.env.NEXT_PUBLIC_CONTROL_PLANE_BASE_URL ??
8− "http://127.0.0.1:4312/api/control-plane"
9− : process.env.NEXT_PUBLIC_CONTROL_PLANE_BASE_URL ?? "/api/control-plane";
13+ ? trim(process.env.CONTROL_PLANE_SERVER_BASE_URL)
14+ ?? trim(process.env.CONTROL_PLANE_UPSTREAM_URL)
15+ ?? trim(process.env.NEXT_PUBLIC_CONTROL_PLANE_BASE_URL)
16+ ?? defaultControlPlaneBaseUrl
17+ : trim(process.env.NEXT_PUBLIC_CONTROL_PLANE_BASE_URL)
18+ ?? defaultControlPlaneBaseUrl;
1019
1120 const controlPlaneAccountId = process.env.NEXT_PUBLIC_CONTROL_PLANE_ACCOUNT_ID;
1221
v2/bun.lock+2−1
@@ -42,7 +42,7 @@ · 41 unmodified lines
4242 "@executor-v2/management-api": "workspace:*",
4343 "@executor-v2/mcp-gateway": "workspace:*",
4444 "@executor-v2/persistence-ports": "workspace:*",
45− "@executor-v2/runtime-local-inproc": "workspace:*",
45+ "@executor-v2/runtime-cloudflare-worker-loader": "workspace:*",
4646 "@executor-v2/schema": "workspace:*",
4747 "@executor-v2/sdk": "workspace:*",
4848 "convex": "catalog:",
@@ -183,6 +183,7 @@ · 134 unmodified lines
183183 "@executor-v2/persistence-ports": "workspace:*",
184184 "@executor-v2/schema": "workspace:*",
185185 "@executor-v2/sdk": "workspace:*",
186+ "@modelcontextprotocol/sdk": "^1.26.0",
186187 "effect": "catalog:",
187188 },
188189 "devDependencies": {
v2/packages/engine/package.json+1−0
@@ -14,6 +14,7 @@ · 13 unmodified lines
1414 "@executor-v2/persistence-ports": "workspace:*",
1515 "@executor-v2/schema": "workspace:*",
1616 "@executor-v2/sdk": "workspace:*",
17+ "@modelcontextprotocol/sdk": "^1.26.0",
1718 "effect": "catalog:"
1819 },
1920 "devDependencies": {
v2/packages/engine/src/graphql-provider.test.ts+210−0
@@ -0,0 +1,210 @@
1+import { createServer, type IncomingMessage, type ServerResponse } from "node:http";
2+
3+import { describe, expect, it } from "@effect/vitest";
4+import { SourceSchema } from "@executor-v2/schema";
5+import * as Data from "effect/Data";
6+import * as Effect from "effect/Effect";
7+import * as Schema from "effect/Schema";
8+
9+import { makeGraphqlToolProvider } from "./graphql-provider";
10+
11+const decodeSource = Schema.decodeUnknownSync(SourceSchema);
12+
13+type TestServer = {
14+ endpoint: string;
15+ requests: Array<{
16+ headers: Record<string, string>;
17+ body: Record<string, unknown>;
18+ }>;
19+ close: () => Promise<void>;
20+};
21+
22+class GraphqlProviderTestServerReleaseError extends Data.TaggedError(
23+ "GraphqlProviderTestServerReleaseError",
24+)<{
25+ message: string;
26+}> {}
27+
28+const getHeader = (request: IncomingMessage, key: string): string | null => {
29+ const value = request.headers[key];
30+ if (typeof value === "string") {
31+ return value;
32+ }
33+
34+ if (Array.isArray(value)) {
35+ return value[0] ?? null;
36+ }
37+
38+ return null;
39+};
40+
41+const json = (response: ServerResponse, body: unknown): void => {
42+ response.statusCode = 200;
43+ response.setHeader("content-type", "application/json");
44+ response.end(JSON.stringify(body));
45+};
46+
47+const makeGraphqlTestServer = Effect.acquireRelease(
48+ Effect.promise<TestServer>(
49+ () =>
50+ new Promise<TestServer>((resolve, reject) => {
51+ const requests: TestServer["requests"] = [];
52+
53+ const server = createServer(async (request, response) => {
54+ if (request.method !== "POST") {
55+ response.statusCode = 405;
56+ response.end();
57+ return;
58+ }
59+
60+ const chunks: Array<Buffer> = [];
61+ for await (const chunk of request) {
62+ chunks.push(Buffer.from(chunk));
63+ }
64+
65+ const rawBody = Buffer.concat(chunks).toString("utf8");
66+ const parsedBody = JSON.parse(rawBody) as Record<string, unknown>;
67+ requests.push({
68+ headers: {
69+ "x-api-key": getHeader(request, "x-api-key") ?? "",
70+ "x-extra": getHeader(request, "x-extra") ?? "",
71+ },
72+ body: parsedBody,
73+ });
74+
75+ const query = typeof parsedBody.query === "string" ? parsedBody.query : "";
76+ if (query.includes("errorCase")) {
77+ json(response, {
78+ errors: [{ message: "boom" }],
79+ });
80+ return;
81+ }
82+
83+ json(response, {
84+ data: {
85+ ok: true,
86+ },
87+ });
88+ });
89+
90+ server.once("error", (error) => reject(error));
91+ server.listen(0, "127.0.0.1", () => {
92+ const address = server.address();
93+ if (!address || typeof address === "string") {
94+ reject(new Error("Failed to resolve GraphQL test server address"));
95+ return;
96+ }
97+
98+ resolve({
99+ endpoint: `http://127.0.0.1:${address.port}/graphql`,
100+ requests,
101+ close: () =>
102+ new Promise<void>((closeResolve, closeReject) => {
103+ server.close((error) => {
104+ if (error) {
105+ closeReject(error);
106+ return;
107+ }
108+ closeResolve();
109+ });
110+ }),
111+ });
112+ });
113+ }),
114+ ),
115+ (server) =>
116+ Effect.tryPromise({
117+ try: () => server.close(),
118+ catch: (cause) =>
119+ new GraphqlProviderTestServerReleaseError({
120+ message: cause instanceof Error ? cause.message : String(cause),
121+ }),
122+ }).pipe(Effect.orDie),
123+);
124+
125+describe("makeGraphqlToolProvider", () => {
126+ it.scoped("discovers a request tool and invokes GraphQL operations", () =>
127+ Effect.gen(function* () {
128+ const testServer = yield* makeGraphqlTestServer;
129+ const provider = makeGraphqlToolProvider();
130+
131+ const source = decodeSource({
132+ id: "src_graphql",
133+ workspaceId: "ws_local",
134+ name: "GraphQL Source",
135+ kind: "graphql",
136+ endpoint: "https://fallback.example/graphql",
137+ status: "connected",
138+ enabled: true,
139+ configJson: JSON.stringify({
140+ endpoint: testServer.endpoint,
141+ headers: {
142+ "x-api-key": "secret",
143+ },
144+ }),
145+ sourceHash: "source_hash",
146+ lastError: null,
147+ createdAt: Date.now(),
148+ updatedAt: Date.now(),
149+ });
150+
151+ const discovered = yield* provider.discoverFromSource!(source);
152+ expect(discovered.sourceHash).toBe("source_hash");
153+ expect(discovered.tools).toHaveLength(1);
154+ expect(discovered.tools[0]?.toolId).toBe("request");
155+
156+ const tool = discovered.tools[0]!;
157+ const success = yield* provider.invoke({
158+ source,
159+ tool,
160+ args: {
161+ query: "query viewer { viewer { id } }",
162+ variables: {
163+ includePrivate: false,
164+ },
165+ operationName: "viewer",
166+ headers: {
167+ "x-extra": "extra",
168+ },
169+ },
170+ });
171+
172+ expect(success.isError).toBe(false);
173+ expect(success.output).toMatchObject({
174+ status: 200,
175+ body: {
176+ data: {
177+ ok: true,
178+ },
179+ },
180+ });
181+
182+ const failing = yield* provider.invoke({
183+ source,
184+ tool,
185+ args: {
186+ query: "query errorCase { viewer { id } }",
187+ },
188+ });
189+
190+ expect(failing.isError).toBe(true);
191+ expect(failing.output).toMatchObject({
192+ status: 200,
193+ body: {
194+ errors: [{ message: "boom" }],
195+ },
196+ });
197+
198+ expect(testServer.requests).toHaveLength(2);
199+ expect(testServer.requests[0]?.headers["x-api-key"]).toBe("secret");
200+ expect(testServer.requests[0]?.headers["x-extra"]).toBe("extra");
201+ expect(testServer.requests[0]?.body).toMatchObject({
202+ query: "query viewer { viewer { id } }",
203+ variables: {
204+ includePrivate: false,
205+ },
206+ operationName: "viewer",
207+ });
208+ }),
209+ );
210+});
v2/packages/engine/src/graphql-provider.ts+195−0
@@ -0,0 +1,195 @@
1+import type {
2+ CanonicalToolDescriptor,
3+ Source,
4+} from "@executor-v2/schema";
5+import * as Effect from "effect/Effect";
6+import * as ParseResult from "effect/ParseResult";
7+import * as Schema from "effect/Schema";
8+
9+import {
10+ collectSourceHeaders,
11+ parseSourceConfig,
12+ readStringRecord,
13+ resolveSourceEndpoint,
14+} from "./source-config";
15+import { ToolProviderError, type ToolProvider } from "./tool-providers";
16+
17+const GraphqlInvocationPayloadSchema = Schema.Struct({
18+ kind: Schema.Literal("graphql_request"),
19+});
20+
21+const GraphqlInvokeArgsSchema = Schema.Struct({
22+ query: Schema.String,
23+ variables: Schema.optional(
24+ Schema.Record({
25+ key: Schema.String,
26+ value: Schema.Unknown,
27+ }),
28+ ),
29+ operationName: Schema.optional(Schema.String),
30+ headers: Schema.optional(
31+ Schema.Record({
32+ key: Schema.String,
33+ value: Schema.String,
34+ }),
35+ ),
36+});
37+
38+const decodeGraphqlInvocationPayload = Schema.decodeUnknown(GraphqlInvocationPayloadSchema);
39+const decodeGraphqlInvokeArgs = Schema.decodeUnknown(GraphqlInvokeArgsSchema);
40+
41+const toGraphqlProviderError = (
42+ operation: string,
43+ message: string,
44+ cause: unknown,
45+): ToolProviderError =>
46+ new ToolProviderError({
47+ operation,
48+ providerKind: "graphql",
49+ message,
50+ details: ParseResult.isParseError(cause)
51+ ? ParseResult.TreeFormatter.formatErrorSync(cause)
52+ : String(cause),
53+ });
54+
55+const parseGraphqlResponseBody = (
56+ response: Response,
57+): Effect.Effect<unknown, ToolProviderError> =>
58+ Effect.tryPromise({
59+ try: async () => {
60+ const contentType = response.headers.get("content-type")?.toLowerCase() ?? "";
61+ if (contentType.includes("application/json")) {
62+ return await response.json();
63+ }
64+
65+ return await response.text();
66+ },
67+ catch: (cause) =>
68+ toGraphqlProviderError(
69+ "invoke.decode_response",
70+ "Failed to decode GraphQL response body",
71+ cause,
72+ ),
73+ });
74+
75+const hasGraphqlErrors = (value: unknown): boolean => {
76+ if (!value || typeof value !== "object" || Array.isArray(value)) {
77+ return false;
78+ }
79+
80+ return Array.isArray((value as { errors?: unknown }).errors);
81+};
82+
83+const descriptorForSource = (source: Source): CanonicalToolDescriptor => ({
84+ providerKind: "graphql",
85+ sourceId: source.id,
86+ workspaceId: source.workspaceId,
87+ toolId: "request",
88+ name: "GraphQL request",
89+ description: "Execute a GraphQL operation with args.query, args.variables, and args.operationName.",
90+ invocationMode: "graphql",
91+ availability: "remote_capable",
92+ providerPayload: {
93+ kind: "graphql_request",
94+ },
95+});
96+
97+export const makeGraphqlToolProvider = (): ToolProvider => ({
98+ kind: "graphql",
99+
100+ discoverFromSource: (source) =>
101+ Effect.succeed({
102+ sourceHash: source.sourceHash,
103+ tools: [descriptorForSource(source)],
104+ }),
105+
106+ invoke: (input) =>
107+ Effect.gen(function* () {
108+ if (!input.source) {
109+ return yield* new ToolProviderError({
110+ operation: "invoke.validate_source",
111+ providerKind: "graphql",
112+ message: "GraphQL provider requires a source",
113+ details: null,
114+ });
115+ }
116+ const source = input.source;
117+
118+ yield* decodeGraphqlInvocationPayload(input.tool.providerPayload).pipe(
119+ Effect.mapError((cause) =>
120+ toGraphqlProviderError(
121+ "invoke.decode_payload",
122+ `Invalid GraphQL invocation payload for tool: ${input.tool.toolId}`,
123+ cause,
124+ ),
125+ ),
126+ );
127+
128+ const args = yield* decodeGraphqlInvokeArgs(input.args).pipe(
129+ Effect.mapError((cause) =>
130+ toGraphqlProviderError(
131+ "invoke.decode_args",
132+ `Invalid GraphQL args for tool: ${input.tool.toolId}`,
133+ cause,
134+ ),
135+ ),
136+ );
137+
138+ const query = args.query.trim();
139+ if (query.length === 0) {
140+ return yield* new ToolProviderError({
141+ operation: "invoke.validate_args",
142+ providerKind: "graphql",
143+ message: "GraphQL query must be non-empty",
144+ details: input.tool.toolId,
145+ });
146+ }
147+
148+ const config = parseSourceConfig(source);
149+ const endpoint = resolveSourceEndpoint(source, config, ["endpoint", "url"]);
150+ if (endpoint.trim().length === 0) {
151+ return yield* new ToolProviderError({
152+ operation: "invoke.validate_source",
153+ providerKind: "graphql",
154+ message: "GraphQL source endpoint is required",
155+ details: source.id,
156+ });
157+ }
158+
159+ const headers = new Headers({
160+ "content-type": "application/json",
161+ ...collectSourceHeaders(config),
162+ ...readStringRecord(args.headers),
163+ });
164+
165+ const response = yield* Effect.tryPromise({
166+ try: () =>
167+ fetch(endpoint, {
168+ method: "POST",
169+ headers,
170+ body: JSON.stringify({
171+ query,
172+ variables: args.variables,
173+ operationName: args.operationName,
174+ }),
175+ }),
176+ catch: (cause) =>
177+ toGraphqlProviderError(
178+ "invoke.http_request",
179+ `GraphQL request failed for source: ${source.name}`,
180+ cause,
181+ ),
182+ });
183+
184+ const body = yield* parseGraphqlResponseBody(response);
185+
186+ return {
187+ output: {
188+ status: response.status,
189+ headers: Object.fromEntries(response.headers.entries()),
190+ body,
191+ },
192+ isError: response.status >= 400 || hasGraphqlErrors(body),
193+ };
194+ }),
195+});
v2/packages/engine/src/index.ts+2−0
@@ -66,6 +66,8 @@ export { · 65 unmodified lines
6666 makeOpenApiToolProvider,
6767 openApiToolDescriptorsFromManifest,
6868 } from "./openapi-provider";
69+export { makeMcpToolProvider, type MakeMcpToolProviderOptions } from "./mcp-provider";
70+export { makeGraphqlToolProvider } from "./graphql-provider";
6971
7072 export {
7173 ToolProviderRegistryLive,
v2/packages/engine/src/mcp-provider.test.ts+143−0
@@ -0,0 +1,143 @@
1+import { describe, expect, it } from "@effect/vitest";
2+import { SourceSchema, type CanonicalToolDescriptor } from "@executor-v2/schema";
3+import * as Effect from "effect/Effect";
4+import * as Schema from "effect/Schema";
5+
6+import { makeMcpToolProvider } from "./mcp-provider";
7+
8+const decodeSource = Schema.decodeUnknownSync(SourceSchema);
9+
10+describe("makeMcpToolProvider", () => {
11+ it.effect("discovers MCP tools and produces stable unique tool ids", () =>
12+ Effect.gen(function* () {
13+ let closeCalls = 0;
14+
15+ const provider = makeMcpToolProvider({
16+ connector: async (input) => {
17+ expect(input.endpoint).toBe("https://mcp.example/mcp");
18+ expect(input.transport).toBe("streamable-http");
19+ expect(input.queryParams).toEqual({
20+ workspace: "ws_local",
21+ });
22+
23+ return {
24+ client: {
25+ listTools: async () => ({
26+ tools: [
27+ { name: "Read File", description: "Reads a file" },
28+ { name: "Read.File", description: "Also reads a file" },
29+ { name: "List Users", description: null },
30+ ],
31+ }),
32+ callTool: async () => ({
33+ content: [{ type: "text", text: "ok" }],
34+ isError: false,
35+ }),
36+ },
37+ close: async () => {
38+ closeCalls += 1;
39+ },
40+ };
41+ },
42+ });
43+
44+ const source = decodeSource({
45+ id: "src_mcp",
46+ workspaceId: "ws_local",
47+ name: "MCP Source",
48+ kind: "mcp",
49+ endpoint: "https://fallback.example/mcp",
50+ status: "connected",
51+ enabled: true,
52+ configJson: JSON.stringify({
53+ url: "https://mcp.example/mcp",
54+ transport: "streamable-http",
55+ queryParams: {
56+ workspace: "ws_local",
57+ },
58+ }),
59+ sourceHash: "hash_1",
60+ lastError: null,
61+ createdAt: Date.now(),
62+ updatedAt: Date.now(),
63+ });
64+
65+ const discovered = yield* provider.discoverFromSource!(source);
66+ expect(discovered.sourceHash).toBe("hash_1");
67+ expect(discovered.tools.map((tool) => tool.toolId)).toEqual([
68+ "read_file",
69+ "read_file_2",
70+ "list_users",
71+ ]);
72+ expect(closeCalls).toBe(1);
73+ }),
74+ );
75+
76+ it.effect("invokes MCP tool and propagates isError from MCP result payload", () =>
77+ Effect.gen(function* () {
78+ const provider = makeMcpToolProvider({
79+ connector: async () => ({
80+ client: {
81+ listTools: async () => ({ tools: [] }),
82+ callTool: async (input) => {
83+ expect(input.name).toBe("echo");
84+ expect(input.arguments).toEqual({
85+ value: "hello",
86+ });
87+
88+ return {
89+ isError: true,
90+ content: [{ type: "text", text: "denied" }],
91+ };
92+ },
93+ },
94+ close: async () => undefined,
95+ }),
96+ });
97+
98+ const source = decodeSource({
99+ id: "src_mcp",
100+ workspaceId: "ws_local",
101+ name: "MCP Source",
102+ kind: "mcp",
103+ endpoint: "https://mcp.example/mcp",
104+ status: "connected",
105+ enabled: true,
106+ configJson: "{}",
107+ sourceHash: null,
108+ lastError: null,
109+ createdAt: Date.now(),
110+ updatedAt: Date.now(),
111+ });
112+
113+ const tool: CanonicalToolDescriptor = {
114+ providerKind: "mcp",
115+ sourceId: source.id,
116+ workspaceId: source.workspaceId,
117+ toolId: "echo",
118+ name: "Echo",
119+ description: null,
120+ invocationMode: "mcp",
121+ availability: "remote_capable",
122+ providerPayload: {
123+ kind: "mcp_tool",
124+ toolName: "echo",
125+ },
126+ };
127+
128+ const result = yield* provider.invoke({
129+ source,
130+ tool,
131+ args: {
132+ value: "hello",
133+ },
134+ });
135+
136+ expect(result.isError).toBe(true);
137+ expect(result.output).toEqual({
138+ isError: true,
139+ content: [{ type: "text", text: "denied" }],
140+ });
141+ }),
142+ );
143+});
v2/packages/engine/src/mcp-provider.ts+389−0
@@ -0,0 +1,389 @@
1+import {
2+ type CanonicalToolDescriptor,
3+ type Source,
4+} from "@executor-v2/schema";
5+import { Client } from "@modelcontextprotocol/sdk/client/index.js";
6+import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
7+import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
8+import * as Effect from "effect/Effect";
9+import * as ParseResult from "effect/ParseResult";
10+import * as Schema from "effect/Schema";
11+
12+import {
13+ collectSourceHeaders,
14+ parseSourceConfig,
15+ readMcpTransportFromConfig,
16+ readQueryParamsFromConfig,
17+ resolveSourceEndpoint,
18+ type McpTransportPreference,
19+} from "./source-config";
20+import { ToolProviderError, type ToolProvider } from "./tool-providers";
21+
22+type McpClientLike = {
23+ listTools: () => Promise<unknown>;
24+ callTool: (input: { name: string; arguments: Record<string, unknown> }) => Promise<unknown>;
25+};
26+
27+type McpConnection = {
28+ client: McpClientLike;
29+ close: () => Promise<void>;
30+};
31+
32+type McpConnectorInput = {
33+ endpoint: string;
34+ transport: McpTransportPreference;
35+ queryParams: Record<string, string>;
36+ headers: Record<string, string>;
37+};
38+
39+export type McpConnector = (input: McpConnectorInput) => Promise<McpConnection>;
40+
41+type McpToolSummary = {
42+ name: string;
43+ description: string | null;
44+};
45+
46+const McpInvocationPayloadSchema = Schema.Struct({
47+ kind: Schema.Literal("mcp_tool"),
48+ toolName: Schema.String,
49+});
50+
51+const McpInvokeArgsSchema = Schema.Record({
52+ key: Schema.String,
53+ value: Schema.Unknown,
54+});
55+
56+const decodeMcpInvocationPayload = Schema.decodeUnknown(McpInvocationPayloadSchema);
57+const decodeMcpInvokeArgs = Schema.decodeUnknown(McpInvokeArgsSchema);
58+
59+const toMcpProviderError = (
60+ operation: string,
61+ message: string,
62+ cause: unknown,
63+): ToolProviderError =>
64+ new ToolProviderError({
65+ operation,
66+ providerKind: "mcp",
67+ message,
68+ details: ParseResult.isParseError(cause)
69+ ? ParseResult.TreeFormatter.formatErrorSync(cause)
70+ : String(cause),
71+ });
72+
73+const mergeHeadersForFetch = (
74+ input: RequestInfo | URL,
75+ init: RequestInit | undefined,
76+ headers: Record<string, string>,
77+): Promise<Response> => {
78+ const mergedHeaders = new Headers(init?.headers ?? {});
79+
80+ for (const [key, value] of Object.entries(headers)) {
81+ mergedHeaders.set(key, value);
82+ }
83+
84+ return fetch(input, {
85+ ...init,
86+ headers: mergedHeaders,
87+ });
88+};
89+
90+const createEndpoint = (
91+ endpoint: string,
92+ queryParams: Record<string, string>,
93+): URL => {
94+ const url = new URL(endpoint);
95+
96+ for (const [key, value] of Object.entries(queryParams)) {
97+ url.searchParams.set(key, value);
98+ }
99+
100+ return url;
101+};
102+
103+const connectMcpWithSdk: McpConnector = async (input) => {
104+ const endpoint = createEndpoint(input.endpoint, input.queryParams);
105+ const requestInit = Object.keys(input.headers).length > 0
106+ ? { headers: input.headers }
107+ : undefined;
108+
109+ const client = new Client(
110+ {
111+ name: "executor-v2-engine",
112+ version: "0.1.0",
113+ },
114+ { capabilities: {} },
115+ );
116+
117+ if (input.transport === "sse") {
118+ await client.connect(new SSEClientTransport(endpoint, {
119+ requestInit,
120+ eventSourceInit: requestInit
121+ ? {
122+ fetch: (requestInput, requestOptions) =>
123+ mergeHeadersForFetch(requestInput, requestOptions, input.headers),
124+ }
125+ : undefined,
126+ }));
127+
128+ return {
129+ client,
130+ close: () => client.close(),
131+ };
132+ }
133+
134+ if (input.transport === "streamable-http") {
135+ await client.connect(new StreamableHTTPClientTransport(endpoint, {
136+ requestInit,
137+ }));
138+
139+ return {
140+ client,
141+ close: () => client.close(),
142+ };
143+ }
144+
145+ try {
146+ await client.connect(new StreamableHTTPClientTransport(endpoint, {
147+ requestInit,
148+ }));
149+
150+ return {
151+ client,
152+ close: () => client.close(),
153+ };
154+ } catch {
155+ await client.connect(new SSEClientTransport(endpoint, {
156+ requestInit,
157+ eventSourceInit: requestInit
158+ ? {
159+ fetch: (requestInput, requestOptions) =>
160+ mergeHeadersForFetch(requestInput, requestOptions, input.headers),
161+ }
162+ : undefined,
163+ }));
164+
165+ return {
166+ client,
167+ close: () => client.close(),
168+ };
169+ }
170+};
171+
172+const extractMcpTools = (value: unknown): Array<McpToolSummary> => {
173+ if (!value || typeof value !== "object" || Array.isArray(value)) {
174+ return [];
175+ }
176+
177+ const tools = (value as { tools?: unknown }).tools;
178+ if (!Array.isArray(tools)) {
179+ return [];
180+ }
181+
182+ return tools
183+ .map((tool): McpToolSummary | null => {
184+ if (!tool || typeof tool !== "object" || Array.isArray(tool)) {
185+ return null;
186+ }
187+
188+ const toolRecord = tool as Record<string, unknown>;
189+ const name = typeof toolRecord.name === "string" ? toolRecord.name.trim() : "";
190+ if (name.length === 0) {
191+ return null;
192+ }
193+
194+ const description = typeof toolRecord.description === "string"
195+ ? toolRecord.description
196+ : null;
197+
198+ return {
199+ name,
200+ description,
201+ };
202+ })
203+ .filter((tool): tool is McpToolSummary => tool !== null);
204+};
205+
206+const sanitizeToolId = (value: string): string => {
207+ const normalized = value
208+ .trim()
209+ .toLowerCase()
210+ .replace(/[^a-z0-9]+/g, "_")
211+ .replace(/^_+|_+$/g, "");
212+
213+ return normalized.length > 0 ? normalized : "tool";
214+};
215+
216+const uniqueToolId = (value: string, byBase: Map<string, number>): string => {
217+ const base = sanitizeToolId(value);
218+ const count = (byBase.get(base) ?? 0) + 1;
219+ byBase.set(base, count);
220+
221+ return count === 1 ? base : `${base}_${count}`;
222+};
223+
224+const withMcpConnection = <A>(
225+ source: Source,
226+ connector: McpConnector,
227+ operation: string,
228+ run: (connection: McpConnection) => Effect.Effect<A, ToolProviderError>,
229+): Effect.Effect<A, ToolProviderError> =>
230+ Effect.scoped(
231+ Effect.gen(function* () {
232+ const config = parseSourceConfig(source);
233+ const endpoint = resolveSourceEndpoint(source, config, ["url", "endpoint"]);
234+ if (endpoint.trim().length === 0) {
235+ return yield* new ToolProviderError({
236+ operation,
237+ providerKind: "mcp",
238+ message: "MCP source endpoint is required",
239+ details: source.id,
240+ });
241+ }
242+
243+ const connection = yield* Effect.acquireRelease(
244+ Effect.tryPromise({
245+ try: () =>
246+ connector({
247+ endpoint,
248+ transport: readMcpTransportFromConfig(config),
249+ queryParams: readQueryParamsFromConfig(config),
250+ headers: collectSourceHeaders(config),
251+ }),
252+ catch: (cause) =>
253+ toMcpProviderError(
254+ operation,
255+ `Failed to connect to MCP source: ${source.name}`,
256+ cause,
257+ ),
258+ }),
259+ (connected) =>
260+ Effect.tryPromise({
261+ try: () => connected.close(),
262+ catch: () => undefined,
263+ }).pipe(Effect.orDie),
264+ );
265+
266+ return yield* run(connection);
267+ }),
268+ );
269+
270+export type MakeMcpToolProviderOptions = {
271+ connector?: McpConnector;
272+};
273+
274+export const makeMcpToolProvider = (
275+ options: MakeMcpToolProviderOptions = {},
276+): ToolProvider => {
277+ const connector = options.connector ?? connectMcpWithSdk;
278+
279+ return {
280+ kind: "mcp",
281+
282+ discoverFromSource: (source) =>
283+ withMcpConnection(
284+ source,
285+ connector,
286+ "discover.connect",
287+ (connection) =>
288+ Effect.gen(function* () {
289+ const listed = yield* Effect.tryPromise({
290+ try: () => connection.client.listTools(),
291+ catch: (cause) =>
292+ toMcpProviderError(
293+ "discover.list_tools",
294+ `Failed to list MCP tools for source: ${source.name}`,
295+ cause,
296+ ),
297+ });
298+
299+ const discoveredTools = extractMcpTools(listed);
300+ const usedToolIds = new Map<string, number>();
301+
302+ const tools: ReadonlyArray<CanonicalToolDescriptor> = discoveredTools.map((tool) => ({
303+ providerKind: "mcp",
304+ sourceId: source.id,
305+ workspaceId: source.workspaceId,
306+ toolId: uniqueToolId(tool.name, usedToolIds),
307+ name: tool.name,
308+ description: tool.description,
309+ invocationMode: "mcp",
310+ availability: "remote_capable",
311+ providerPayload: {
312+ kind: "mcp_tool",
313+ toolName: tool.name,
314+ },
315+ }));
316+
317+ return {
318+ sourceHash: source.sourceHash,
319+ tools,
320+ };
321+ }),
322+ ),
323+
324+ invoke: (input) =>
325+ Effect.gen(function* () {
326+ if (!input.source) {
327+ return yield* new ToolProviderError({
328+ operation: "invoke.validate_source",
329+ providerKind: "mcp",
330+ message: "MCP provider requires a source",
331+ details: null,
332+ });
333+ }
334+
335+ const payload = yield* decodeMcpInvocationPayload(input.tool.providerPayload).pipe(
336+ Effect.mapError((cause) =>
337+ toMcpProviderError(
338+ "invoke.decode_payload",
339+ `Invalid MCP invocation payload for tool: ${input.tool.toolId}`,
340+ cause,
341+ ),
342+ ),
343+ );
344+
345+ const args = yield* decodeMcpInvokeArgs(input.args).pipe(
346+ Effect.mapError((cause) =>
347+ toMcpProviderError(
348+ "invoke.decode_args",
349+ `Invalid MCP tool args for tool: ${input.tool.toolId}`,
350+ cause,
351+ ),
352+ ),
353+ );
354+
355+ return yield* withMcpConnection(
356+ input.source,
357+ connector,
358+ "invoke.connect",
359+ (connection) =>
360+ Effect.gen(function* () {
361+ const result = yield* Effect.tryPromise({
362+ try: () =>
363+ connection.client.callTool({
364+ name: payload.toolName,
365+ arguments: args,
366+ }),
367+ catch: (cause) =>
368+ toMcpProviderError(
369+ "invoke.call_tool",
370+ `Failed MCP tool invocation: ${payload.toolName}`,
371+ cause,
372+ ),
373+ });
374+
375+ const isError = Boolean(
376+ result &&
377+ typeof result === "object" &&
378+ (result as { isError?: unknown }).isError === true,
379+ );
380+
381+ return {
382+ output: result,
383+ isError,
384+ };
385+ }),
386+ );
387+ }),
388+ };
389+};
v2/packages/engine/src/source-config.ts+143−0
@@ -0,0 +1,143 @@
1+import type { Source } from "@executor-v2/schema";
2+
3+export type SourceConfig = Record<string, unknown>;
4+
5+export type McpTransportPreference = "auto" | "streamable-http" | "sse";
6+
7+const normalizeString = (value: unknown): string | null => {
8+ if (typeof value !== "string") {
9+ return null;
10+ }
11+
12+ const trimmed = value.trim();
13+ return trimmed.length > 0 ? trimmed : null;
14+};
15+
16+const asRecord = (value: unknown): Record<string, unknown> => {
17+ if (!value || typeof value !== "object" || Array.isArray(value)) {
18+ return {};
19+ }
20+
21+ return value as Record<string, unknown>;
22+};
23+
24+const parseJson = (value: string): unknown | null => {
25+ try {
26+ return JSON.parse(value);
27+ } catch {
28+ return null;
29+ }
30+};
31+
32+export const parseSourceConfig = (source: Source): SourceConfig =>
33+ asRecord(parseJson(source.configJson));
34+
35+export const resolveSourceEndpoint = (
36+ source: Source,
37+ config: SourceConfig,
38+ candidates: ReadonlyArray<string>,
39+): string => {
40+ for (const candidate of candidates) {
41+ const value = normalizeString(config[candidate]);
42+ if (value) {
43+ return value;
44+ }
45+ }
46+
47+ return source.endpoint;
48+};
49+
50+export const readStringRecord = (
51+ value: unknown,
52+): Record<string, string> => {
53+ const record = asRecord(value);
54+ const normalized: Record<string, string> = {};
55+
56+ for (const [rawKey, rawValue] of Object.entries(record)) {
57+ const key = normalizeString(rawKey);
58+ const resolvedValue = normalizeString(rawValue);
59+ if (!key || !resolvedValue) {
60+ continue;
61+ }
62+
63+ normalized[key] = resolvedValue;
64+ }
65+
66+ return normalized;
67+};
68+
69+export const readQueryParamsFromConfig = (
70+ config: SourceConfig,
71+): Record<string, string> => {
72+ const queryParams = asRecord(config.queryParams);
73+ const normalized: Record<string, string> = {};
74+
75+ for (const [key, value] of Object.entries(queryParams)) {
76+ const normalizedKey = normalizeString(key);
77+ if (!normalizedKey) {
78+ continue;
79+ }
80+
81+ if (
82+ typeof value === "string" ||
83+ typeof value === "number" ||
84+ typeof value === "boolean" ||
85+ typeof value === "bigint"
86+ ) {
87+ normalized[normalizedKey] = String(value);
88+ }
89+ }
90+
91+ return normalized;
92+};
93+
94+export const readMcpTransportFromConfig = (
95+ config: SourceConfig,
96+): McpTransportPreference => {
97+ const value = normalizeString(config.transport)?.toLowerCase();
98+ if (value === "streamable-http" || value === "sse") {
99+ return value;
100+ }
101+
102+ return "auto";
103+};
104+
105+export const collectSourceHeaders = (
106+ config: SourceConfig,
107+): Record<string, string> => {
108+ const configuredHeaders = readStringRecord(config.headers);
109+ const auth = asRecord(config.auth);
110+ const authType = normalizeString(auth.type)?.toLowerCase();
111+ const authHeaders: Record<string, string> = {};
112+
113+ if (authType === "bearer") {
114+ const token = normalizeString(auth.token) ?? normalizeString(auth.value);
115+ if (token) {
116+ authHeaders.Authorization = `Bearer ${token}`;
117+ }
118+ }
119+
120+ if (authType === "apikey" || authType === "api_key" || authType === "apiKey") {
121+ const headerName = normalizeString(auth.header) ?? "Authorization";
122+ const apiKey = normalizeString(auth.value);
123+ if (apiKey) {
124+ authHeaders[headerName] = apiKey;
125+ }
126+ }
127+
128+ if (authType === "basic") {
129+ const username = normalizeString(auth.username);
130+ const password = normalizeString(auth.password);
131+ if (username && password) {
132+ authHeaders.Authorization = `Basic ${Buffer.from(
133+ `${username}:${password}`,
134+ "utf8",
135+ ).toString("base64")}`;
136+ }
137+ }
138+
139+ return {
140+ ...configuredHeaders,
141+ ...authHeaders,
142+ };
143+};
v2/packages/management-api/src/auth/workspace-membership.ts+13−15
@@ -65,23 +65,21 @@ export const deriveWorkspaceMembershipsForPrincipal = (input: { · 64 unmodified lines
6565 });
6666 }
6767
68− if (input.workspace.organizationId !== null) {
69− for (const membership of input.organizationMemberships) {
70− if (membership.accountId !== input.principalAccountId) {
71− continue;
72− }
73−
74− if (membership.organizationId !== input.workspace.organizationId) {
75− continue;
76− }
68+ for (const membership of input.organizationMemberships) {
69+ if (membership.accountId !== input.principalAccountId) {
70+ continue;
71+ }
7772
78− candidates.push({
79− role: membership.role,
80− status: toWorkspaceMembershipStatus(membership.status),
81− grantedAt: membership.joinedAt ?? membership.createdAt,
82− updatedAt: membership.updatedAt,
83− });
73+ if (membership.organizationId !== input.workspace.organizationId) {
74+ continue;
8475 }
76+
77+ candidates.push({
78+ role: membership.role,
79+ status: toWorkspaceMembershipStatus(membership.status),
80+ grantedAt: membership.joinedAt ?? membership.createdAt,
81+ updatedAt: membership.updatedAt,
82+ });
8583 }
8684
8785 const activeCandidates = candidates.filter(
v2/packages/management-api/src/credentials/api.ts+7−1
@@ -18,7 +18,13 @@ const RequiredUpsertCredentialBindingPayloadSchema = SourceCredentialBindingSche · 17 unmodified lines
1818 );
1919
2020 const OptionalUpsertCredentialBindingPayloadSchema = SourceCredentialBindingSchema.pipe(
21− Schema.pick("id", "accountId", "additionalHeadersJson", "boundAuthFingerprint"),
21+ Schema.pick(
22+ "id",
23+ "accountId",
24+ "secretProvider",
25+ "additionalHeadersJson",
26+ "boundAuthFingerprint",
27+ ),
2228 Schema.partialWith({ exact: true }),
2329 );
2430
v2/packages/management-api/src/organizations/api.ts+1−1
@@ -14,7 +14,7 @@ const RequiredUpsertOrganizationPayloadSchema = OrganizationSchema.pipe( · 13 unmodified lines
1414 );
1515
1616 const OptionalUpsertOrganizationPayloadSchema = OrganizationSchema.pipe(
17− Schema.pick("id", "status"),
17+ Schema.pick("id", "status", "createdByAccountId"),
1818 Schema.partialWith({ exact: true }),
1919 );
2020
v2/packages/management-api/src/organizations/http.ts+15−1
@@ -124,8 +124,22 @@ export const ControlPlaneOrganizationsLive = HttpApiBuilder.group( · 123 unmodified lines
124124 });
125125 }
126126
127+ const payloadWithCreator = {
128+ ...payload,
129+ createdByAccountId: actor.principal.accountId,
130+ };
131+
132+ const existingOrganizations = yield* service.listOrganizations();
133+ const organizationExists = existingOrganizations.some(
134+ (organization) => organization.id === payload.id,
135+ );
136+
137+ if (!organizationExists) {
138+ return yield* service.upsertOrganization({ payload: payloadWithCreator });
139+ }
140+
127141 return yield* withPolicy(requireManageOrganization(payload.id))(
128− service.upsertOrganization({ payload }),
142+ service.upsertOrganization({ payload: payloadWithCreator }),
129143 ).pipe(Effect.provideService(Actor, actor));
130144 }).pipe(
131145 Effect.catchTag("ActorUnauthenticatedError", (cause) =>
v2/packages/management-api/src/workspaces/api.ts+2−2
@@ -10,11 +10,11 @@ import { · 9 unmodified lines
1010 } from "../errors";
1111
1212 const RequiredUpsertWorkspacePayloadSchema = WorkspaceSchema.pipe(
13− Schema.pick("name"),
13+ Schema.pick("name", "organizationId"),
1414 );
1515
1616 const OptionalUpsertWorkspacePayloadSchema = WorkspaceSchema.pipe(
17− Schema.pick("id", "organizationId"),
17+ Schema.pick("id"),
1818 Schema.partialWith({ exact: true }),
1919 );
2020
v2/packages/management-api/src/workspaces/http.ts+8−32
@@ -17,7 +17,6 @@ import { · 16 unmodified lines
1717 import * as Effect from "effect/Effect";
1818
1919 import {
20− ControlPlaneBadRequestError,
2120 ControlPlaneForbiddenError,
2221 ControlPlaneStorageError,
2322 ControlPlaneUnauthorizedError,
@@ -102,13 +101,10 @@ const filterVisibleWorkspaces = ( · 78 unmodified lines
102101 permission: "workspace:read",
103102 workspaceId: workspace.id,
104103 })
105− || (
106− workspace.organizationId !== null
107− && actor.hasPermission({
108− permission: "workspace:read",
109− organizationId: workspace.organizationId,
110− })
111− )
104+ || actor.hasPermission({
105+ permission: "workspace:read",
106+ organizationId: workspace.organizationId,
107+ })
112108 );
113109
114110 export const ControlPlaneWorkspacesLive = HttpApiBuilder.group(
@@ -143,32 +139,12 @@ export const ControlPlaneWorkspacesLive = HttpApiBuilder.group( · 28 unmodified lines
143139 const service = yield* ControlPlaneService;
144140 const actor = yield* resolveActor;
145141
146− const workspacePolicy = (() => {
147− if (payload.id && payload.organizationId !== null && payload.organizationId !== undefined) {
148− return any([
142+ const workspacePolicy = payload.id
143+ ? any([
149144 requireManageWorkspace(payload.id),
150145 requireManageWorkspaceInOrganization(payload.organizationId),
151− ]);
152− }
153−
154− if (payload.id) {
155− return requireManageWorkspace(payload.id);
156− }
157−
158− if (payload.organizationId !== null && payload.organizationId !== undefined) {
159− return requireManageWorkspaceInOrganization(payload.organizationId);
160− }
161−
162− return null;
163− })();
164−
165− if (!workspacePolicy) {
166− return yield* new ControlPlaneBadRequestError({
167− operation: "workspaces.upsert",
168− message: "workspace id or organizationId is required",
169− details: "payload.id or payload.organizationId must be provided for scoped authorization",
170− });
171− }
146+ ])
147+ : requireManageWorkspaceInOrganization(payload.organizationId);
172148
173149 return yield* withPolicy(workspacePolicy)(
174150 service.upsertWorkspace({ payload }),
v2/packages/runtime-cloudflare-worker-loader/src/index.ts+1−1
@@ -127,7 +127,7 @@ const resolveConfig = ( · 126 unmodified lines
127127 const callbackInternalSecret =
128128 options.callbackInternalSecret ??
129129 normalizeString(
130− env.CLOUDFLARE_SANDBOX_CALLBACK_INTERNAL_SECRET ??
130+ env.CLOUDFLARE_SANDBOX_CALLBACK_SECRET ??
131131 env.EXECUTOR_INTERNAL_TOKEN,
132132 ) ??
133133 null;
v2/packages/schema/src/enums.ts+4−0
@@ -13,6 +13,9 @@ export const CredentialProviderSchema = Schema.Literal( · 12 unmodified lines
1313 "oauth2",
1414 "custom",
1515 );
16+export const CredentialSecretProviderSchema = Schema.Literal(
17+ "local",
18+);
1619 export const CredentialScopeTypeSchema = Schema.Literal(
1720 "workspace",
1821 "organization",
@@ -44,6 +47,7 @@ export type ApprovalStatus = typeof ApprovalStatusSchema.Type; · 25 unmodified lines
4447 export type TaskRunStatus = typeof TaskRunStatusSchema.Type;
4548 export type CredentialMode = typeof CredentialModeSchema.Type;
4649 export type CredentialProvider = typeof CredentialProviderSchema.Type;
50+export type CredentialSecretProvider = typeof CredentialSecretProviderSchema.Type;
4751 export type CredentialScopeType = typeof CredentialScopeTypeSchema.Type;
4852 export type StorageScopeType = typeof StorageScopeTypeSchema.Type;
4953 export type StorageDurability = typeof StorageDurabilitySchema.Type;
v2/packages/schema/src/models/source-credential-binding.ts+6−1
@@ -1,7 +1,11 @@
11 import { Schema } from "effect";
22
33 import { TimestampMsSchema } from "../common";
4−import { CredentialProviderSchema, CredentialScopeTypeSchema } from "../enums";
4+import {
5+ CredentialProviderSchema,
6+ CredentialScopeTypeSchema,
7+ CredentialSecretProviderSchema,
8+} from "../enums";
59 import {
610 AccountIdSchema,
711 CredentialBindingIdSchema,
@@ -19,6 +23,7 @@ export const SourceCredentialBindingSchema = Schema.Struct({ · 11 unmodified lines
1923 scopeType: CredentialScopeTypeSchema,
2024 sourceKey: Schema.String,
2125 provider: CredentialProviderSchema,
26+ secretProvider: Schema.optional(CredentialSecretProviderSchema),
2227 secretRef: Schema.String,
2328 additionalHeadersJson: Schema.NullOr(Schema.String),
2429 boundAuthFingerprint: Schema.NullOr(Schema.String),
v2/packages/schema/src/models/workspace.ts+1−1
@@ -5,7 +5,7 @@ import { AccountIdSchema, OrganizationIdSchema, WorkspaceIdSchema } from "../ids · 4 unmodified lines
55
66 export const WorkspaceSchema = Schema.Struct({
77 id: WorkspaceIdSchema,
8− organizationId: Schema.NullOr(OrganizationIdSchema),
8+ organizationId: OrganizationIdSchema,
99 name: Schema.String,
1010 createdByAccountId: Schema.NullOr(AccountIdSchema),
1111 createdAt: TimestampMsSchema,
v2/packages/state-local-file/src/state-store.test.ts+1−1
@@ -60,7 +60,7 @@ describe("makeLocalStateStore", () => { · 59 unmodified lines
6060 workspaces: [
6161 {
6262 id: "ws_local",
63− organizationId: null,
63+ organizationId: "org_local",
6464 name: "Local Workspace",
6565 createdByAccountId: null,
6666 createdAt: now,

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