@qlairoslabs/acp-client 0.13.1-alpha.1 → 0.13.2-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/CONSUMER_GUIDE.md +60 -26
  2. package/package.json +5 -1
  3. package/src/agent/config.ts +2 -0
  4. package/src/agent/native-operations.ts +1 -0
  5. package/src/agent-session.ts +11 -2
  6. package/src/agent.ts +4 -1
  7. package/src/index.ts +2 -0
  8. package/src/native/capabilities.ts +2 -2
  9. package/src/native/connection.ts +1 -1
  10. package/src/native/controller.ts +2 -1
  11. package/src/native/host-config.ts +2 -0
  12. package/src/native/host.ts +10 -0
  13. package/src/native/mcp.ts +47 -0
  14. package/src/native/recovery.ts +8 -7
  15. package/src/native/reminders/routine-guard.ts +4 -3
  16. package/src/native/reminders/routine-wire.ts +1 -1
  17. package/src/native-harness/README.md +58 -1
  18. package/src/native-harness/package.json +4 -0
  19. package/src/native-harness/src/capabilities/attachments/admission.ts +42 -0
  20. package/src/native-harness/src/capabilities/attachments/image-validation.ts +98 -0
  21. package/src/native-harness/src/capabilities/attachments/input.ts +1 -0
  22. package/src/native-harness/src/capabilities/attachments/read.ts +76 -0
  23. package/src/native-harness/src/capabilities/attachments/recovery.ts +26 -0
  24. package/src/native-harness/src/capabilities/attachments/selection.ts +37 -0
  25. package/src/native-harness/src/capabilities/attachments/service.ts +75 -0
  26. package/src/native-harness/src/capabilities/attachments/upload.ts +164 -0
  27. package/src/native-harness/src/capabilities/attachments/vision.ts +45 -0
  28. package/src/native-harness/src/capabilities/context/build.ts +5 -0
  29. package/src/native-harness/src/capabilities/model/openrouter-stream.ts +80 -17
  30. package/src/native-harness/src/capabilities/model/runner.ts +6 -3
  31. package/src/native-harness/src/capabilities/tools/mcp/client.ts +97 -0
  32. package/src/native-harness/src/capabilities/tools/mcp/http.ts +183 -0
  33. package/src/native-harness/src/capabilities/tools/mcp/registry.ts +62 -0
  34. package/src/native-harness/src/capabilities/tools/mcp/result.ts +33 -0
  35. package/src/native-harness/src/capabilities/tools/mcp/schema.ts +77 -0
  36. package/src/native-harness/src/capabilities/tools/mcp/secrets.ts +28 -0
  37. package/src/native-harness/src/capabilities/tools/mcp/stdio.ts +105 -0
  38. package/src/native-harness/src/capabilities/tools/runtime/invocations.ts +4 -1
  39. package/src/native-harness/src/capabilities/tools/web/config.ts +1 -0
  40. package/src/native-harness/src/capabilities/tools/web/definitions.ts +18 -0
  41. package/src/native-harness/src/capabilities/tools/web/direct-address.ts +56 -0
  42. package/src/native-harness/src/capabilities/tools/web/direct-transport.ts +235 -0
  43. package/src/native-harness/src/capabilities/tools/web/direct.ts +149 -0
  44. package/src/native-harness/src/capabilities/tools/web/exa-transport.ts +41 -0
  45. package/src/native-harness/src/capabilities/tools/web/exa.ts +71 -0
  46. package/src/native-harness/src/capabilities/tools/web/preview.ts +44 -0
  47. package/src/native-harness/src/capabilities/tools/web/registry.ts +47 -0
  48. package/src/native-harness/src/capabilities/tools/web/usage.ts +1 -0
  49. package/src/native-harness/src/contracts/agent.ts +3 -1
  50. package/src/native-harness/src/contracts/attachments.ts +62 -0
  51. package/src/native-harness/src/contracts/config-permissions.ts +13 -4
  52. package/src/native-harness/src/contracts/context.ts +1 -1
  53. package/src/native-harness/src/contracts/events.ts +2 -2
  54. package/src/native-harness/src/contracts/loop.ts +3 -3
  55. package/src/native-harness/src/contracts/mcp.ts +22 -0
  56. package/src/native-harness/src/contracts/model-execution.ts +2 -1
  57. package/src/native-harness/src/contracts/operator-controls.ts +8 -1
  58. package/src/native-harness/src/contracts/protocol.ts +20 -4
  59. package/src/native-harness/src/contracts/session-file.ts +2 -1
  60. package/src/native-harness/src/contracts/session.ts +6 -1
  61. package/src/native-harness/src/contracts/storage.ts +23 -5
  62. package/src/native-harness/src/contracts/tools.ts +2 -0
  63. package/src/native-harness/src/contracts/web.ts +16 -0
  64. package/src/native-harness/src/governance/permissions/gate.ts +9 -2
  65. package/src/native-harness/src/governance/policy/resolve.ts +6 -1
  66. package/src/native-harness/src/index.ts +43 -11
  67. package/src/native-harness/src/interfaces/cli/development.ts +108 -53
  68. package/src/native-harness/src/interfaces/cli/serve.ts +2 -2
  69. package/src/native-harness/src/interfaces/cli/start.ts +22 -13
  70. package/src/native-harness/src/interfaces/client.ts +8 -2
  71. package/src/native-harness/src/interfaces/inspector/index.html +7 -1
  72. package/src/native-harness/src/interfaces/inspector/state.ts +6 -2
  73. package/src/native-harness/src/interfaces/protocol/load.ts +3 -1
  74. package/src/native-harness/src/interfaces/protocol/local.ts +13 -4
  75. package/src/native-harness/src/interfaces/protocol/operator.ts +8 -2
  76. package/src/native-harness/src/interfaces/protocol/server.ts +93 -29
  77. package/src/native-harness/src/interfaces/protocol/stdio-client.ts +1 -0
  78. package/src/native-harness/src/interfaces/web-chat/index.html +65 -12
  79. package/src/native-harness/src/interfaces/web-chat/server.ts +30 -3
  80. package/src/native-harness/src/kernel/channels.ts +19 -11
  81. package/src/native-harness/src/kernel/loop.ts +1 -1
  82. package/src/native-harness/src/runtime/config/inference-key.ts +7 -0
  83. package/src/native-harness/src/runtime/config/managed.ts +1 -1
  84. package/src/native-harness/src/runtime/config/paths.ts +3 -2
  85. package/src/native-harness/src/runtime/execution/mcp-stdio.ts +31 -0
  86. package/src/native-harness/src/state/storage/archive.ts +95 -12
  87. package/src/native-harness/src/state/storage/attachment-files.ts +58 -0
  88. package/src/native-harness/src/state/storage/attachment-import.ts +106 -0
  89. package/src/native-harness/src/state/storage/attachment-tables.ts +123 -0
  90. package/src/native-harness/src/state/storage/engine.ts +194 -34
  91. package/src/native-harness/src/state/storage/inference.ts +30 -2
  92. package/src/native-harness/src/state/storage/memory-attachments.ts +56 -0
  93. package/src/native-harness/src/state/storage/memory.ts +18 -3
  94. package/src/native-harness/src/state/storage/reminder-archive.ts +2 -2
  95. package/src/native-harness/src/state/storage/session-file.ts +22 -9
  96. package/src/native-harness/src/state/storage/sqlite.ts +51 -10
  97. package/src/native-harness/src/state/storage/web-tables.ts +47 -0
  98. package/src/native-harness/src/testing.ts +150 -55
  99. package/src/native-harness/src/util/attachment-input.ts +42 -0
  100. package/src/native-harness/src/util/config.ts +59 -12
  101. package/src/native-harness/src/util/mcp-config.ts +102 -0
  102. package/src/native-harness/src/util/web-config.ts +34 -0
  103. package/src/native-harness/src/util/web-usage.ts +33 -0
  104. package/src/steering/combine.ts +1 -0
  105. package/src/steering/contracts.ts +3 -0
