@orgsdk/executor 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # Persistent project executor
2
2
 
3
- The `@orgsdk/executor` npm package provides `orgsdk-executor`. Install it with `npm install -g @orgsdk/executor@0.1.0` for an independently managed runner. The `@orgsdk/cli` platform package already includes its local executor. Linux with Node 22.22.0+ and npm is required. Bun 1.4 remains an optional source-development runtime; installed JavaScript workers do not require Bun on PATH. Docker execution additionally requires Docker with `--mount volume-subpath` support, a built executor image, and network access to the OrgSDK application.
3
+ The `@orgsdk/executor` npm package provides `orgsdk-executor`. Install it with `npm install -g @orgsdk/executor` for an independently managed runner. The `@orgsdk/cli` platform package already includes its local executor. Linux with Node 22.22.0+ and npm is required. Bun 1.4 remains an optional source-development runtime; installed JavaScript workers do not require Bun on PATH. Docker execution additionally requires Docker with `--mount volume-subpath` support, a built executor image, and network access to the OrgSDK application.
4
4
 
5
5
  Create an executor identity for the chosen project in the application. Register using its token on stdin (or `EXECUTOR_TOKEN`), without placing the token in command history:
6
6
 
@@ -9,13 +9,13 @@ orgsdk-executor register --url http://localhost:8080 --data /path/to/private-run
9
9
  orgsdk-executor start --data /path/to/private-runner
10
10
  ```
11
11
 
12
- Registration saves the token in `registration.json` with mode 0600. Without `--data` or `EXECUTOR_DATA_DIR`, data lives at `$XDG_DATA_HOME/orgsdk/executor` (default `~/.local/share/orgsdk/executor`), independently of the package installation directory. Docker is the default mode. Configure `EXECUTOR_IMAGE`, `EXECUTION_NETWORK`, and `EXECUTOR_DATA_VOLUME`; set `--data` to the mounted volume root so it contains `agents/<agent-id>`. Docker jobs mount only their own agent subdirectory at `/agent`, use `/agent/workspace` as their working directory, and receive only their run capability through stdin. Other agents and registration files are not mounted. The managed installation runs `orgsdk-executor manage` (or `node dist/supervisor.js`) with `DJANGO_URL` and `LOCAL_EXECUTOR_BOOTSTRAP_TOKEN`. Each identity has one serial worker; revoked identities stop and remain stopped while the same revoked registration is advertised. Bootstrap omissions stop active workers; a later explicit re-enable or replacement identity starts a new worker. Transient startup failures retry with a bounded delay.
12
+ Registration saves the token in `registration.json` with mode 0600. Without `--data` or `EXECUTOR_DATA_DIR`, data lives at `$XDG_DATA_HOME/orgsdk/executor` (default `~/.local/share/orgsdk/executor`), independently of the package installation directory. Docker is the default mode. Configure `EXECUTOR_IMAGE`, `EXECUTION_NETWORK`, and `EXECUTOR_DATA_VOLUME`; set `--data` to the mounted volume root so it contains `agents/<agent-id>`. Docker jobs mount only their own agent subdirectory at `/agent`, use `/agent/workspace` as their working directory, and receive only their run capability through stdin. Other agents and registration files are not mounted. The managed installation runs `orgsdk-executor manage` (or `node dist/supervisor.js`) with `ORGSDK_SERVER_URL` and `LOCAL_EXECUTOR_BOOTSTRAP_TOKEN`. Each identity has one serial worker; revoked identities stop and remain stopped while the same revoked registration is advertised. Bootstrap omissions stop active workers; a later explicit re-enable or replacement identity starts a new worker. Transient startup failures retry with a bounded delay.
13
13
 
14
14
  Use `start --mode host` explicitly to run child jobs using the current OS account, its PATH and HOME. Host mode can use installed command-line tools and their account configuration; it is appropriate only for trusted plugins. It filters bootstrap, token, password, API key and credential environment variables from child jobs. Plugin code still receives only snapshot-authorized product credentials through the run capability. Host processes retain OS account filesystem access. Host validation/test workers receive only the allowlisted source, SDK metadata, test fixtures and output schema, run in a disposable directory, and have no product capability or project mount. Their OS account can still access host files; Docker provides the OS isolation boundary. Docker is the default isolation boundary.
15
15
 
16
16
  Project workspace files and installed plugin releases survive runs. No run cleanup deletes the agent folder. Plugins install under `agents/<id>/plugins/<slug>/<sha256>/plugin.mjs`; historical pinned versions remain available to retries. Current enabled configuration is fetched before each claim. External clients own reasoning and coordination. The runtime executes action, code, validation and test jobs only; built-in chat and reasoning delegation are retired. Existing `agents/<id>` storage paths and `--agent` install arguments identify retained project IDs.
17
17
 
18
- The separate [execution session module](src/sessions/README.md) supports successive cells in one live worker, stable session IDs, cursor-based events and retained history after close or expiry. It is an internal module and is not connected to the existing executor job loop or public APIs.
18
+ [Execution sessions](src/sessions/README.md) keep successive cells in one live worker, with stable session IDs, cursor-based events and retained history after close or expiry. The executor advertises session support during registration and handles authenticated session commands in its project job loop.
19
19
 
20
20
  ## External plugins
21
21
 
@@ -49,8 +49,8 @@ Docker mode also needs Docker
49
49
  Engine. Extract the installer from the tarball and run it as root:
50
50
 
51
51
  ```sh
