@zvada/agent-server 0.3.24 → 0.3.26

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 (190) hide show
  1. package/CHANGELOG.md +110 -0
  2. package/README.md +3 -0
  3. package/dist/client/client.js +93 -34
  4. package/dist/core/agents/acp/acp-agent.js +91 -14
  5. package/dist/core/agents/acp/mappings.js +5 -1
  6. package/dist/core/agents/claude-code/approvals.js +2 -1
  7. package/dist/core/agents/claude-code/claude-agent.js +12 -2
  8. package/dist/core/agents/claude-code/mcp.js +9 -1
  9. package/dist/core/agents/claude-code/models.js +16 -10
  10. package/dist/core/agents/claude-code/options.js +23 -2
  11. package/dist/core/agents/claude-code/session.js +21 -1
  12. package/dist/core/agents/claude-code/tools.js +9 -4
  13. package/dist/core/agents/claude-code/turn.js +2 -0
  14. package/dist/core/agents/codex-app-server/adapter.js +2 -0
  15. package/dist/core/agents/codex-app-server/client.js +8 -5
  16. package/dist/core/agents/codex-app-server/codex-agent.js +35 -2
  17. package/dist/core/agents/codex-app-server/effort.js +13 -6
  18. package/dist/core/agents/codex-app-server/mcp.js +35 -18
  19. package/dist/core/agents/codex-app-server/models.js +10 -10
  20. package/dist/core/agents/codex-app-server/options.js +11 -2
  21. package/dist/core/agents/codex-app-server/session.js +11 -4
  22. package/dist/core/agents/codex-app-server/thread-settings.js +30 -11
  23. package/dist/core/agents/host-tools.js +493 -0
  24. package/dist/core/agents/mcp-config.js +6 -2
  25. package/dist/core/agents/scripted/scripted-agent.js +11 -4
  26. package/dist/core/agents/scripted/steps.js +5 -1
  27. package/dist/core/agents/session-agent.js +70 -2
  28. package/dist/core/agents/thinking-levels.js +8 -5
  29. package/dist/core/index.js +1 -0
  30. package/dist/core/presets.js +12 -2
  31. package/dist/core/processes/identity.js +1 -0
  32. package/dist/core/processes/lifeline.js +13 -1
  33. package/dist/core/processes/process-table.js +1 -0
  34. package/dist/core/provision/extract.js +1 -0
  35. package/dist/core/provision/pins.js +7 -16
  36. package/dist/core/provision/releases.js +25 -25
  37. package/dist/core/proxy/loopback.js +22 -4
  38. package/dist/core/runtime/agent-runtime.js +6 -3
  39. package/dist/core/runtime/turn.js +20 -10
  40. package/dist/protocol/config.js +21 -1
  41. package/dist/protocol/credentials.js +2 -1
  42. package/dist/protocol/errors.js +12 -3
  43. package/dist/protocol/model-catalog.js +58 -18
  44. package/dist/protocol/models.js +6 -27
  45. package/dist/protocol/thinking.js +22 -9
  46. package/dist/protocol/wire-api.js +2 -2
  47. package/dist/server/bin.js +6 -4
  48. package/dist/server/routes.js +3 -2
  49. package/dist/types/client/client.d.ts +6 -1
  50. package/dist/types/client/client.d.ts.map +1 -1
  51. package/dist/types/core/agents/acp/acp-agent.d.ts +15 -0
  52. package/dist/types/core/agents/acp/acp-agent.d.ts.map +1 -1
  53. package/dist/types/core/agents/acp/mappings.d.ts +5 -1
  54. package/dist/types/core/agents/acp/mappings.d.ts.map +1 -1
  55. package/dist/types/core/agents/acp/requests.d.ts +2 -0
  56. package/dist/types/core/agents/acp/requests.d.ts.map +1 -1
  57. package/dist/types/core/agents/claude-code/approvals.d.ts +2 -1
  58. package/dist/types/core/agents/claude-code/approvals.d.ts.map +1 -1
  59. package/dist/types/core/agents/claude-code/claude-agent.d.ts +1 -0
  60. package/dist/types/core/agents/claude-code/claude-agent.d.ts.map +1 -1
  61. package/dist/types/core/agents/claude-code/mcp.d.ts +8 -1
  62. package/dist/types/core/agents/claude-code/mcp.d.ts.map +1 -1
  63. package/dist/types/core/agents/claude-code/models.d.ts +9 -5
  64. package/dist/types/core/agents/claude-code/models.d.ts.map +1 -1
  65. package/dist/types/core/agents/claude-code/options.d.ts +14 -1
  66. package/dist/types/core/agents/claude-code/options.d.ts.map +1 -1
  67. package/dist/types/core/agents/claude-code/session.d.ts +2 -0
  68. package/dist/types/core/agents/claude-code/session.d.ts.map +1 -1
  69. package/dist/types/core/agents/claude-code/tools.d.ts.map +1 -1
  70. package/dist/types/core/agents/claude-code/turn.d.ts +3 -0
  71. package/dist/types/core/agents/claude-code/turn.d.ts.map +1 -1
  72. package/dist/types/core/agents/codex-app-server/adapter.d.ts.map +1 -1
  73. package/dist/types/core/agents/codex-app-server/client.d.ts +2 -0
  74. package/dist/types/core/agents/codex-app-server/client.d.ts.map +1 -1
  75. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts +11 -0
  76. package/dist/types/core/agents/codex-app-server/codex-agent.d.ts.map +1 -1
  77. package/dist/types/core/agents/codex-app-server/effort.d.ts +7 -7
  78. package/dist/types/core/agents/codex-app-server/effort.d.ts.map +1 -1
  79. package/dist/types/core/agents/codex-app-server/mcp.d.ts +11 -3
  80. package/dist/types/core/agents/codex-app-server/mcp.d.ts.map +1 -1
  81. package/dist/types/core/agents/codex-app-server/models.d.ts +4 -1
  82. package/dist/types/core/agents/codex-app-server/models.d.ts.map +1 -1
  83. package/dist/types/core/agents/codex-app-server/options.d.ts +9 -2
  84. package/dist/types/core/agents/codex-app-server/options.d.ts.map +1 -1
  85. package/dist/types/core/agents/codex-app-server/requests.d.ts +2 -0
  86. package/dist/types/core/agents/codex-app-server/requests.d.ts.map +1 -1
  87. package/dist/types/core/agents/codex-app-server/session.d.ts +6 -3
  88. package/dist/types/core/agents/codex-app-server/session.d.ts.map +1 -1
  89. package/dist/types/core/agents/codex-app-server/thread-settings.d.ts.map +1 -1
  90. package/dist/types/core/agents/host-tools.d.ts +162 -0
  91. package/dist/types/core/agents/host-tools.d.ts.map +1 -0
  92. package/dist/types/core/agents/mcp-config.d.ts +11 -2
  93. package/dist/types/core/agents/mcp-config.d.ts.map +1 -1
  94. package/dist/types/core/agents/scripted/scripted-agent.d.ts.map +1 -1
  95. package/dist/types/core/agents/scripted/steps.d.ts +1 -1
  96. package/dist/types/core/agents/scripted/steps.d.ts.map +1 -1
  97. package/dist/types/core/agents/session-agent.d.ts +2 -7
  98. package/dist/types/core/agents/session-agent.d.ts.map +1 -1
  99. package/dist/types/core/agents/thinking-levels.d.ts +7 -3
  100. package/dist/types/core/agents/thinking-levels.d.ts.map +1 -1
  101. package/dist/types/core/index.d.ts +1 -0
  102. package/dist/types/core/index.d.ts.map +1 -1
  103. package/dist/types/core/presets.d.ts +11 -1
  104. package/dist/types/core/presets.d.ts.map +1 -1
  105. package/dist/types/core/processes/identity.d.ts.map +1 -1
  106. package/dist/types/core/processes/lifeline.d.ts.map +1 -1
  107. package/dist/types/core/processes/process-table.d.ts.map +1 -1
  108. package/dist/types/core/provision/extract.d.ts.map +1 -1
  109. package/dist/types/core/provision/pins.d.ts +5 -4
  110. package/dist/types/core/provision/pins.d.ts.map +1 -1
  111. package/dist/types/core/proxy/loopback.d.ts.map +1 -1
  112. package/dist/types/core/runtime/agent-runtime.d.ts +4 -1
  113. package/dist/types/core/runtime/agent-runtime.d.ts.map +1 -1
  114. package/dist/types/core/runtime/turn.d.ts +12 -7
  115. package/dist/types/core/runtime/turn.d.ts.map +1 -1
  116. package/dist/types/protocol/clis.d.ts +3 -3
  117. package/dist/types/protocol/config.d.ts +12 -19
  118. package/dist/types/protocol/config.d.ts.map +1 -1
  119. package/dist/types/protocol/conversation.d.ts +10 -42
  120. package/dist/types/protocol/conversation.d.ts.map +1 -1
  121. package/dist/types/protocol/credentials.d.ts +13 -1
  122. package/dist/types/protocol/credentials.d.ts.map +1 -1
  123. package/dist/types/protocol/errors.d.ts +6 -4
  124. package/dist/types/protocol/errors.d.ts.map +1 -1
  125. package/dist/types/protocol/execution.d.ts +2 -18
  126. package/dist/types/protocol/execution.d.ts.map +1 -1
  127. package/dist/types/protocol/lifecycle.d.ts +12 -76
  128. package/dist/types/protocol/lifecycle.d.ts.map +1 -1
  129. package/dist/types/protocol/model-catalog.d.ts.map +1 -1
  130. package/dist/types/protocol/models.d.ts +4 -42
  131. package/dist/types/protocol/models.d.ts.map +1 -1
  132. package/dist/types/protocol/thinking.d.ts +19 -19
  133. package/dist/types/protocol/thinking.d.ts.map +1 -1
  134. package/dist/types/protocol/wire-api.d.ts +32 -117
  135. package/dist/types/protocol/wire-api.d.ts.map +1 -1
  136. package/dist/types/protocol/wire.d.ts +24 -125
  137. package/dist/types/protocol/wire.d.ts.map +1 -1
  138. package/dist/types/server/routes.d.ts.map +1 -1
  139. package/docs/consuming.md +92 -12
  140. package/docs/deploy.md +8 -0
  141. package/docs/harnesses.md +88 -27
  142. package/package.json +4 -4
  143. package/src/client/client.ts +114 -44
  144. package/src/core/agents/acp/acp-agent.ts +123 -17
  145. package/src/core/agents/acp/mappings.ts +5 -1
  146. package/src/core/agents/acp/requests.ts +2 -0
  147. package/src/core/agents/claude-code/approvals.ts +2 -1
  148. package/src/core/agents/claude-code/claude-agent.ts +14 -2
  149. package/src/core/agents/claude-code/mcp.ts +11 -1
  150. package/src/core/agents/claude-code/models.ts +15 -10
  151. package/src/core/agents/claude-code/options.ts +37 -3
  152. package/src/core/agents/claude-code/session.ts +26 -1
  153. package/src/core/agents/claude-code/tools.ts +10 -4
  154. package/src/core/agents/claude-code/turn.ts +4 -0
  155. package/src/core/agents/codex-app-server/adapter.ts +2 -0
  156. package/src/core/agents/codex-app-server/client.ts +11 -5
  157. package/src/core/agents/codex-app-server/codex-agent.ts +45 -1
  158. package/src/core/agents/codex-app-server/effort.ts +15 -20
  159. package/src/core/agents/codex-app-server/mcp.ts +46 -23
  160. package/src/core/agents/codex-app-server/models.ts +10 -10
  161. package/src/core/agents/codex-app-server/options.ts +16 -2
  162. package/src/core/agents/codex-app-server/requests.ts +2 -0
  163. package/src/core/agents/codex-app-server/session.ts +19 -4
  164. package/src/core/agents/codex-app-server/thread-settings.ts +31 -11
  165. package/src/core/agents/host-tools.ts +649 -0
  166. package/src/core/agents/mcp-config.ts +15 -3
  167. package/src/core/agents/scripted/scripted-agent.ts +11 -3
  168. package/src/core/agents/scripted/steps.ts +5 -1
  169. package/src/core/agents/session-agent.ts +78 -2
  170. package/src/core/agents/thinking-levels.ts +9 -6
  171. package/src/core/index.ts +9 -0
  172. package/src/core/presets.ts +24 -3
  173. package/src/core/processes/identity.ts +1 -0
  174. package/src/core/processes/lifeline.ts +14 -1
  175. package/src/core/processes/process-table.ts +1 -0
  176. package/src/core/provision/extract.ts +1 -0
  177. package/src/core/provision/pins.ts +7 -16
  178. package/src/core/provision/releases.ts +25 -25
  179. package/src/core/proxy/loopback.ts +25 -4
  180. package/src/core/runtime/agent-runtime.ts +6 -3
  181. package/src/core/runtime/turn.ts +21 -9
  182. package/src/protocol/config.ts +22 -1
  183. package/src/protocol/credentials.ts +19 -5
  184. package/src/protocol/errors.ts +12 -3
  185. package/src/protocol/model-catalog.ts +58 -18
  186. package/src/protocol/models.ts +6 -26
  187. package/src/protocol/thinking.ts +27 -14
  188. package/src/protocol/wire-api.ts +2 -2
  189. package/src/server/bin.ts +6 -4
  190. package/src/server/routes.ts +3 -2