@@ -1,26 +1,89 @@
1
1
  import type { ModelAttempt, ModelAttemptEvent } from "../../contracts/model-execution.ts";
2
2
  import type { Message } from "../../contracts/loop.ts";
3
+ import { projectVisionParts, VisionInputError } from "../attachments/vision.ts";
4
+ import { ATTACHMENT_LIMITS } from "../../contracts/attachments.ts";
5
+ import { createHash } from "node:crypto";
3
6
 
4
- function wireMessage(message: Message): unknown {
5
- if (message.role === "assistant") return message.providerState ?? { role: "assistant", content: message.content,
7
+ function wireMessage(message: Message, preserveProviderState: boolean): unknown {
8
+ if (message.role === "assistant") return (preserveProviderState ? message.providerState : undefined) ?? { role: "assistant", content: message.content,
6
9
  ...(message.calls.length ? { tool_calls: message.calls.map(c => ({ id: c.id, type: "function", function: { name: c.name, arguments: c.arguments } })) } : {}) };
7
10
  return message.role === "tool" ? { role: "tool", content: message.content, tool_call_id: message.callId } : message;
8
11
  }
9
12
  /** OpenRouter SSE translation stays at the provider boundary; tool fragments are
10
13
  * private until a valid terminal response is assembled by the adapter. */
11
- export function openRouterAttempt(apiKey: string, model: string, fetcher: typeof fetch = fetch, onRequest?: (body: string) => void): ModelAttempt {
14
+ type Vision = Parameters<typeof projectVisionParts>[1] & { verify?: (metadata: import("../../contracts/attachments.ts").AttachmentMetadata, signal: AbortSignal) => Promise<void> };
15
+ export function openRouterAttempt(apiKey: string, model: string, fetcher: typeof fetch = fetch, onRequest?: (body: string) => void, vision?: Vision): ModelAttempt {
16
+ return chatAttempt(apiKey, model, fetcher, onRequest, undefined, vision);
17
+ }
18
+ export function openAICompatibleAttempt(baseUrl: string, model: string, apiKey?: string, fetcher: typeof fetch = fetch, onRequest?: (body: string) => void, metadata?: Vision["metadata"]): ModelAttempt {
19
+ const references: Vision | undefined = metadata ? { supported: false, metadata, read: () => { throw new Error("Image bytes unavailable for text-only model"); } } : undefined;
20
+ return chatAttempt(apiKey, model, fetcher, onRequest, `${baseUrl}/chat/completions`, references);
21
+ }
22
+ function chatAttempt(apiKey: string | undefined, model: string, fetcher: typeof fetch, onRequest?: (body: string) => void, endpoint?: string, vision?: Vision): ModelAttempt {
12
23
  return async function* (request, signal) {
13
- const body = JSON.stringify({ model, stream: true, stream_options: { include_usage: true }, messages: request.messages.map(wireMessage),
14
- ...(request.tools.length ? { tools: request.tools.map(tool => ({ type: "function", function: tool })) } : {}) });
15
- onRequest?.(body);
24
+ const imageUrls: string[] = [];
25
+ let messages: unknown[];
26
+ try {
27
+ let imageBytes = 0;
28
+ const unavailable = new Set<string>();
29
+ const images = new Map<string, ReturnType<NonNullable<typeof vision>["metadata"]>>();
30
+ for (const message of request.messages) if (message.role === "user" && message.parts) {
31
+ if (!vision) throw new VisionInputError("unsupported_image", "No attachment resolver is configured");
32
+ for (const part of message.parts) if (part.type === "attachment") {
33
+ const metadata = vision.metadata(part.id);
34
+ if (!metadata) unavailable.add(part.id);
35
+ else if (metadata.mediaType.startsWith("image/")) { imageBytes += metadata.bytes; images.set(part.id, metadata); }
36
+ }
37
+ }
38
+ if (unavailable.size) throw new VisionInputError("attachment_unavailable", "Attachment metadata is unavailable", [...unavailable]);
39
+ if (endpoint && images.size) throw new VisionInputError("unsupported_image", "The configured model does not support image input", [...images.keys()]);
40
+ if (imageBytes > ATTACHMENT_LIMITS.imageBytesPerTurn) throw new VisionInputError("transfer_limit", "Image request exceeds the turn budget");
41
+ if (images.size && !vision!.supported) throw new VisionInputError("unsupported_image", "The configured model does not support image input", [...images.keys()]);
42
+ const bytes = new Map<string, Uint8Array>();
43
+ for (const [id, metadata] of images) try {
44
+ await vision!.verify?.(metadata!, signal);
45
+ const value = vision!.read(metadata!);
46
+ if (value.length !== metadata!.bytes || createHash("sha256").update(value).digest("hex") !== metadata!.sha256) throw new Error("Integrity failure");
47
+ bytes.set(id, value);
48
+ } catch { unavailable.add(id); }
49
+ if (unavailable.size) throw new VisionInputError("attachment_unavailable", "Image bytes are unavailable", [...unavailable]);
50
+ messages = request.messages.map(message => {
51
+ if (message.role !== "user" || !message.parts) return wireMessage(message, endpoint === undefined);
52
+ if (!vision) throw new VisionInputError("unsupported_image", "No attachment resolver is configured");
53
+ const content = projectVisionParts(message.parts, { ...vision, read: metadata => bytes.get(metadata.id)! });
54
+ for (const part of content) if (part.type === "image_url") imageUrls.push(part.image_url.url);
55
+ const separator = message.content.indexOf("\n\n");
56
+ const attribution = message.content.startsWith("Participant: ") && separator >= 0 ? message.content.slice(0, separator + 2) : "";
57
+ if (endpoint) return { role: "user", content: attribution + content.map(part => part.type === "text" ? part.text : "").join("") };
58
+ return { role: "user", content: attribution ? [{ type: "text", text: attribution }, ...content] : content };
59
+ });
60
+ } catch (error) {
61
+ if (error instanceof VisionInputError) { yield { type: "failure", kind: "invalid_request", code: error.code, attachmentIds: error.attachmentIds, message: error.message }; return; }
62
+ throw error;
63
+ }
64
+ const body = JSON.stringify({ model, stream: true, stream_options: { include_usage: true }, messages,
65
+ ...(request.tools.length ? { tools: request.tools.map(tool => ({ type: "function", function: tool })), ...(endpoint ? { tool_choice: "auto" } : {}) } : {}) });
66
+ const redact = (text: string) => {
67
+ let safe = apiKey ? text.replaceAll(apiKey, "[REDACTED]") : text;
68
+ for (const url of imageUrls) { safe = safe.replaceAll(url, "[REDACTED_IMAGE]"); const encoded = url.slice(url.indexOf(",") + 1); if (encoded) safe = safe.replaceAll(encoded, "[REDACTED_IMAGE]"); }
69
+ return safe;
70
+ };
71
+ const errorText = (error: unknown) => endpoint ? "Chat Completions transport failed" : redact(String(error));
72
+ onRequest?.(imageUrls.length ? redact(body) : body);
16
73
  let response: Response;
17
- try { response = await fetcher("https://openrouter.ai/api/v1/chat/completions", { method: "POST", headers: { Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json" }, body, signal }); }
18
- catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: String(error).replaceAll(apiKey, "[REDACTED]") }; return; }
74
+ try { response = await fetcher(endpoint ?? "https://openrouter.ai/api/v1/chat/completions", { method: "POST", headers: { ...(apiKey === undefined ? {} : { Authorization: `Bearer ${apiKey}` }), "Content-Type": "application/json" }, body, signal, ...(endpoint ? { redirect: "manual" } : {}) }); }
75
+ catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(error) }; return; }
19
76
  if (!response.ok) {
20
- const text = (await response.text()).replaceAll(apiKey, "[REDACTED]");
77
+ if (endpoint) {
78
+ void response.body?.cancel().catch(() => {});
79
+ if (response.status >= 300 && response.status < 400) { yield { type: "failure", kind: "provider", message: "redirect_refused" }; return; }
80
+ yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `Chat Completions HTTP ${response.status}` }; return;
81
+ }
82
+ const text = redact(await response.text());
21
83
  yield { type: "failure", kind: response.status === 429 || response.status >= 500 ? "transient" : "invalid_request", message: `OpenRouter HTTP ${response.status}: ${text}` }; return;
22
84
  }
23
- const requestId = response.headers.get("x-request-id") ?? undefined;
85
+ const safeRequestId = (id: string | undefined) => endpoint && apiKey && id?.includes(apiKey) ? undefined : id;
86
+ const requestId = safeRequestId(response.headers.get("x-request-id") ?? undefined);
24
87
  if (!response.body) return;
25
88
  let content = "", buffer = "", stop: string | undefined, providerId = requestId, reasoning = "";
26
89
  const reasoningDetails: unknown[] = [];
@@ -35,8 +98,8 @@ export function openRouterAttempt(apiKey: string, model: string, fetcher: typeof
35
98
  if (!line.startsWith("data:")) continue;
36
99
  const data = line.slice(5).trim(); if (!data || data === "[DONE]") continue;
37
100
  let payload: { id?: string; usage?: { prompt_tokens?: number; completion_tokens?: number; total_tokens?: number }; choices?: { finish_reason?: string | null; delta?: { content?: string | null; reasoning?: string | null; reasoning_details?: unknown[]; tool_calls?: { index: number; id?: string; function?: { name?: string; arguments?: string } }[] } }[] };
38
- try { payload = JSON.parse(data); } catch { yield { type: "failure", kind: "provider", message: "Malformed OpenRouter stream" }; return; }
39
- if (!providerId && payload.id) providerId = payload.id;
101
+ try { payload = JSON.parse(data); } catch { yield { type: "failure", kind: "provider", message: endpoint ? "Malformed Chat Completions stream" : "Malformed OpenRouter stream" }; return; }
102
+ if (!providerId && payload.id) providerId = safeRequestId(payload.id);
40
103
  // A parsed response frame, unlike an HTTP success header, is evidence
41
104
  // the provider has accepted the inference request.
42
105
  if (!confirmed) { confirmed = true; yield { type: "accepted", ...(providerId ? { providerRequestId: providerId } : {}) }; }
@@ -59,14 +122,14 @@ export function openRouterAttempt(apiKey: string, model: string, fetcher: typeof
59
122
  const ordered = [...fragments.entries()].sort((a, b) => a[0] - b[0]);
60
123
  if (ordered.some(([n], i) => n !== i)) { yield { type: "failure", kind: "provider", message: "Non-contiguous tool fragments" }; return; }
61
124
  const stopReason = stop === "stop" ? "complete" : stop === "tool_calls" ? "tool_calls" : stop === "length" ? "output_limit" : undefined;
62
- if (!stopReason) { yield { type: "failure", kind: "provider", message: `Unsupported finish reason: ${stop}` }; return; }
125
+ if (!stopReason) { yield { type: "failure", kind: "provider", message: endpoint ? "Unsupported Chat Completions finish reason" : `Unsupported finish reason: ${stop}` }; return; }
63
126
  const calls = ordered.map(([, value]) => value);
64
127
  const message = { role: "assistant" as const, content: content || null, calls };
65
- const event: ModelAttemptEvent = { type: "response", response: { ...message, stopReason, providerState: { role: "assistant", content: message.content,
128
+ const event: ModelAttemptEvent = { type: "response", response: { ...message, stopReason, ...(endpoint ? {} : { providerState: { role: "assistant", content: message.content,
66
129
  ...(reasoning ? { reasoning } : {}), ...(reasoningDetails.length ? { reasoning_details: reasoningDetails } : {}),
67
- ...(calls.length ? { tool_calls: calls.map(call => ({ id: call.id, type: "function", function: { name: call.name, arguments: call.arguments } })) } : {}) } }, ...(providerId ? { providerRequestId: providerId } : {}) };
130
+ ...(calls.length ? { tool_calls: calls.map(call => ({ id: call.id, type: "function", function: { name: call.name, arguments: call.arguments } })) } : {}) } }) }, ...(providerId ? { providerRequestId: providerId } : {}) };
68
131
  yield event;
69
- } catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: String(error).replaceAll(apiKey, "[REDACTED]") }; }
70
- finally { reader.releaseLock(); }
132
+ } catch (error) { if (!signal.aborted) yield { type: "failure", kind: "transient", message: errorText(error) }; }
133
+ finally { if (endpoint) void reader.cancel().catch(() => {}); reader.releaseLock(); }
71
134
  };
72
135
  }