52
- tar -xzf orgsdk-executor-0.1.0.tgz package/scripts/install-service.sh
53
- sudo bash package/scripts/install-service.sh "$PWD/orgsdk-executor-0.1.0.tgz" researcher docker
52
+ tar -xzf orgsdk-executor-0.2.0.tgz package/scripts/install-service.sh
53
+ sudo bash package/scripts/install-service.sh "$PWD/orgsdk-executor-0.2.0.tgz" researcher docker
54
54
  ```
55
55
 
56
56
  The installer creates `/opt/orgsdk-executor`, the `orgsdk-researcher` system
@@ -95,7 +95,7 @@ Browser's engine is a runner prerequisite. The optional `Dockerfile.chromium` in
95
95
 
96
96
  ```sh
97
97
  docker build -t orgsdk-job:chromium -f runtime/Dockerfile.chromium runtime
98
- make EXECUTOR_JOB_IMAGE=orgsdk-job:chromium executor
98
+ EXECUTOR_IMAGE=orgsdk-job:chromium orgsdk-executor start --mode docker
99
99
  ```
100
100
 
101
101
  Independently managed executors can select that image using `EXECUTOR_IMAGE`. Standard executors remain unchanged. Host-mode runners need matching Chromium at `PLAYWRIGHT_BROWSERS_PATH`.
@@ -109,4 +109,6 @@ bun --no-env-file runtime/scripts/verify-plugin-releases.ts \
109
109
 
110
110
  Use `--catalog /path/releases.json --bundle-root /path/bundles` before publication. Add `--render-pdf` when the matching engine is provisioned to exercise real PDF output. Every package is checksum-verified, installed in temporary `orgsdk-platform-test` project storage, and loaded to compare its exported tools to the catalog. Data Tools is exercised through the VM action interface. This does not prove provider OAuth setup or live external writes.
111
111
 
112
- The retained `DJANGO_URL` executor setting is the application base URL for protocol compatibility. Point it at the application server, for example `http://127.0.0.1:8080`. The server binary does not include or start the executor.
112
+ `ORGSDK_SERVER_URL` is the executor's application base URL. Point it at the application server, for example `http://127.0.0.1:8080`. The server binary does not include or start the executor. Separately managed executors must configure `ORGSDK_SERVER_URL` when upgrading; the platform CLI and managed development command supply it automatically.
113
+
114
+ Protocol 4 adds project-owned remote MCP discovery and execution over Streamable HTTP or legacy HTTP/SSE. Connections and reviewed tool schemas are supplied in immutable jobs; authentication headers are retrieved using run-scoped credentials. Each run owns and closes its connections. No stdio servers are launched. See the platform [remote MCP guide](../docs/remote-mcp.md).
package/dist/cli.js CHANGED
@@ -9,8 +9,14 @@ import { Client } from "./client.js";
9
9
  import { manage, registrationSchema, runAgent } from "./supervisor.js";
10
10
  import { installPlugin } from "./plugin-store.js";
11
11
  import { pluginSchema } from "./contract.js";
12
+ import { registerExecutor } from "./register-executor.js";
12
13
  import { packagePlugin } from "./package-plugin.js";
13
14
  var { command, option } = executorArguments(process.argv.slice(2));