@@ -0,0 +1,649 @@
1
+ import { randomBytes } from "node:crypto";
2
+ import {
3
+ type AgentHarness,
4
+ MAX_REQUEST_TIMEOUT_MS,
5
+ type McpServerConfig,
6
+ type PermissionMode,
7
+ } from "../../protocol/index.ts";
8
+ import { type Loopback, serveLoopback } from "../proxy/loopback.ts";
9
+ import { onAbort } from "../utils/deadline.ts";
10
+ import { InvalidRequestError, McpUnavailableError } from "../utils/errors.ts";
11
+
12
+ // @ref LLP 0018#the-api — one tool source, every harness
13
+
14
+ /** A tool the host gives its sessions' agents. */
15
+ export interface HostTool {
16
+ name: string;
17
+ description: string;
18
+ /** The JSON Schema of its arguments: an object schema. */
19
+ inputSchema: Record<string, unknown>;
20
+ /** MCP's `readOnlyHint` and `destructiveHint`: Codex runs a read-only tool without asking. */
21
+ annotations?: { readOnly?: boolean; destructive?: boolean };
22
+ }
23
+
24
+ export type HostToolContent =
25
+ | { type: "text"; text: string }
26
+ | { type: "image"; data: string; mimeType: string };
27
+
28
+ /** What a call answers: its content, and whether it failed (the model reads why). */
29
+ export interface HostToolResult {
30
+ content: HostToolContent[];
31
+ isError?: boolean;
32
+ }
33
+
34
+ /** Who calls, as only the engine knows it at the moment of the call. */
35
+ export interface HostToolCaller {
36
+ sessionId: string;
37
+ harness: AgentHarness;
38
+ /** The turn running when the call came: a call outside a turn is refused before the host sees it. */
39
+ turnId: string;
40
+ /** The mode the session runs in at the moment of the call, a change mid-turn included. */
41
+ permissionMode: PermissionMode;
42
+ }
43
+
44
+ /** A session's tools: one MCP server, named `name` on every harness. */
45
+ export interface HostToolSource {
46
+ name: string;
47
+ tools: readonly HostTool[];
48
+ /** Words for the model about the tools (MCP's `instructions`). */
49
+ instructions?: string;
50
+ /** How long one call may run, on every harness (30 minutes by default). */
51
+ timeoutMs?: number;
52
+ /** Run a tool. `signal` aborts when the agent gives the call up. A throw is the call's failure. */
53
+ call(
54
+ name: string,
55
+ args: Record<string, unknown>,
56
+ caller: HostToolCaller,
57
+ signal: AbortSignal,
58
+ ): Promise<HostToolResult>;
59
+ }
60
+
61
+ /** The host's tools for a session, asked once, at its first turn; none gives it none. */
62
+ export type HostTools = (session: {
63
+ sessionId: string;
64
+ cwd: string;
65
+ harness: AgentHarness;
66
+ }) => HostToolSource | undefined | Promise<HostToolSource | undefined>;
67
+
68
+ /** What the engine knows of a session's turn when a tool is called, and the turn's own cancel. */
69
+ export type LiveTurn = () =>
70
+ | (Pick<HostToolCaller, "turnId" | "permissionMode"> & { signal?: AbortSignal })
71
+ | undefined;
72
+
73
+ // @ref LLP 0018#timeouts — a tool may run as long as a question may wait
74
+ /** How long a host tool call may run unless its source says otherwise. */
75
+ export const HOST_TOOL_TIMEOUT_MS = 30 * 60_000;
76
+
77
+ /** The MCP versions answered, newest first: the official SDK's list (1.32), as `operator/mcp.ts`. */
78
+ const MCP_VERSIONS = ["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
79
+
80
+ type Id = string | number;
81
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
82
+ typeof value === "object" && value !== null && !Array.isArray(value);
83
+ const ok = (id: Id, result: unknown) => ({ jsonrpc: "2.0", id, result });
84
+ const fail = (id: Id | null, code: number, message: string) => ({
85
+ jsonrpc: "2.0",
86
+ id,
87
+ error: { code, message },
88
+ });
89
+ const failed = (text: string) => ({
90
+ content: [{ type: "text", text }] as unknown[],
91
+ isError: true as const,
92
+ });
93
+
94
+ /** Stop a call under way: the engine answers it `why`, then tells the tool through its signal. */
95
+ type Stop = (why: string) => void;
96
+
97
+ /** How one MCP client's messages are answered. */
98
+ interface Answering {
99
+ /** Who calls and the turn's own cancel, read at dispatch; none while no turn runs. */
100
+ caller: () => { caller: HostToolCaller; signal?: AbortSignal } | undefined;
101
+ /** The client's session entry still stands: a released one runs no call. */
102
+ alive: () => boolean;
103
+ /** Why a call may not run for this caller, when it may not. */
104
+ refuse?: (tool: HostTool, caller: HostToolCaller) => string | undefined;
105
+ /**
106
+ * The calls under way by request id, which `notifications/cancelled`
107
+ * stops: only for a client whose ids are its own (the in-process one).
108
+ * Over stateless HTTP two clients of a session can reuse an id, so a call
109
+ * there is stopped by its own request closing (`signal`).
110
+ */
111
+ calls?: Map<Id, Stop>;
112
+ /** Stops every call of this client: its request closed, its transport closed. */
113
+ signal?: AbortSignal;
114
+ /** Every call of the session under way, which its release stops. */
115
+ running: Set<Stop>;
116
+ }
117
+
118
+ /**
119
+ * Answer one MCP message for `source`: the tool methods only. Null for a
120
+ * notification or a response.
121
+ */
122
+ async function answer(
123
+ source: HostToolSource,
124
+ message: unknown,
125
+ answering: Answering,
126
+ ): Promise<unknown | null> {
127
+ if (!isRecord(message) || message.jsonrpc !== "2.0") return fail(null, -32600, "Invalid Request");
128
+ const { id, method } = message;
129
+ const params = isRecord(message.params) ? message.params : {};
130
+ if (typeof method !== "string") return null;
131
+ if (typeof id !== "string" && typeof id !== "number") {
132
+ if (method === "notifications/cancelled")
133
+ answering.calls?.get(params.requestId as Id)?.("the agent cancelled the call");
134
+ return null;
135
+ }
136
+ switch (method) {
137
+ case "initialize":
138
+ return ok(id, {
139
+ protocolVersion: MCP_VERSIONS.find((v) => v === params.protocolVersion) ?? MCP_VERSIONS[0],
140
+ capabilities: { tools: {} },
141
+ serverInfo: { name: source.name, version: "1" },
142
+ ...(source.instructions && { instructions: source.instructions }),
143
+ });
144
+ case "ping":
145
+ return ok(id, {});
146
+ case "tools/list":
147
+ return ok(id, { tools: source.tools.map(listed) });
148
+ case "tools/call": {
149
+ const tool = source.tools.find((each) => each.name === params.name);
150
+ if (!tool) return ok(id, failed(`No tool ${JSON.stringify(params.name)} on ${source.name}`));
151
+ // A client that already gave up is answered by no call.
152
+ if (answering.signal?.aborted) return null;
153
+ // @ref LLP 0018#the-api — a call of a released session does not run
154
+ if (!answering.alive()) return ok(id, failed(`${source.name} of this session was released`));
155
+ // @ref LLP 0018#the-api — a call names its turn, or does not run
156
+ const who = answering.caller();
157
+ if (!who)
158
+ return ok(
159
+ id,
160
+ failed(`${source.name} answers only during a turn of this session, and none is running`),
161
+ );
162
+ const refused = answering.refuse?.(tool, who.caller);
163
+ if (refused) return ok(id, failed(refused));
164
+ return ok(id, await run(source, tool, params.arguments, who, id, answering));
165
+ }
166
+ default:
167
+ return fail(id, -32601, `Method not found: ${method}`);
168
+ }
169
+ }
170
+
171
+ /** A tool as `tools/list` shows it: only the hints the host gave, so MCP's defaults hold for the rest. */
172
+ function listed({ name, description, inputSchema, annotations }: HostTool) {
173
+ const hints = {
174
+ ...(annotations?.readOnly !== undefined && { readOnlyHint: annotations.readOnly }),
175
+ ...(annotations?.destructive !== undefined && { destructiveHint: annotations.destructive }),
176
+ };
177
+ return {
178
+ name,
179
+ description,
180
+ inputSchema,
181
+ ...(Object.keys(hints).length && { annotations: hints }),
182
+ };
183
+ }
184
+
185
+ type CallResult = { content: unknown[]; isError?: true };
186
+
187
+ // @ref LLP 0018#timeouts — the engine holds the limit: an in-process call has none of its own
188
+ /**
189
+ * One call. It ends at whichever comes first: the tool's answer, its limit,
190
+ * its client closing, the turn's cancel, the session's release. The engine's
191
+ * outcome is settled before the tool's signal aborts, so a tool that answers
192
+ * from its abort handler cannot turn a cut call into a success, and every
193
+ * path clears the timer and the listeners.
194
+ */
195
+ function run(
196
+ source: HostToolSource,
197
+ tool: HostTool,
198
+ args: unknown,
199
+ who: { caller: HostToolCaller; signal?: AbortSignal },
200
+ id: Id,
201
+ { calls, signal, running }: Answering,
202
+ ): Promise<CallResult> {
203
+ const call = new AbortController();
204
+ const limit = timeoutOf(source);
205
+ return new Promise<CallResult>((resolve) => {
206
+ let settled = false;
207
+ const offs: Array<() => void> = [];
208
+ const settle = (result: CallResult) => {
209
+ if (settled) return false;
210
+ settled = true;
211
+ clearTimeout(timer);
212
+ for (const off of offs) off();
213
+ if (calls?.get(id) === stop) calls.delete(id);
214
+ running.delete(stop);
215
+ resolve(result);
216
+ return true;
217
+ };
218
+ const stop: Stop = (why) => {
219
+ if (settle(failed(why))) call.abort();
220
+ };
221
+ const timer = setTimeout(
222
+ () => stop(`${tool.name} did not answer within ${limit / 1000} s, its time limit`),
223
+ limit,
224
+ );
225
+ calls?.set(id, stop);
226
+ running.add(stop);
227
+ offs.push(onAbort(signal, () => stop("the agent gave the call up")));
228
+ offs.push(onAbort(who.signal, () => stop("the turn was cancelled")));
229
+ // A call already ended (its client or turn gone) never reaches the host:
230
+ // checked here, and the host is asked at once, with no tick between.
231
+ if (settled) return;
232
+ const given = isRecord(args) ? args : {};
233
+ const fault = (error: unknown) => settle(failed(describe(error)));
234
+ let answered: Promise<HostToolResult>;
235
+ try {
236
+ answered = Promise.resolve(source.call(tool.name, given, who.caller, call.signal));
237
+ } catch (error) {
238
+ fault(error);
239
+ return;
240
+ }
241
+ answered.then((result) => settle(asResult(tool, result)), fault).catch(fault);
242
+ });
243
+ }
244
+
245
+ /** A host's answer as MCP takes it; one not of the declared shape is the tool's failure. */
246
+ function asResult(tool: HostTool, result: unknown): CallResult {
247
+ if (!isRecord(result) || !Array.isArray(result.content))
248
+ return failed(
249
+ `${tool.name} answered with no content (a host tool's result is { content: [...] })`,
250
+ );
251
+ return { content: result.content, ...(result.isError === true && { isError: true as const }) };
252
+ }
253
+
254
+ /** The MCP transport the Claude Agent SDK hands an in-process server (`connect`). */
255
+ interface SdkTransport {
256
+ onmessage?: (message: unknown) => void;
257
+ onclose?: () => void;
258
+ send(message: unknown): Promise<void>;
259
+ start(): Promise<void>;
260
+ }
261
+
262
+ /** The header that carries a session's secret: never its URL, which Codex logs (LLP 0018). */
263
+ const SECRET_HEADER = "authorization";
264
+
265
+ /** The hosts a harness process must reach directly, never through a proxy (`NO_PROXY`). */
266
+ export const LOOPBACK_HOSTS = ["127.0.0.1", "localhost"];
267
+
268
+ export interface HostToolSessionsOptions {
269
+ /** The session's turn now, for a call over HTTP. */
270
+ live?: (sessionId: string) => ReturnType<LiveTurn>;
271
+ /**
272
+ * The harness cannot be relied on to ask the person before a tool that
273
+ * changes something (an ACP agent): such a tool runs only with full access.
274
+ */
275
+ writesNeedFullAccess?: boolean;
276
+ }
277
+
278
+ /** A session's own entry: its source, asked once, and what serving it holds. */
279
+ interface Entry {
280
+ source: Promise<HostToolSource | undefined>;
281
+ /** The source, once it resolved while this entry was still the session's. */
282
+ resolved?: HostToolSource;
283
+ secret?: string;
284
+ running: Set<Stop>;
285
+ }
286
+
287
+ /** A session's source, bound to the entry it came from: its HTTP server is that entry's or none. */
288
+ export interface HostLease {
289
+ source: HostToolSource;
290
+ /**
291
+ * The session's server on the engine's loopback, as a turn names it: the
292
+ * same URL and secret for the session's life, so a Codex thread's config
293
+ * does not change between its turns. A loopback that cannot start is the
294
+ * server's `mcp_unavailable`; a session released meanwhile gets nothing.
295
+ */
296
+ http(): Promise<McpServerConfig>;
297
+ }
298
+
299
+ /**
300
+ * A harness's host tools: each session's source, asked once; for Claude an
301
+ * in-process server, for an agent that reaches it over HTTP the engine's own
302
+ * loopback endpoint, which knows a session by the secret its config carries.
303
+ */
304
+ export class HostToolSessions {
305
+ private readonly entries = new Map<string, Entry>();
306
+ private readonly bySecret = new Map<string, string>();
307
+ private loopback?: Promise<Loopback>;
308
+ private closed = false;
309
+
310
+ constructor(
311
+ private readonly hostTools: HostTools,
312
+ private readonly harness: AgentHarness,
313
+ private readonly options: HostToolSessionsOptions = {},
314
+ ) {}
315
+
316
+ /** The session's source: asked at its first turn, the same one after. */
317
+ source(sessionId: string, cwd: string): Promise<HostToolSource | undefined> {
318
+ return this.entry(sessionId, cwd)?.source ?? Promise.resolve(undefined);
319
+ }
320
+
321
+ // @ref LLP 0018#the-api — setup carries the exact entry it began with
322
+ /** The session's source and its HTTP server, both bound to the entry asked now. */
323
+ async lease(sessionId: string, cwd: string): Promise<HostLease | undefined> {
324
+ const entry = this.entry(sessionId, cwd);
325
+ const source = await entry?.source;
326
+ if (!entry || !source || this.entries.get(sessionId) !== entry) return undefined;
327
+ return { source, http: () => this.http(sessionId, entry, source) };
328
+ }
329
+
330
+ private entry(sessionId: string, cwd: string): Entry | undefined {
331
+ if (this.closed) return undefined;
332
+ const existing = this.entries.get(sessionId);
333
+ if (existing) return existing;
334
+ const entry: Entry = {
335
+ source: Promise.resolve(this.hostTools({ sessionId, cwd, harness: this.harness })),
336
+ running: new Set(),
337
+ };
338
+ this.entries.set(sessionId, entry);
339
+ // @ref LLP 0018#the-api — a late answer belongs to its own entry, never a successor's
340
+ entry.source.then(
341
+ (source) => {
342
+ if (this.entries.get(sessionId) === entry) entry.resolved = source;
343
+ },
344
+ // A source that failed is asked again by the next turn.
345
+ () => {
346
+ if (this.entries.get(sessionId) === entry) this.entries.delete(sessionId);
347
+ },
348
+ );
349
+ return entry;
350
+ }
351
+
352
+ /** Claude's in-process server for the session's source, its caller read from `live` at each call. */
353
+ inProcess(sessionId: string, source: HostToolSource, live: LiveTurn) {
354
+ const entry = this.entries.get(sessionId);
355
+ const answering: Answering = {
356
+ caller: () => this.caller(sessionId, live),
357
+ alive: () => entry !== undefined && this.entries.get(sessionId) === entry,
358
+ refuse: (tool, caller) => this.refuse(tool, caller),
359
+ calls: new Map(),
360
+ running: entry?.running ?? new Set(),
361
+ };
362
+ const instance = {
363
+ async connect(transport: SdkTransport) {
364
+ // The transport closed: its calls stop, and nothing more is sent on it.
365
+ const closed = new AbortController();
366
+ answering.signal = closed.signal;
367
+ transport.onclose = () => closed.abort();
368
+ transport.onmessage = (message) =>
369
+ void answer(source, message, answering)
370
+ .then((reply) => {
371
+ if (reply !== null && !closed.signal.aborted) return transport.send(reply);
372
+ })
373
+ .catch(() => {});
374
+ await transport.start();
375
+ },
376
+ };
377
+ return { type: "sdk" as const, name: source.name, timeout: timeoutOf(source), instance };
378
+ }
379
+
380
+ private async http(
381
+ sessionId: string,
382
+ entry: Entry,
383
+ source: HostToolSource,
384
+ ): Promise<McpServerConfig> {
385
+ const owner = () => {
386
+ if (this.closed || this.entries.get(sessionId) !== entry || entry.resolved !== source)
387
+ throw new Error(`the host's tools of session ${sessionId} were released`);
388
+ };
389
+ owner();
390
+ this.loopback ??= serveLoopback((request) => this.serve(request));
391
+ const starting = this.loopback;
392
+ let url: string;
393
+ try {
394
+ ({ url } = await starting);
395
+ } catch (error) {
396
+ if (this.loopback === starting) this.loopback = undefined;
397
+ const cause = describe(error);
398
+ throw new McpUnavailableError({
399
+ [source.name]: `the engine's loopback did not start: ${cause}`,
400
+ });
401
+ }
402
+ owner();
403
+ if (!entry.secret) {
404
+ entry.secret = randomBytes(32).toString("base64url");
405
+ this.bySecret.set(entry.secret, sessionId);
406
+ }
407
+ return {
408
+ type: "http",
409
+ url: `${url}/host-tools`,
410
+ headers: { [SECRET_HEADER]: `Bearer ${entry.secret}` },
411
+ timeoutMs: timeoutOf(source),
412
+ };
413
+ }
414
+
415
+ /** The session's secret, when it has one: no text the engine lets out may hold it. */
416
+ secretOf(sessionId: string): string | undefined {
417
+ return this.entries.get(sessionId)?.secret;
418
+ }
419
+
420
+ /** Forget the session: its source, its calls, and its secret, which answers no more. */
421
+ release(sessionId: string): void {
422
+ const entry = this.entries.get(sessionId);
423
+ if (!entry) return;
424
+ this.entries.delete(sessionId);
425
+ if (entry.secret) this.bySecret.delete(entry.secret);
426
+ for (const stop of [...entry.running]) stop("the session was released");
427
+ }
428
+
429
+ async close(): Promise<void> {
430
+ this.closed = true;
431
+ for (const sessionId of [...this.entries.keys()]) this.release(sessionId);
432
+ const loopback = this.loopback;
433
+ this.loopback = undefined;
434
+ await (await loopback?.catch(() => undefined))?.close();
435
+ }
436
+
437
+ private caller(
438
+ sessionId: string,
439
+ live: LiveTurn,
440
+ ): { caller: HostToolCaller; signal?: AbortSignal } | undefined {
441
+ const turn = live();
442
+ if (!turn) return undefined;
443
+ const { signal, turnId, permissionMode } = turn;
444
+ return { caller: { sessionId, harness: this.harness, turnId, permissionMode }, signal };
445
+ }
446
+
447
+ // @ref LLP 0018#permissions — an ACP agent's writes run only with full access
448
+ private refuse(tool: HostTool, caller: HostToolCaller): string | undefined {
449
+ if (!this.options.writesNeedFullAccess || tool.annotations?.readOnly) return undefined;
450
+ if (caller.permissionMode === "bypass_permissions") return undefined;
451
+ return `${tool.name} changes something, and this agent cannot ask the person first: it runs only when the session has full access (bypass_permissions)`;
452
+ }
453
+
454
+ /** The session a request's bearer names, and its entry, when both still stand. */
455
+ private bearer(request: Request): { sessionId: string; entry: Entry } | undefined {
456
+ const given = /^Bearer (.+)$/i.exec(request.headers.get(SECRET_HEADER) ?? "")?.[1];
457
+ const sessionId = given === undefined ? undefined : this.bySecret.get(given);
458
+ const entry = sessionId === undefined ? undefined : this.entries.get(sessionId);
459
+ return sessionId !== undefined && entry?.resolved && entry.secret === given
460
+ ? { sessionId, entry }
461
+ : undefined;
462
+ }
463
+
464
+ /** One MCP POST: a secret of no session's, or none, is refused; never a 401, which starts OAuth. */
465
+ private async serve(request: Request): Promise<Response> {
466
+ const before = this.bearer(request);
467
+ if (!before) return new Response("Forbidden", { status: 403 });
468
+ if (new URL(request.url).pathname !== "/host-tools" || request.method !== "POST")
469
+ return new Response(null, { status: 405, headers: { Allow: "POST" } });
470
+ let message: unknown;
471
+ try {
472
+ message = await request.json();
473
+ } catch {
474
+ return Response.json(fail(null, -32700, "Parse error"), { status: 400 });
475
+ }
476
+ // @ref LLP 0018#codex — the bearer still names the same session and source once the body is read
477
+ const now = this.bearer(request);
478
+ if (now?.entry !== before.entry) return new Response("Forbidden", { status: 403 });
479
+ const { sessionId, entry } = now;
480
+ const source = entry.resolved as HostToolSource;
481
+ const reply = await answer(source, message, {
482
+ caller: () => this.caller(sessionId, () => this.options.live?.(sessionId)),
483
+ alive: () => this.entries.get(sessionId) === entry,
484
+ refuse: (tool, caller) => this.refuse(tool, caller),
485
+ signal: request.signal,
486
+ running: entry.running,
487
+ });
488
+ return reply === null ? new Response(null, { status: 202 }) : Response.json(reply);
489
+ }
490
+ }
491
+
492
+ /** A harness's host tools, when the operator gives any. */
493
+ export function hostToolSessions(
494
+ hostTools: HostTools | undefined,
495
+ harness: AgentHarness,
496
+ options?: HostToolSessionsOptions,
497
+ ): HostToolSessions | undefined {
498
+ return hostTools && new HostToolSessions(hostTools, harness, options);
499
+ }
500
+
501
+ // @ref LLP 0018#timeouts — the wire's own cap: a larger delay is a 1 ms timer on Node
502
+ /** A source's limit when the wire would take it (a positive whole number of ms, at most a timer's limit), else the default. */
503
+ function timeoutOf(source: HostToolSource): number {
504
+ const limit = source.timeoutMs;
505
+ const valid =
506
+ limit !== undefined && Number.isInteger(limit) && limit > 0 && limit <= MAX_REQUEST_TIMEOUT_MS;
507
+ return valid ? limit : HOST_TOOL_TIMEOUT_MS;
508
+ }
509
+
510
+ /** A turn's own server may not take the host tools' name: neither harness would say whose it is. */
511
+ export function refuseHostName(
512
+ servers: Readonly<Record<string, unknown>> | undefined,
513
+ name: string,
514
+ ): void {
515
+ if (servers?.[name] !== undefined)
516
+ throw new InvalidRequestError([
517
+ { path: `mcpServers.${name}`, message: "the host's own tools have this name" },
518
+ ]);
519
+ }
520
+
521
+ /** The variables that name a proxy, in both spellings. */
522
+ const PROXY_VARIABLES = ["HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY"].flatMap((name) => [
523
+ name,
524
+ name.toLowerCase(),
525
+ ]);
526
+
527
+ // @ref LLP 0018#codex — the loopback reached directly, and a bare `*` left exactly as it is
528
+ /**
529
+ * The environment `env` changes to for the loopback to be reached directly,
530
+ * each value `""` for a variable to leave out:
531
+ * - each of `NO_PROXY` and `no_proxy` that is set gets the loopback hosts
532
+ * added to its own list (a tool may read either, and the two may differ);
533
+ * with neither set, both name the loopback;
534
+ * - one whose value is exactly `*` (no proxy for anything) is left as it is,
535
+ * since a client may honour `*` only as the whole value (Codex 0.169.1 sent
536
+ * its model's traffic through the proxy once it read `*,127.0.0.1`); when
537
+ * the value a client reads (`NO_PROXY`, else `no_proxy`) is exactly `*`, the
538
+ * proxy variables are left out instead: Codex's MCP client (hyper-util
539
+ * 0.1.20) checks an IP address only against IP entries, so `*` alone left
540
+ * 127.0.0.1 to the proxy, and with `*` the person asked for no proxy at all.
541
+ * A `*` inside a longer list is extended like any other list.
542
+ */
543
+ export function loopbackDirect(env: Record<string, string | undefined>): Record<string, string> {
544
+ const names = (["NO_PROXY", "no_proxy"] as const).filter((name) => env[name] !== undefined);
545
+ if (!names.length)
546
+ return { NO_PROXY: LOOPBACK_HOSTS.join(","), no_proxy: LOOPBACK_HOSTS.join(",") };
547
+ const lists = names.map((name) => {
548
+ const list = (env[name] as string)
549
+ .split(",")
550
+ .map((host) => host.trim())
551
+ .filter(Boolean);
552
+ return [name, list] as const;
553
+ });
554
+ // The value a client reads: `NO_PROXY`, else `no_proxy` (hyper-util's order).
555
+ const effective = (env.NO_PROXY ?? env.no_proxy ?? "").trim();
556
+ const bare = ([, list]: (typeof lists)[number]) => list.length === 1 && list[0] === "*";
557
+ return Object.fromEntries([
558
+ ...(effective === "*"
559
+ ? PROXY_VARIABLES.filter((name) => env[name] !== undefined).map((name) => [name, ""])
560
+ : []),
561
+ ...lists
562
+ .filter((entry) => !bare(entry))
563
+ .map(([name, list]) => [
564
+ name,
565
+ [...list, ...LOOPBACK_HOSTS.filter((host) => !list.includes(host))].join(","),
566
+ ]),
567
+ ]);
568
+ }
569
+
570
+ /** An error's words, for a call's failure: never a throw of its own. */
571
+ function describe(error: unknown): string {
572
+ try {
573
+ return error instanceof Error ? String(error.message) : String(error);
574
+ } catch {
575
+ return "the tool failed, and its error could not be read";
576
+ }
577
+ }
578
+
579
+ /** `env` with the loopback reached directly: a variable left out is gone, not empty. */
580
+ export function withLoopbackDirect(
581
+ env: Record<string, string | undefined>,
582
+ ): Record<string, string | undefined> {
583
+ const changes = loopbackDirect(env);
584
+ const out = { ...env, ...changes };
585
+ for (const [name, value] of Object.entries(changes)) if (value === "") delete out[name];
586
+ return out;
587
+ }
588
+
589
+ // @ref LLP 0018#who-can-read-the-secret — no serialising; a copy only of an event that holds it
590
+ /**
591
+ * `value` with `secret` replaced by `[redacted]` in every string, key and
592
+ * value alike, at any depth. A first pass looks for it without copying, so
593
+ * an event that does not hold it is returned as it is. One that does is
594
+ * copied whole (arrays and plain objects; strings are shared), each object
595
+ * once, so two fields sharing an object share its copy and a cycle stays a
596
+ * cycle in the copy. An error is changed in place: its message, stack,
597
+ * cause and every own field (`data`). Other objects are left as they are.
598
+ */
599
+ export function withoutSecret<T>(value: T, secret: string | undefined): T {
600
+ if (!secret) return value;
601
+ const plain = (each: object) =>
602
+ Array.isArray(each) ||
603
+ Object.getPrototypeOf(each) === Object.prototype ||
604
+ Object.getPrototypeOf(each) === null;
605
+ const fieldsOf = (error: Error) => ["message", "stack", "cause", ...Object.keys(error)];
606
+ const seen = new Set<object>();
607
+ const holds = (each: unknown): boolean => {
608
+ if (typeof each === "string") return each.includes(secret);
609
+ if (typeof each !== "object" || each === null || seen.has(each)) return false;
610
+ seen.add(each);
611
+ const fields = each as Record<string, unknown>;
612
+ if (each instanceof Error) return fieldsOf(each).some((key) => holds(fields[key]));
613
+ if (!plain(each)) return false;
614
+ return Object.entries(fields).some(([key, field]) => key.includes(secret) || holds(field));
615
+ };
616
+ if (!holds(value)) return value;
617
+ const copies = new Map<object, unknown>();
618
+ const copy = (each: unknown): unknown => {
619
+ if (typeof each === "string") return each.replaceAll(secret, "[redacted]");
620
+ if (typeof each !== "object" || each === null) return each;
621
+ if (copies.has(each)) return copies.get(each);
622
+ if (each instanceof Error) {
623
+ copies.set(each, each);
624
+ const fields = each as unknown as Record<string, unknown>;
625
+ for (const key of fieldsOf(each))
626
+ if (fields[key] !== undefined) fields[key] = copy(fields[key]);
627
+ return each;
628
+ }
629
+ if (!plain(each)) return each;
630
+ if (Array.isArray(each)) {
631
+ const out: unknown[] = [];
632
+ copies.set(each, out);
633
+ for (const item of each) out.push(copy(item));
634
+ return out;
635
+ }
636
+ const out: Record<string, unknown> = Object.create(Object.getPrototypeOf(each));
637
+ copies.set(each, out);
638
+ // Own data properties: a JSON `__proto__` key assigned would set the copy's prototype.
639
+ for (const [key, field] of Object.entries(each))
640
+ Object.defineProperty(out, copy(key) as string, {
641
+ value: copy(field),
642
+ enumerable: true,
643
+ writable: true,
644
+ configurable: true,
645
+ });
646
+ return out;
647
+ };
648
+ return copy(value) as T;
649
+ }
@@ -14,9 +14,21 @@ function mcpServerRequired(server: McpServerConfig | undefined): boolean {
14
14
  return server?.required !== false;
15
15
  }
16
16
 
17
- /** The server as its harness takes it: whether a turn needs it is the engine's rule. */
18
- export function nativeMcpServer(server: McpServerConfig): McpServerConfig {
19
- const { required: _required, ...native } = server;
17
+ /** Each kind of server without the fields that are the engine's own. */
18
+ type WithoutEngineFields<Server> = Server extends unknown
19
+ ? Omit<Server, "required" | "timeoutMs">
20
+ : never;
21
+
22
+ /** A server without the fields that are the engine's own, which no harness takes as they are. */
23
+ export type NativeMcpServer = WithoutEngineFields<McpServerConfig>;
24
+
25
+ /**
26
+ * The server as a harness takes it: whether a turn needs it is the engine's
27
+ * rule, and how long a tool call may run each harness says in its own way
28
+ * (Claude's `timeout`, Codex's `tool_timeout_sec`), if at all.
29
+ */
30
+ export function nativeMcpServer(server: McpServerConfig): NativeMcpServer {
31
+ const { required: _required, timeoutMs: _timeoutMs, ...native } = server;
20
32
  return native;
21
33
  }
22
34