@@ -4,7 +4,8 @@ import type { StorageResult, TimelineEntry } from "../../contracts/storage.ts";
4
4
  /** One deadline covers the first attempt, retry wait and retry. */
5
5
  export const MODEL_EXECUTION_DEFAULTS: Readonly<ModelExecutionSettings> = { timeoutMs: 120_000, retryDelayMs: 1_000, maxRetries: 1 };
6
6
  export class ModelCallError extends Error {
7
- constructor(readonly outcome: Exclude<CallOutcome, "running" | "succeeded">, message: string) { super(message); this.name = "ModelCallError"; }
7
+ constructor(readonly outcome: Exclude<CallOutcome, "running" | "succeeded">, message: string,
8
+ readonly attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure) { super(message); this.name = "ModelCallError"; }
8
9
  }
9
10
  class ModelStorageError extends Error {}
10
11
  function take<T>(result: StorageResult<T>): T {
@@ -40,11 +41,12 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
40
41
  const call = take(options.store.startCall(options.turnId, options.itemIds));
41
42
  options.started?.(call.callId);
42
43
  let deadline = 0, output = false;
43
- const finish = (outcome: Exclude<CallOutcome, "running" | "succeeded">, detail: string = outcome): never => {
44
+ const finish = (outcome: Exclude<CallOutcome, "running" | "succeeded">, detail: string = outcome,
45
+ attachmentFailure?: import("../../contracts/attachments.ts").AttachmentFailure): never => {
44
46
  const result = options.store.finishCall(call.callId, outcome);
45
47
  if (!result.ok && !(outcome === "interrupted" && result.error.code === "invalid_state")) take(result);
46
48
  if (output) options.incomplete?.({ messageId: call.messageId, reason: outcome });
47
- throw new ModelCallError(outcome, detail);
49
+ throw new ModelCallError(outcome, detail, attachmentFailure);
48
50
  };
49
51
  for (let ordinal = 0; ordinal <= Math.min(1, settings.maxRetries); ordinal++) {
50
52
  if (options.signal?.aborted) return finish("interrupted");
@@ -102,6 +104,7 @@ export async function runModelCall(options: RunModelCallOptions): Promise<{ resp
102
104
  const attemptOutcome = failure === "transient" ? "transient_failure" : failure === "provider" ? "provider_failure" : failure;
103
105
  take(options.store.finishAttempt(call.callId, attempt.attemptId, attemptOutcome));
104
106
  if (terminal?.type === "failure" && terminal.message === "script_exhausted" && options.scripted) return finish("failed", "script_exhausted");
107
+ if (terminal?.type === "failure" && terminal.code) return finish("failed", terminal.message, { code: terminal.code, attachmentIds: [...terminal.attachmentIds ?? []] });
105
108
  if (failure !== "transient" || output || ordinal >= Math.min(1, settings.maxRetries)) return finish(failure === "incomplete" ? "incomplete" : "failed");
106
109
  if (deadline - Date.now() < settings.retryDelayMs) return finish("timeout");
107
110
  const delay = await new Promise<"ready" | "interrupted">(resolve => {
@@ -0,0 +1,97 @@
1
+ import type { JSONRPCMessage } from "@modelcontextprotocol/sdk/types.js";
2
+ import type { McpTool } from "../../../contracts/mcp.ts";
3
+ import { acceptsMcpSchema, matchesMcpArguments, mcpToolName } from "./schema.ts";
4
+ import { mcpSecrets } from "./secrets.ts";
5
+ import { projectMcpResult } from "./result.ts";
6
+ import { McpStdioTransport, type McpStdioProcess } from "./stdio.ts";
7
+
8
+ const encoder = new TextEncoder();
9
+
10
+ type Transport = import("@modelcontextprotocol/sdk/shared/transport.js").Transport;
11
+ export const supportedMcpVersions = new Set(["2025-03-26", "2025-06-18", "2025-11-25"]);
12
+
13
+ export function connectMcpStdio(name: string, child: McpStdioProcess, deadlineMs?: number, secrets?: readonly string[]) {
14
+ return connectMcp(name, async () => {
15
+ const { JSONRPCMessageSchema } = await import("@modelcontextprotocol/sdk/types.js");
16
+ const transport = new McpStdioTransport<JSONRPCMessage>(child, supportedMcpVersions, value => JSONRPCMessageSchema.parse(value));
17
+ return { transport, drain: () => transport.drain() };
18
+ }, deadlineMs, secrets, () => child.close());
19
+ }
20
+
21
+ export async function connectMcp(name: string,
22
+ assemble: () => Promise<{ transport: Transport; drain(): Promise<void> }>,
23
+ deadlineMs = 1_800_000, secrets: readonly string[] = [], rollback?: () => Promise<void>) {
24
+ let transport: Transport | undefined;
25
+ const startup = AbortSignal.timeout(10_000);
26
+ try {
27
+ const redact = mcpSecrets(secrets);
28
+ const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
29
+ const { ErrorCode, McpError } = await import("@modelcontextprotocol/sdk/types.js");
30
+ const live = await assemble();
31
+ transport = live.transport;
32
+ const client = new Client({ name: "native-harness", version: "1" }, { capabilities: {} });
33
+ let ready = true;
34
+ const shutdown = new AbortController();
35
+ client.onclose = () => { ready = false; };
36
+ await client.connect(transport, { signal: startup, timeout: 10_000 });
37
+ if (!client.getServerCapabilities()?.tools) throw new Error("MCP tools unavailable");
38
+ const bindings = new Map<string, McpTool>();
39
+ const cursors = new Set<string>();
40
+ let bytes = 0;
41
+ let cursor: string | undefined;
42
+ for (let page = 0; ; page++) {
43
+ if (page === 4) throw new Error("MCP catalog exceeds page limit");
44
+ const list = await client.listTools(cursor === undefined ? undefined : { cursor }, { signal: startup, timeout: 10_000 });
45
+ for (const remote of list.tools) {
46
+ if (redact.contains(remote.name)) throw new Error("Unsafe MCP tool name");
47
+ redact.tree(remote.inputSchema, true);
48
+ const key = mcpToolName(name, remote.name);
49
+ const schema = remote.inputSchema;
50
+ if (!key || bindings.has(key) || bindings.size === 32 || !acceptsMcpSchema(schema)) throw new Error("Invalid MCP tool catalog");
51
+ const definition = { name: key, description: redact.text(remote.description ?? ""), parameters: schema };
52
+ bytes += encoder.encode(JSON.stringify(definition)).length;
53
+ if (bytes > 128 * 1024) throw new Error("MCP catalog exceeds byte limit");
54
+ bindings.set(key, {
55
+ definition,
56
+ available: () => ready,
57
+ accepts: args => encoder.encode(JSON.stringify(args)).length <= 16 * 1024 && matchesMcpArguments(schema, args),
58
+ async call(args, signal) {
59
+ const fail = (code: string) => ({ content: JSON.stringify({ ok: false, code }), code });
60
+ if (!ready) return fail("tool_unavailable");
61
+ if (signal.aborted) return fail("tool_interrupted");
62
+ try {
63
+ const result = await client.callTool({ name: remote.name, arguments: args }, undefined, {
64
+ timeout: deadlineMs, signal: AbortSignal.any([signal, shutdown.signal]), resetTimeoutOnProgress: false, onprogress() {},
65
+ });
66
+ if (result.isError) return fail("mcp_tool_error");
67
+ if (!Array.isArray(result.content)) return fail("mcp_protocol_error");
68
+ try {
69
+ return { content: projectMcpResult({
70
+ content: result.content,
71
+ structuredContent: redact.tree(result.structuredContent),
72
+ }, redact.text) };
73
+ } catch { return fail("mcp_protocol_error"); }
74
+ } catch (error) {
75
+ if (signal.aborted) return fail("tool_interrupted");
76
+ if (error instanceof McpError && error.code === ErrorCode.RequestTimeout) return fail("tool_timeout");
77
+ return fail(ready && error instanceof McpError && error.code !== ErrorCode.ConnectionClosed
78
+ ? "mcp_protocol_error" : "mcp_uncertain");
79
+ }
80
+ },
81
+ });
82
+ }
83
+ cursor = list.nextCursor;
84
+ if (cursor === undefined) break;
85
+ if (cursors.has(cursor)) throw new Error("MCP catalog cursor repeated");
86
+ cursors.add(cursor);
87
+ }
88
+ return { name, bindings, bytes, available: () => ready, async close() {
89
+ shutdown.abort();
90
+ await live.drain();
91
+ await client.close();
92
+ } };
93
+ } catch {
94
+ await (transport?.close() ?? rollback?.());
95
+ throw new Error("MCP initialization failed");
96
+ }
97
+ }
@@ -0,0 +1,183 @@
1
+ import { connectMcp, supportedMcpVersions } from "./client.ts";
2
+
3
+ const receiveLimit = 256 * 1024;
4
+ type Fetch = (...args: Parameters<typeof fetch>) => Promise<Response>;
5
+
6
+ export function connectMcpHttps(name: string, endpoint: string, headers: Record<string, string>,
7
+ deadlineMs?: number, secrets?: readonly string[], fixtureCa?: string) {
8
+ return connectMcp(name, async () => {
9
+ const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");
10
+ // The Bun package-name shim delegates back to proxy-aware Bun fetch.
11
+ const undici: typeof import("undici") = await import(new URL("index.js", import.meta.resolve("undici/package.json")).href);
12
+ const dispatcher = new undici.Agent({ headersTimeout: 0, bodyTimeout: 0,
13
+ connect: { rejectUnauthorized: true, ...(fixtureCa === undefined ? {} : { ca: fixtureCa }) } });
14
+ const send: Fetch = async (input, init) => {
15
+ const response = await dispatcher.request({
16
+ origin: new URL(String(input)).origin,
17
+ path: new URL(String(input)).pathname,
18
+ method: "POST", body: String(init?.body), signal: init?.signal ?? undefined,
19
+ headers: { ...Object.fromEntries(new Headers(init?.headers)), "accept-encoding": "identity" },
20
+ });
21
+ // Undici reports deliberate destruction through the Node error event.
22
+ // The iterator still observes read errors; discarded bodies have no reader.
23
+ response.body.on("error", () => {});
24
+ const discard = async () => {
25
+ if (response.body.closed) return;
26
+ await new Promise<void>(resolve => {
27
+ response.body.once("close", resolve);
28
+ response.body.destroy();
29
+ });
30
+ };
31
+ const headers = new Headers();
32
+ for (const [name, value] of Object.entries(response.headers)) {
33
+ if (typeof value === "string") headers.set(name, value);
34
+ else for (const item of value ?? []) headers.append(name, item);
35
+ }
36
+ const encoding = headers.get("content-encoding");
37
+ if ((response.statusCode >= 300 && response.statusCode < 400) || (encoding && encoding.toLowerCase() !== "identity")) {
38
+ await discard();
39
+ throw new Error("MCP HTTPS response refused");
40
+ }
41
+ if (response.statusCode >= 400 || [204, 205].includes(response.statusCode)) {
42
+ await discard();
43
+ return new Response(null, { status: response.statusCode, headers });
44
+ }
45
+ // Pull from Undici directly. Bun's Readable.toWeb adapter can enqueue
46
+ // after cancel and throw outside the request's error path.
47
+ const source = response.body.iterator();
48
+ let cancelled = false;
49
+ const body = new ReadableStream<Uint8Array>({
50
+ async pull(controller) {
51
+ try {
52
+ const next = await source.next();
53
+ if (cancelled) return;
54
+ if (next.done) controller.close();
55
+ else controller.enqueue(next.value);
56
+ } catch (error) {
57
+ if (!cancelled) controller.error(error);
58
+ }
59
+ },
60
+ async cancel() {
61
+ cancelled = true;
62
+ await discard();
63
+ await source.return?.().catch(() => {});
64
+ },
65
+ });
66
+ return new Response(body, { status: response.statusCode, headers });
67
+ };
68
+ const requests = new Map<number | string, AbortController>();
69
+ const finished = new Set<number | string>();
70
+ const receiveFailure = (id: number | string, lifetime: AbortController) => {
71
+ setTimeout(() => {
72
+ if (requests.get(id) === lifetime && !lifetime.signal.aborted && !finished.has(id)) void transport.close().catch(() => {});
73
+ release(id);
74
+ }, 0);
75
+ };
76
+ function release(id: number | string) {
77
+ requests.delete(id);
78
+ finished.delete(id);
79
+ }
80
+ const cancellations = new Set<Promise<void>>();
81
+ const fencedFetch: Fetch = async (input, init) => {
82
+ if (String(input) !== endpoint) throw new Error("MCP endpoint refused");
83
+ if (init?.method === "GET") return new Response(null, { status: 405 });
84
+ if (init?.method !== "POST") throw new Error("MCP method refused");
85
+ const message = JSON.parse(String(init.body));
86
+ const id: unknown = message.id;
87
+ const requestId = typeof id === "number" || typeof id === "string" ? id : undefined;
88
+ const cancelId = message.method === "notifications/cancelled" ? message.params?.requestId : undefined;
89
+ const lifetime = requestId === undefined ? undefined : new AbortController();
90
+ const signals = [init.signal, lifetime?.signal, requestId === undefined ? AbortSignal.timeout(250) : undefined]
91
+ .filter((signal): signal is AbortSignal => !!signal);
92
+ if (lifetime && requestId !== undefined) requests.set(requestId, lifetime);
93
+ let done: (() => void) | undefined;
94
+ if (cancelId !== undefined) {
95
+ let finish!: () => void;
96
+ const pending = new Promise<void>(resolve => { finish = resolve; });
97
+ cancellations.add(pending);
98
+ done = () => { requests.get(cancelId)?.abort(); cancellations.delete(pending); finish(); };
99
+ }
100
+ const releaseRequest = () => { if (requestId !== undefined) release(requestId); };
101
+ try {
102
+ const response = await send(endpoint, { ...init, redirect: "error", signal: AbortSignal.any(signals) });
103
+ if (!response.ok || requestId === undefined) {
104
+ await response.body?.cancel();
105
+ releaseRequest();
106
+ return new Response(null, { status: response.status, headers: response.headers });
107
+ }
108
+ if (!response.body) { releaseRequest(); return response; }
109
+ const reader = response.body.getReader();
110
+ const streamed = response.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() === "text/event-stream";
111
+ let count = 0;
112
+ let jsonStart = !streamed;
113
+ const body = new ReadableStream<Uint8Array>({
114
+ async pull(controller) {
115
+ try {
116
+ const chunk = await reader.read();
117
+ if (chunk.done) {
118
+ controller.close();
119
+ if (streamed) receiveFailure(requestId, lifetime!);
120
+ else releaseRequest();
121
+ return;
122
+ }
123
+ count += chunk.value.byteLength;
124
+ if (count > receiveLimit) {
125
+ await reader.cancel();
126
+ throw new Error("MCP response limit exceeded");
127
+ }
128
+ if (jsonStart) {
129
+ for (const byte of chunk.value) {
130
+ if (byte === 32 || byte === 9 || byte === 10 || byte === 13) continue;
131
+ if (byte === 91) { await reader.cancel(); throw new Error("MCP response batch refused"); }
132
+ jsonStart = false;
133
+ break;
134
+ }
135
+ }
136
+ controller.enqueue(chunk.value);
137
+ } catch (error) {
138
+ if (streamed) receiveFailure(requestId, lifetime!);
139
+ else releaseRequest();
140
+ controller.error(error);
141
+ }
142
+ },
143
+ async cancel() { releaseRequest(); await reader.cancel(); },
144
+ });
145
+ return new Response(body, { status: response.status, headers: response.headers });
146
+ } catch {
147
+ releaseRequest();
148
+ throw new Error("MCP HTTPS request failed");
149
+ } finally { done?.(); }
150
+ };
151
+ const transport = new StreamableHTTPClientTransport(new URL(endpoint), {
152
+ requestInit: { headers },
153
+ fetch: fencedFetch,
154
+ reconnectionOptions: { maxRetries: 0, initialReconnectionDelay: 0, maxReconnectionDelay: 0, reconnectionDelayGrowFactor: 1 },
155
+ });
156
+ const close = transport.close.bind(transport);
157
+ let closing: Promise<void> | undefined;
158
+ transport.close = () => closing ??= (async () => {
159
+ try { await close(); } finally { await dispatcher.destroy(); }
160
+ })();
161
+ const start = transport.start.bind(transport);
162
+ transport.start = async () => {
163
+ const onmessage = transport.onmessage;
164
+ transport.onmessage = message => {
165
+ if ("id" in message && ("result" in message || "error" in message) && message.id !== undefined && requests.has(message.id)) {
166
+ finished.add(message.id);
167
+ }
168
+ onmessage?.(message);
169
+ };
170
+ await start();
171
+ };
172
+ const setVersion = transport.setProtocolVersion.bind(transport);
173
+ transport.setProtocolVersion = version => {
174
+ if (!supportedMcpVersions.has(version)) throw new Error("Unsupported MCP protocol revision");
175
+ setVersion(version);
176
+ };
177
+ return { transport, async drain() {
178
+ // SDK cancellation enters async send before its POST reaches fencedFetch.
179
+ await Bun.sleep(0);
180
+ await Promise.allSettled(cancellations);
181
+ } };
182
+ }, deadlineMs, secrets);
183
+ }
@@ -0,0 +1,62 @@
1
+ import type { ManagedConfig } from "../../../contracts/config-permissions.ts";
2
+ import { spawnMcpStdio } from "../../../runtime/execution/mcp-stdio.ts";
3
+ import type { McpServerStatus, McpTool } from "../../../contracts/mcp.ts";
4
+ import { connectMcpHttps } from "./http.ts";
5
+ import { resolveMcpHttpsHeaders } from "../../../util/mcp-config.ts";
6
+ import { connectMcpStdio } from "./client.ts";
7
+
8
+ export async function openMcpRegistry(config: ManagedConfig, environment: Record<string, string | undefined>,
9
+ runtimeHeaders?: Record<string, Record<string, string>>, fixtureCa?: string) {
10
+ const entries = Object.entries(config.mcpServers ?? {}).sort(([a], [b]) => a.localeCompare(b));
11
+ type Connection = Awaited<ReturnType<typeof connectMcpStdio>>;
12
+ const connections: Connection[] = [];
13
+ const bindings = new Map<string, McpTool>();
14
+ const status = Object.create(null) as Record<string, McpServerStatus>;
15
+ let bytes = 0;
16
+ for (let offset = 0; offset < entries.length; offset += 4) {
17
+ const batch = await Promise.all(entries.slice(offset, offset + 4).map(async ([name, entry]) => {
18
+ const transport = entry.transport;
19
+ if (entry.enabled === false) { status[name] = { transport, state: "disabled" }; return; }
20
+ if (transport === "http") {
21
+ const resolved = resolveMcpHttpsHeaders(entry, environment, runtimeHeaders?.[name]);
22
+ if (!resolved) { status[name] = { transport, state: "unavailable", reason: "config" }; return; }
23
+ try {
24
+ const connection = await connectMcpHttps(name, entry.endpoint, resolved.headers, config.limits?.mcpCallTimeoutMs, resolved.secrets, fixtureCa);
25
+ return { name, connection, transport };
26
+ } catch { status[name] = { transport, state: "unavailable", reason: "connect" }; return; }
27
+ }
28
+ const env: Record<string, string> = Object.create(null);
29
+ for (const [key, value] of Object.entries(entry.env ?? {})) {
30
+ const resolved = environment[value.env];
31
+ if (!resolved?.trim() || resolved.includes("\0")) {
32
+ status[name] = { transport, state: "unavailable", reason: "config" }; return;
33
+ }
34
+ env[key] = resolved;
35
+ }
36
+ let child;
37
+ try { child = spawnMcpStdio({ ...entry, env }); }
38
+ catch { status[name] = { transport, state: "unavailable", reason: "spawn" }; return; }
39
+ try { return { name, connection: await connectMcpStdio(name, child, config.limits?.mcpCallTimeoutMs, Object.values(env)), transport }; }
40
+ catch { status[name] = { transport, state: "unavailable", reason: "discovery" }; return; }
41
+ }));
42
+ for (const result of batch) {
43
+ if (!result) continue;
44
+ const { name, connection, transport } = result;
45
+ if (bytes + connection.bytes > 128 * 1024 || bindings.size + connection.bindings.size > 64) {
46
+ status[name] = { transport, state: "unavailable", reason: "limit" };
47
+ await connection.close();
48
+ } else {
49
+ status[name] = { transport, state: "ready" };
50
+ bytes += connection.bytes;
51
+ connections.push(connection);
52
+ for (const [id, tool] of connection.bindings) bindings.set(id, tool);
53
+ }
54
+ }
55
+ }
56
+ let closing: Promise<void> | undefined;
57
+ return { bindings, status() {
58
+ return Object.fromEntries(Object.entries(status).map(([name, state]) => [name,
59
+ state.state === "ready" && connections.some(connection => connection.name === name && !connection.available())
60
+ ? { ...state, state: "unavailable" as const, reason: "closed" as const } : state]));
61
+ }, close() { return closing ??= Promise.allSettled(connections.map(connection => connection.close())).then(() => {}); } };
62
+ }
@@ -0,0 +1,33 @@
1
+ /** SDK-validated result, projected without exposing unsupported block payloads. */
2
+ export function projectMcpResult(result: {
3
+ content: readonly { type: string; text?: string }[];
4
+ structuredContent?: unknown;
5
+ }, redactText: (text: string) => string = text => text): string {
6
+ const textBlocks = result.content.filter(block => block.type === "text" && typeof block.text === "string");
7
+ const output = {
8
+ text: redactText(textBlocks.map(block => block.text).join("\n")),
9
+ structuredContent: result.structuredContent ?? null,
10
+ omittedContentBlocks: result.content.length - textBlocks.length,
11
+ truncated: false,
12
+ };
13
+ const serialize = () => JSON.stringify(output);
14
+ const fits = () => Buffer.byteLength(serialize()) <= 2048;
15
+ if (fits()) return serialize();
16
+ output.truncated = true;
17
+ if (output.structuredContent !== null) output.structuredContent = null;
18
+ if (fits()) return serialize();
19
+ const units: string[] = [];
20
+ for (const unit of output.text) {
21
+ if (units.length === 2048) break;
22
+ units.push(unit);
23
+ }
24
+ let low = 0, high = units.length;
25
+ while (low < high) {
26
+ const mid = Math.ceil((low + high) / 2);
27
+ output.text = units.slice(0, mid).join("");
28
+ if (fits()) low = mid;
29
+ else high = mid - 1;
30
+ }
31
+ output.text = units.slice(0, low).join("");
32
+ return serialize();
33
+ }
@@ -0,0 +1,77 @@
1
+ const types = new Set(["object", "array", "string", "boolean", "integer", "number", "null"]);
2
+
3
+ interface Schema {
4
+ type: string;
5
+ properties?: Record<string, Schema>;
6
+ required?: string[];
7
+ additionalProperties?: boolean;
8
+ items?: Schema;
9
+ enum?: unknown[];
10
+ }
11
+
12
+ function record(value: unknown): value is Record<string, unknown> {
13
+ return value !== null && typeof value === "object" && !Array.isArray(value);
14
+ }
15
+
16
+ function matches(type: string, value: unknown): boolean {
17
+ switch (type) {
18
+ case "object": return record(value);
19
+ case "array": return Array.isArray(value);
20
+ case "integer": return Number.isInteger(value);
21
+ case "number": return typeof value === "number" && Number.isFinite(value);
22
+ case "null": return value === null;
23
+ default: return typeof value === type;
24
+ }
25
+ }
26
+
27
+ export function acceptsMcpSchema(input: unknown): input is Schema {
28
+ let nodes = 0;
29
+ function visit(node: unknown, depth: number): boolean {
30
+ if (++nodes > 128 || depth > 8 || !record(node) || typeof node.type !== "string" || !types.has(node.type)) return false;
31
+ for (const [key, value] of Object.entries(node)) {
32
+ switch (key) {
33
+ case "type": break;
34
+ case "description": case "title": if (typeof value !== "string") return false; break;
35
+ case "properties":
36
+ if (node.type !== "object" || !record(value) || !Object.values(value).every(child => visit(child, depth + 1))) return false;
37
+ break;
38
+ case "required":
39
+ if (node.type !== "object" || !Array.isArray(value) || new Set(value).size !== value.length ||
40
+ !value.every(name => typeof name === "string" && record(node.properties) && Object.hasOwn(node.properties, name))) return false;
41
+ break;
42
+ case "additionalProperties":
43
+ if (node.type !== "object" || typeof value !== "boolean") return false;
44
+ break;
45
+ case "items":
46
+ if (node.type !== "array" || !visit(value, depth + 1)) return false;
47
+ break;
48
+ case "enum":
49
+ if (!Array.isArray(value) || !value.length || new Set(value).size !== value.length ||
50
+ node.type === "object" || node.type === "array" || !value.every(member => matches(node.type as string, member))) return false;
51
+ break;
52
+ default: return false;
53
+ }
54
+ }
55
+ return true;
56
+ }
57
+ return record(input) && input.type === "object" && visit(input, 1) &&
58
+ Buffer.byteLength(JSON.stringify(input)) <= 8192;
59
+ }
60
+
61
+ export function matchesMcpArguments(schema: Schema, value: unknown): boolean {
62
+ if (!matches(schema.type, value) || (schema.enum && !schema.enum.includes(value))) return false;
63
+ if (schema.items && Array.isArray(value)) return value.every(item => matchesMcpArguments(schema.items!, item));
64
+ if (!record(value)) return true;
65
+ if (schema.required?.some(key => !Object.hasOwn(value, key))) return false;
66
+ return Object.entries(value).every(([key, entry]) => {
67
+ const properties = schema.properties;
68
+ return properties && Object.hasOwn(properties, key)
69
+ ? matchesMcpArguments(properties[key]!, entry)
70
+ : schema.additionalProperties !== false;
71
+ });
72
+ }
73
+
74
+ export function mcpToolName(server: string, remote: string): string | undefined {
75
+ if (!/^[a-z][a-z0-9]{0,11}$/.test(server) || !remote || !remote.isWellFormed() || Buffer.byteLength(remote) > 22) return;
76
+ return `mcp__${server}__${Buffer.from(remote).toString("hex")}`;
77
+ }