15
+ var registerResponseSchema = z.object({
16
+ id: z.string(),
17
+ agent_id: z.string()
18
+ });
19
+ var modeSchema = z.enum(["docker", "host"]);
14
20
  var data = resolve(
15
21
  option("data") || process.env.EXECUTOR_DATA_DIR || join(
16
22
  process.env.XDG_DATA_HOME || join(homedir(), ".local", "share"),
@@ -25,19 +31,12 @@ if (command === "--help" || !command) {
25
31
  "orgsdk-executor register --url URL [--data DIR] (token: EXECUTOR_TOKEN or stdin)\norgsdk-executor start [--mode docker|host] [--data DIR]\norgsdk-executor install --agent ID --manifest FILE [--file bundled.mjs] [--data DIR]\norgsdk-executor package-plugin --directory CHECKOUT --output DIR [--embed-dependencies package,...] [--license FILE]\norgsdk-executor manage [--mode docker|host] (bootstrap manager)"
26
32
  );
27
33
  } else if (command === "--version") {
28
- console.log("0.1.0");
34
+ console.log("0.1.1");
29
35
  } else if (command === "register") {
30
- const base = z.string().url().parse(option("url") || process.env.DJANGO_URL);
36
+ const base = z.string().url().parse(option("url") || process.env.ORGSDK_SERVER_URL);
31
37
  const token = z.string().min(32).parse(process.env.EXECUTOR_TOKEN || (await readStdin()).trim());
32
- const registration = z.object({ id: z.string(), agent_id: z.string() }).parse(
33
- await new Client(base, token).request(
34
- "/internal/execution/v1/register/",
35
- "POST",
36
- {
37
- protocol_version: 3,
38
- capabilities: ["action", "code", "validate", "test"]
39
- }
40
- )
38
+ const registration = registerResponseSchema.parse(
39
+ await registerExecutor(new Client(base, token))
41
40
  );
42
41
  await mkdir(data, { recursive: true, mode: 448 });
43
42
  await writeFile(
@@ -57,10 +56,10 @@ if (command === "--help" || !command) {
57
56
  await runAgent(
58
57
  config.base,
59
58
  config,
60
- z.enum(["docker", "host"]).parse(option("mode") || "docker")
59
+ modeSchema.parse(option("mode") || "docker")
61
60
  );
62
61
  } else if (command === "manage")
63
- await manage(z.enum(["docker", "host"]).parse(option("mode") || "docker"));
62
+ await manage(modeSchema.parse(option("mode") || "docker"));
64
63
  else if (command === "package-plugin")
65
64
  await packagePlugin(
66
65
  z.string().parse(option("directory")),
package/dist/client.js CHANGED
@@ -1,6 +1,9 @@
1
1
  // src/client.ts
2
2
  import { z } from "zod";
3
3
  import { withRetry } from "./engine/retry.js";
4
+ function identifier(value) {
5
+ return z.string().regex(/^[a-zA-Z0-9_-]+$/).parse(value);
6
+ }
4
7
  var Client = class {
5
8
  constructor(base, token, signal) {
6
9
  this.base = base;
@@ -10,9 +13,74 @@ var Client = class {
10
13
  base;
11
14
  token;
12
15
  signal;
13
- async request(path, method = "GET", body) {
14
- if (!path.startsWith("/internal/execution/v1/"))
15
- throw new Error("Invalid capability path");
16
+ register(input) {
17
+ return this.#request("/internal/execution/v1/register/", "POST", input);
18
+ }
19
+ configuration() {
20
+ return this.#request("/internal/execution/v1/configuration/", "GET");
21
+ }
22
+ claim() {
23
+ return this.#request("/internal/execution/v1/claim/", "POST");
24
+ }
25
+ bootstrap() {
26
+ return this.#request("/internal/execution/v1/bootstrap/", "POST");
27
+ }
28
+ heartbeat(runId) {
29
+ return this.#request(
30
+ `/internal/execution/v1/runs/${identifier(runId)}/heartbeat/`,
31
+ "POST",
32
+ {}
33
+ );
34
+ }
35
+ publishEvent(runId, event) {
36
+ return this.#request(
37
+ `/internal/execution/v1/runs/${identifier(runId)}/events/`,
38
+ "POST",
39
+ event
40
+ );
41
+ }
42
+ complete(runId, result) {
43
+ return this.#request(
44
+ `/internal/execution/v1/runs/${identifier(runId)}/complete/`,
45
+ "POST",
46
+ result
47
+ );
48
+ }
49
+ createApproval(input) {
50
+ return this.#request(
51
+ "/internal/execution/v1/product/approvals/",
52
+ "POST",
53
+ input
54
+ );
55
+ }
56
+ approval(id) {
57
+ return this.#request(
58
+ `/internal/execution/v1/product/approvals/${identifier(id)}/`,
59
+ "GET"
60
+ );
61
+ }
62
+ saveArtifact(input) {
63
+ return this.#request(
64
+ "/internal/execution/v1/product/artifacts/",
65
+ "POST",
66
+ input
67
+ );
68
+ }
69
+ projectData(operation, params) {
70
+ return this.#request(
71
+ "/internal/execution/v1/product/project-data/",
72
+ "POST",
73
+ { ...params, operation }
74
+ );
75
+ }
76
+ async secret(id) {
77
+ const result = await this.#request(
78
+ `/internal/execution/v1/credentials/${identifier(id)}/`,
79
+ "GET"
80
+ );
81
+ return z.object({ secret: z.record(z.string(), z.unknown()) }).parse(result).secret;
82
+ }
83
+ async #request(path, method, body) {
16
84
  const response = await withRetry(
17
85
  async () => {
18
86
  const result = await fetch(`${this.base.replace(/\/$/, "")}${path}`, {
@@ -25,29 +93,23 @@ var Client = class {
25
93
  signal: this.signal ? AbortSignal.any([this.signal, AbortSignal.timeout(15e3)]) : AbortSignal.timeout(15e3),
26
94
  redirect: "error"
27
95
  });
28
- if (result.status >= 500) throw new Error(`API ${result.status}`);
96
+ if (result.status >= 500) {
97
+ throw new Error(`API ${result.status}`);
98
+ }
29
99
  return result;
30
100
  },
31
101
  { maxRetries: method === "GET" ? 2 : 0 }
32
102
  );
33
- if (!response.ok)
103
+ if (!response.ok) {
34
104
  throw new Error(
35
105
  `API ${response.status}: ${(await response.text()).slice(0, 500)}`
36
106
  );
37
- if (response.status === 204) return void 0;
107
+ }
108
+ if (response.status === 204) {
109
+ return void 0;
110
+ }
38
111
  return response.json();
39
112
  }
40
- product(path, method = "GET", body) {
41
- if (!/^[a-z][a-z0-9/-]*\/$/.test(path))
42
- throw new Error("Invalid product capability path");
43
- return this.request(`/internal/execution/v1/product/${path}`, method, body);
44
- }
45
- async secret(id) {
46
- const result = await this.request(
47
- `/internal/execution/v1/credentials/${id}/`
48
- );
49
- return z.object({ secret: z.record(z.string(), z.unknown()) }).parse(result).secret;
50
- }
51
113
  };
52
114
  export {
53
115
  Client
package/dist/contract.js CHANGED
@@ -1,7 +1,13 @@
1
1
  // src/contract.ts
2
2
  import { z } from "zod";
3
+ import {
4
+ sessionCommandSchema,
5
+ sessionScopeSchema
6
+ } from "./session-job-contract.js";
7
+ import { connectionSchema } from "./mcp/contract.js";
3
8
  var pluginSchema = z.object({
4
- distribution: z.enum(["inline", "external"]).optional(),
9
+ distribution: z.enum(["inline", "external", "mcp"]).optional(),
10
+ mcp: connectionSchema.optional(),
5
11
  package_url: z.string().optional(),
6
12
  configuration: z.record(z.string(), z.unknown()).optional(),
7
13
  credential_provider: z.string().nullable().optional(),
@@ -28,16 +34,32 @@ var agentSchema = z.object({
28
34
  }).optional()
29
35
  });
30
36
  var jobSchema = z.object({
31
- protocol_version: z.union([z.literal(1), z.literal(2), z.literal(3)]),
37
+ protocol_version: z.union([
38
+ z.literal(1),
39
+ z.literal(2),
40
+ z.literal(3),
41
+ z.literal(4)
42
+ ]),
32
43
  run_id: z.string().uuid(),
33
44
  workspace_id: z.number(),
34
45
  actor_id: z.number(),
35
- operation: z.enum(["action", "chat", "code", "validate", "test"]),
46
+ operation: z.enum([
47
+ "action",
48
+ "chat",
49
+ "code",
50
+ "validate",
51
+ "test",
52
+ "mcp_discover",
53
+ "session"
54
+ ]),
36
55
  capability: z.string(),
37
56
  inputs: z.record(z.string(), z.unknown()),
38
57
  deadline: z.string(),
39
58
  lease_seconds: z.number(),
40
59
  snapshot: z.object({
60
+ mcp_discovery: connectionSchema.optional(),
61
+ session: sessionCommandSchema.optional(),
62
+ session_scope: sessionScopeSchema.optional(),
41
63
  agents: z.array(agentSchema),
42
64
  root_agent_id: z.string(),
43
65
  validation_mode: z.enum(["legacy", "semantic"]).optional(),
@@ -56,11 +78,22 @@ var jobSchema = z.object({
56
78
  sdk_revision: z.number().int().optional(),
57
79
  configuration_revision: z.string().optional()
58
80
  })
59
- }).refine((job) => job.operation !== "code" || job.protocol_version === 2, {
60
- message: "Code execution requires protocol version 2"
61
81
  }).refine(
62
- (job) => !["validate", "test"].includes(job.operation) && job.snapshot.validation_mode !== "semantic" || job.protocol_version === 3,
82
+ (job) => job.protocol_version === 4 || job.operation !== "mcp_discover" && !job.snapshot.mcp_discovery && !job.snapshot.agents.some(
83
+ (agent) => agent.plugins.some((plugin) => plugin.distribution === "mcp")
84
+ ),
85
+ { message: "MCP connections require protocol version 4" }
86
+ ).refine(
87
+ (job) => job.operation !== "code" || [2, 4].includes(job.protocol_version),
88
+ {
89
+ message: "Code execution requires protocol version 2"
90
+ }
91
+ ).refine(
92
+ (job) => !["validate", "test"].includes(job.operation) && job.snapshot.validation_mode !== "semantic" || [3, 4].includes(job.protocol_version),
63
93
  { message: "Semantic validation and tests require protocol version 3" }
94
+ ).refine(
95
+ (job) => job.operation !== "session" || job.protocol_version === 4 && job.snapshot.session !== void 0 && job.snapshot.session_scope?.projectId === job.snapshot.root_agent_id && job.snapshot.session_scope.workspaceId === String(job.workspace_id) && (job.snapshot.session.operation !== "execute" || typeof job.snapshot.source === "string"),
96
+ { message: "Invalid execution session job" }
64
97
  );
65
98
  export {
66
99
  agentSchema,
@@ -33,7 +33,7 @@ function jobEnvironment(base, agentPath, host) {
33
33
  ...inherited,
34
34
  PATH: process.env.PATH || "",
35
35
  HOME: host ? process.env.HOME || agentPath : agentPath,
36
- DJANGO_URL: base,
36
+ ORGSDK_SERVER_URL: base,
37
37
  EXECUTOR_AGENT_DIR: agentPath
38
38
  };
39
39
  }
@@ -56,7 +56,6 @@ async function boundedText(stream, kill) {
56
56
  }
57
57
  async function runIsolatedJob(job, base, sourceArguments, signal, mode = "docker") {
58
58
  const control = new Client(base, job.capability);
59
- const path = `/internal/execution/v1/runs/${job.run_id}/`;
60
59
  let timer;
61
60
  let deadline;
62
61
  let cancelled = false;
@@ -123,7 +122,7 @@ async function runIsolatedJob(job, base, sourceArguments, signal, mode = "docker
123
122
  timer = setInterval(() => {
124
123
  void (async () => {
125
124
  try {
126
- const state = z.object({ cancel_requested: z.boolean(), status: z.string() }).parse(await control.request(`${path}heartbeat/`, "POST"));
125
+ const state = z.object({ cancel_requested: z.boolean(), status: z.string() }).parse(await control.heartbeat(job.run_id));
127
126
  if (state.cancel_requested || ["failed", "interrupted", "cancelled"].includes(state.status))
128
127
  kill();
129
128
  } catch {
@@ -155,7 +154,7 @@ async function runIsolatedJob(job, base, sourceArguments, signal, mode = "docker
155
154
  } : void 0
156
155
  }
157
156
  };
158
- await control.request(`${path}events/`, "POST", {
157
+ await control.publishEvent(job.run_id, {
159
158
  sequence: 1,
160
159
  kind: job.operation === "validate" ? "validation.result" : "test.result",
161
160
  data: {
@@ -164,13 +163,13 @@ async function runIsolatedJob(job, base, sourceArguments, signal, mode = "docker
164
163
  diagnostics: Array.isArray(result.diagnostics) ? result.diagnostics.slice(0, 10) : []
165
164
  }
166
165
  });
167
- await control.request(`${path}complete/`, "POST", {
166
+ await control.complete(job.run_id, {
168
167
  status: passed ? "succeeded" : "failed",
169
168
  output,
170
169
  ...passed ? {} : { error: "Validation or tests failed" }
171
170
  });
172
171
  } catch (error) {
173
- await control.request(`${path}complete/`, "POST", {
172
+ await control.complete(job.run_id, {
174
173
  status: cancelled ? "cancelled" : "failed",
175
174
  error: error instanceof Error ? error.message.slice(0, 2e3) : "Isolated execution failed"
176
175
  }).catch(() => void 0);
@@ -25,14 +25,19 @@ var isolatedInputSchema = z.object({
25
25
  sdk: z.object({
26
26
  plugins: z.array(
27
27
  z.object({
28
+ kind: z.string().optional(),
28
29
  namespace: z.string().nullable(),
29
30
  available: z.boolean(),
30
31
  metadata_complete: z.boolean().optional(),
31
32
  tools: z.array(
32
33
  z.object({
34
+ inputSchema: z.record(z.string(), z.json()).optional(),
35
+ outputSchema: z.record(z.string(), z.json()).nullable().optional(),
33
36
  name: z.string(),
34
37
  parameters: z.array(
35
38
  z.object({
39
+ inputSchema: z.record(z.string(), z.json()).optional(),
40
+ outputSchema: z.record(z.string(), z.json()).nullable().optional(),
36
41
  name: z.string(),
37
42
  type: z.string(),
38
43
  optional: z.boolean().optional()
@@ -0,0 +1,29 @@
1
+ // src/mcp/aliases.ts
2
+ import { createHash } from "node:crypto";
3
+ import { RESERVED_FUNCTION_KEYS } from "../engine/plugins/namespace.js";
4
+ function approveTools(tools, previous) {
5
+ const existing = new Map(previous.map((tool) => [tool.name, tool.alias]));
6
+ const claimed = new Set(previous.map((tool) => tool.alias));
7
+ return [...tools].sort((left, right) => {
8
+ if (left.name === right.name) return 0;
9
+ return left.name < right.name ? -1 : 1;
10
+ }).map((tool) => {
11
+ const old = existing.get(tool.name);
12
+ if (old) return { ...tool, alias: old };
13
+ const words = tool.name.replace(/[^a-zA-Z0-9]+/g, " ").trim().split(/\s+/);
14
+ let alias = words.map(
15
+ (word, index) => index ? word.charAt(0).toUpperCase() + word.slice(1) : word.charAt(0).toLowerCase() + word.slice(1)
16
+ ).join("").slice(0, 60);
17
+ if (!/^[a-z]/.test(alias)) alias = `tool${alias}`;
18
+ if (RESERVED_FUNCTION_KEYS.has(alias) || claimed.has(alias)) {
19
+ alias += createHash("sha256").update(tool.name).digest("hex").slice(0, 16);
20
+ }
21
+ if (claimed.has(alias))
22
+ throw new Error("Tool alias collision; rename the remote tool");
23
+ claimed.add(alias);
24
+ return { ...tool, alias };
25
+ });
26
+ }
27
+ export {
28
+ approveTools
29
+ };
@@ -0,0 +1,239 @@
1
+ // src/mcp/client.ts
2
+ import { httpTransport } from "./transport.js";
3
+ import {
4
+ Client,
5
+ discoverOAuthProtectedResourceMetadata
6
+ } from "@modelcontextprotocol/client";
7
+ import Ajv from "ajv/dist/2020.js";
8
+ import AjvDraft7 from "ajv";
9
+ import Ajv2019 from "ajv/dist/2019.js";
10
+ import { z } from "zod";
11
+ import {
12
+ connectionSchema,
13
+ discoverySchema,
14
+ remoteToolSchema
15
+ } from "./contract.js";
16
+ import { endpointFetch, redactMcp } from "./network.js";
17
+ var argumentsSchema = z.record(z.string(), z.unknown());
18
+ var McpRuntime = class {
19
+ constructor(connection, credentials, signal, transportFactory = httpTransport) {
20
+ this.credentials = credentials;
21
+ this.transportFactory = transportFactory;
22
+ this.connection = connectionSchema.parse(connection);
23
+ this.signal = AbortSignal.any([signal, this.controller.signal]);
24
+ this.signal.addEventListener("abort", this.onAbort, { once: true });
25
+ }
26
+ credentials;
27
+ transportFactory;
28
+ client;
29
+ opening;
30
+ closing;
31
+ onAbort = () => {
32
+ void this.close();
33
+ };
34
+ headers = {};
35
+ secrets = /* @__PURE__ */ new Set();
36
+ lastStatus = 0;
37
+ challenge;
38
+ selected = "streamable-http";
39
+ controller = new AbortController();
40
+ validators = /* @__PURE__ */ new Map();
41
+ signal;
42
+ connection;
43
+ async open() {
44
+ this.signal.throwIfAborted();
45
+ this.headers = await this.credentials();
46
+ for (const value of Object.values(this.headers)) this.secrets.add(value);
47
+ this.signal.throwIfAborted();
48
+ const fetcher = async (input, init) => {
49
+ this.headers = await this.credentials();
50
+ for (const value of Object.values(this.headers)) this.secrets.add(value);
51
+ const response = await endpointFetch(
52
+ this.connection.endpoint,
53
+ this.signal,
54
+ this.headers
55
+ )(input, init);
56
+ this.lastStatus = response.status;
57
+ if ([401, 403].includes(response.status))
58
+ this.challenge = response.headers.get("www-authenticate") ?? void 0;
59
+ return response;
60
+ };
61
+ const connect = async (transport) => {
62
+ this.selected = transport;
63
+ this.lastStatus = 0;
64
+ this.client = new Client(
65
+ { name: "orgsdk-executor", version: "0.1.1" },
66
+ {
67
+ versionNegotiation: { mode: transport === "sse" ? "legacy" : "auto" }
68
+ }
69
+ );
70
+ await this.client.connect(
71
+ this.transportFactory(this.connection.endpoint, transport, fetcher),
72
+ { timeout: 15e3, signal: this.signal }
73
+ );
74
+ };
75
+ try {
76
+ await connect(
77
+ this.connection.transport === "sse" ? "sse" : "streamable-http"
78
+ );
79
+ } catch (error) {
80
+ const fallback = this.connection.transport === "auto" && [404, 405].includes(this.lastStatus);
81
+ await this.client?.close();
82
+ if (!fallback) throw error;
83
+ await connect("sse");
84
+ }
85
+ }
86
+ async ready() {
87
+ this.opening ??= this.open();
88
+ await this.opening;
89
+ this.signal.throwIfAborted();
90
+ if (!this.client) throw new Error("MCP connection unavailable");
91
+ return this.client;
92
+ }
93
+ async connect() {
94
+ await this.ready();
95
+ }
96
+ async discover() {
97
+ const timer = setTimeout(
98
+ () => this.controller.abort(new Error("MCP discovery timed out")),
99
+ 6e4
100
+ );
101
+ try {
102
+ const client = await this.ready();
103
+ const tools = [];
104
+ const cursors = /* @__PURE__ */ new Set();
105
+ const names = /* @__PURE__ */ new Set();
106
+ let cursor;
107
+ do {
108
+ const page = await client.request(
109
+ {
110
+ method: "tools/list",
111
+ params: cursor !== void 0 ? { cursor } : {}
112
+ },
113
+ { signal: this.signal, timeout: 15e3 }
114
+ );
115
+ for (const value of page.tools) {
116
+ const tool = remoteToolSchema.parse(value);
117
+ if (names.has(tool.name))
118
+ throw new Error("MCP server returned duplicate tool names");
119
+ names.add(tool.name);
120
+ tools.push(tool);
121
+ }
122
+ if (tools.length > 1e3 || JSON.stringify(tools).length > 5e5)
123
+ throw new Error("MCP tool catalogue exceeds the supported size");
124
+ cursor = page.nextCursor;
125
+ if (cursor !== void 0 && cursors.has(cursor))
126
+ throw new Error("MCP server repeated a discovery cursor");
127
+ if (cursor !== void 0) cursors.add(cursor);
128
+ if (cursors.size >= 100)
129
+ throw new Error("MCP discovery exceeded 100 pages");
130
+ } while (cursor !== void 0);
131
+ return discoverySchema.parse(
132
+ redactMcp({ tools, transport: this.selected }, this.redactionHeaders())
133
+ );
134
+ } catch (error) {
135
+ if (![401, 403].includes(this.lastStatus)) throw this.safeError(error);
136
+ const metadataUrl = /resource_metadata="([^"]+)"/.exec(
137
+ this.challenge ?? ""
138
+ )?.[1];
139
+ const resourceMetadata = await discoverOAuthProtectedResourceMetadata(
140
+ this.connection.endpoint,
141
+ {
142
+ ...metadataUrl ? { resourceMetadataUrl: new URL(metadataUrl) } : {}
143
+ },
144
+ endpointFetch(
145
+ this.connection.endpoint,
146
+ AbortSignal.any([this.signal, AbortSignal.timeout(15e3)])
147
+ )
148
+ ).catch(() => void 0);
149
+ return discoverySchema.parse(
150
+ redactMcp(
151
+ {
152
+ tools: [],
153
+ transport: this.selected,
154
+ authRequired: true,
155
+ resourceMetadata
156
+ },
157
+ this.redactionHeaders()
158
+ )
159
+ );
160
+ } finally {
161
+ clearTimeout(timer);
162
+ }
163
+ }
164
+ inputValidator(tool) {
165
+ const cached = this.validators.get(tool.alias);
166
+ if (cached) {
167
+ return cached;
168
+ }
169
+ const dialect = String(tool.inputSchema.$schema);
170
+ const validatorClass = dialect.includes("draft-07") ? AjvDraft7 : dialect.includes("2019-09") ? Ajv2019 : Ajv;
171
+ const validate = new validatorClass({
172
+ strict: false,
173
+ validateFormats: false,
174
+ allErrors: false
175
+ }).compile(tool.inputSchema);
176
+ this.validators.set(tool.alias, validate);
177
+ return validate;
178
+ }
179
+ async call(alias, args) {
180
+ const tool = this.connection.tools.find(
181
+ (candidate) => candidate.alias === alias
182
+ );
183
+ if (!tool) throw new Error("Tool is outside the approved MCP catalogue");
184
+ try {
185
+ if (!this.inputValidator(tool)(args))
186
+ throw new Error("Arguments do not match the MCP tool input schema");
187
+ const client = await this.ready();
188
+ const result = await client.callTool(
189
+ {
190
+ name: tool.name,
191
+ arguments: argumentsSchema.parse(args)
192
+ },
193
+ {
194
+ signal: this.signal,
195
+ timeout: 6e4,
196
+ toolDefinition: {
197
+ ...tool,
198
+ inputSchema: { ...tool.inputSchema, type: "object" }
199
+ }
200
+ }
201
+ );
202
+ const clean = redactMcp(result, this.redactionHeaders());
203
+ if (JSON.stringify(clean).length > 1e6)
204
+ throw new Error("MCP result exceeds the supported size");
205
+ if (result.isError)
206
+ throw new Error(
207
+ `Remote MCP tool failed: ${JSON.stringify(clean).slice(0, 1500)}`
208
+ );
209
+ return clean;
210
+ } catch (error) {
211
+ throw this.safeError(error);
212
+ }
213
+ }
214
+ redactionHeaders() {
215
+ return Object.fromEntries(
216
+ [...this.secrets].map((secret, index) => [String(index), secret])
217
+ );
218
+ }
219
+ safeError(error) {
220
+ return new Error(
221
+ String(
222
+ redactMcp(
223
+ error instanceof Error ? error.message : "MCP request failed",
224
+ this.redactionHeaders()
225
+ )
226
+ ).slice(0, 2e3)
227
+ );
228
+ }
229
+ async close() {
230
+ if (this.closing) return this.closing;
231
+ this.signal.removeEventListener("abort", this.onAbort);
232
+ this.controller.abort();
233
+ this.closing = this.client?.close().catch(() => void 0) ?? Promise.resolve();
234
+ return this.closing;
235
+ }
236
+ };
237
+ export {
238
+ McpRuntime
239
+ };