@balchemyai/agent-sdk 0.3.10 → 0.4.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.
Files changed (142) hide show
  1. package/CHANGELOG.md +51 -0
  2. package/LICENSE +21 -0
  3. package/README.md +160 -6
  4. package/dist/agent-loop/agent-loop.d.ts +19 -8
  5. package/dist/agent-loop/agent-loop.d.ts.map +1 -1
  6. package/dist/agent-loop/agent-loop.js +620 -120
  7. package/dist/agent-loop/agent-loop.js.map +1 -1
  8. package/dist/agent-loop/decision-handler.d.ts.map +1 -1
  9. package/dist/agent-loop/decision-handler.js +64 -3
  10. package/dist/agent-loop/decision-handler.js.map +1 -1
  11. package/dist/agent-loop/llm-adapters/anthropic.d.ts +4 -3
  12. package/dist/agent-loop/llm-adapters/anthropic.d.ts.map +1 -1
  13. package/dist/agent-loop/llm-adapters/anthropic.js +79 -40
  14. package/dist/agent-loop/llm-adapters/anthropic.js.map +1 -1
  15. package/dist/agent-loop/llm-adapters/openai.d.ts +4 -3
  16. package/dist/agent-loop/llm-adapters/openai.d.ts.map +1 -1
  17. package/dist/agent-loop/llm-adapters/openai.js +91 -36
  18. package/dist/agent-loop/llm-adapters/openai.js.map +1 -1
  19. package/dist/agent-loop/llm-adapters/transport.d.ts +5 -0
  20. package/dist/agent-loop/llm-adapters/transport.d.ts.map +1 -0
  21. package/dist/agent-loop/llm-adapters/transport.js +63 -0
  22. package/dist/agent-loop/llm-adapters/transport.js.map +1 -0
  23. package/dist/agent-loop/llm-cost-tracker.d.ts +4 -0
  24. package/dist/agent-loop/llm-cost-tracker.d.ts.map +1 -1
  25. package/dist/agent-loop/llm-cost-tracker.js +37 -5
  26. package/dist/agent-loop/llm-cost-tracker.js.map +1 -1
  27. package/dist/agent-loop/rule-checker.d.ts +1 -20
  28. package/dist/agent-loop/rule-checker.d.ts.map +1 -1
  29. package/dist/agent-loop/rule-checker.js +0 -2
  30. package/dist/agent-loop/rule-checker.js.map +1 -1
  31. package/dist/agent-loop/telemetry-reporter.d.ts +8 -14
  32. package/dist/agent-loop/telemetry-reporter.d.ts.map +1 -1
  33. package/dist/agent-loop/telemetry-reporter.js +74 -8
  34. package/dist/agent-loop/telemetry-reporter.js.map +1 -1
  35. package/dist/agent-loop/types.d.ts +25 -9
  36. package/dist/agent-loop/types.d.ts.map +1 -1
  37. package/dist/agent-loop/types.js +0 -7
  38. package/dist/agent-loop/types.js.map +1 -1
  39. package/dist/agent-loop/webhook-receiver.d.ts +21 -2
  40. package/dist/agent-loop/webhook-receiver.d.ts.map +1 -1
  41. package/dist/agent-loop/webhook-receiver.js +196 -33
  42. package/dist/agent-loop/webhook-receiver.js.map +1 -1
  43. package/dist/auth/onboarding.d.ts.map +1 -1
  44. package/dist/auth/onboarding.js +15 -0
  45. package/dist/auth/onboarding.js.map +1 -1
  46. package/dist/client/http-client.d.ts +4 -2
  47. package/dist/client/http-client.d.ts.map +1 -1
  48. package/dist/client/http-client.js +88 -16
  49. package/dist/client/http-client.js.map +1 -1
  50. package/dist/errors/agent-sdk-error.d.ts +6 -0
  51. package/dist/errors/agent-sdk-error.d.ts.map +1 -1
  52. package/dist/errors/agent-sdk-error.js +16 -0
  53. package/dist/errors/agent-sdk-error.js.map +1 -1
  54. package/dist/errors/failure-metadata.d.ts +19 -0
  55. package/dist/errors/failure-metadata.d.ts.map +1 -0
  56. package/dist/errors/failure-metadata.js +177 -0
  57. package/dist/errors/failure-metadata.js.map +1 -0
  58. package/dist/index.d.ts +35 -10
  59. package/dist/index.d.ts.map +1 -1
  60. package/dist/index.js +130 -15
  61. package/dist/index.js.map +1 -1
  62. package/dist/local-runner/assessment-client.d.ts +111 -0
  63. package/dist/local-runner/assessment-client.d.ts.map +1 -0
  64. package/dist/local-runner/assessment-client.js +417 -0
  65. package/dist/local-runner/assessment-client.js.map +1 -0
  66. package/dist/local-runner/control-client.d.ts +126 -0
  67. package/dist/local-runner/control-client.d.ts.map +1 -0
  68. package/dist/local-runner/control-client.js +370 -0
  69. package/dist/local-runner/control-client.js.map +1 -0
  70. package/dist/local-runner/execution-build-client.d.ts +184 -0
  71. package/dist/local-runner/execution-build-client.d.ts.map +1 -0
  72. package/dist/local-runner/execution-build-client.js +389 -0
  73. package/dist/local-runner/execution-build-client.js.map +1 -0
  74. package/dist/local-runner/execution-submit-client.d.ts +126 -0
  75. package/dist/local-runner/execution-submit-client.d.ts.map +1 -0
  76. package/dist/local-runner/execution-submit-client.js +287 -0
  77. package/dist/local-runner/execution-submit-client.js.map +1 -0
  78. package/dist/local-runner/llm-client.d.ts +20 -0
  79. package/dist/local-runner/llm-client.d.ts.map +1 -0
  80. package/dist/local-runner/llm-client.js +23 -0
  81. package/dist/local-runner/llm-client.js.map +1 -0
  82. package/dist/local-runner/owner-positions.d.ts +32 -0
  83. package/dist/local-runner/owner-positions.d.ts.map +1 -0
  84. package/dist/local-runner/owner-positions.js +89 -0
  85. package/dist/local-runner/owner-positions.js.map +1 -0
  86. package/dist/local-runner/pairing-client.d.ts +95 -0
  87. package/dist/local-runner/pairing-client.d.ts.map +1 -0
  88. package/dist/local-runner/pairing-client.js +186 -0
  89. package/dist/local-runner/pairing-client.js.map +1 -0
  90. package/dist/local-runner/research-client.d.ts +98 -0
  91. package/dist/local-runner/research-client.d.ts.map +1 -0
  92. package/dist/local-runner/research-client.js +344 -0
  93. package/dist/local-runner/research-client.js.map +1 -0
  94. package/dist/local-runner/runner-proof-transport.d.ts +55 -0
  95. package/dist/local-runner/runner-proof-transport.d.ts.map +1 -0
  96. package/dist/local-runner/runner-proof-transport.js +258 -0
  97. package/dist/local-runner/runner-proof-transport.js.map +1 -0
  98. package/dist/local-runner/runtime-client.d.ts +122 -0
  99. package/dist/local-runner/runtime-client.d.ts.map +1 -0
  100. package/dist/local-runner/runtime-client.js +265 -0
  101. package/dist/local-runner/runtime-client.js.map +1 -0
  102. package/dist/local-runner/sell-assessment-client.d.ts +113 -0
  103. package/dist/local-runner/sell-assessment-client.d.ts.map +1 -0
  104. package/dist/local-runner/sell-assessment-client.js +225 -0
  105. package/dist/local-runner/sell-assessment-client.js.map +1 -0
  106. package/dist/local-runner/signals-client.d.ts +91 -0
  107. package/dist/local-runner/signals-client.d.ts.map +1 -0
  108. package/dist/local-runner/signals-client.js +357 -0
  109. package/dist/local-runner/signals-client.js.map +1 -0
  110. package/dist/local-runner/solana-platform-account.d.ts +5 -0
  111. package/dist/local-runner/solana-platform-account.d.ts.map +1 -0
  112. package/dist/local-runner/solana-platform-account.js +66 -0
  113. package/dist/local-runner/solana-platform-account.js.map +1 -0
  114. package/dist/local-runner/trading-wallet-client.d.ts +67 -0
  115. package/dist/local-runner/trading-wallet-client.d.ts.map +1 -0
  116. package/dist/local-runner/trading-wallet-client.js +144 -0
  117. package/dist/local-runner/trading-wallet-client.js.map +1 -0
  118. package/dist/mcp/mcp-client.d.ts +31 -4
  119. package/dist/mcp/mcp-client.d.ts.map +1 -1
  120. package/dist/mcp/mcp-client.js +491 -83
  121. package/dist/mcp/mcp-client.js.map +1 -1
  122. package/dist/streaming/sse-event-stream.d.ts +14 -0
  123. package/dist/streaming/sse-event-stream.d.ts.map +1 -1
  124. package/dist/streaming/sse-event-stream.js +153 -13
  125. package/dist/streaming/sse-event-stream.js.map +1 -1
  126. package/dist/types.d.ts +11 -2
  127. package/dist/types.d.ts.map +1 -1
  128. package/dist/utils/package-version.d.ts +2 -0
  129. package/dist/utils/package-version.d.ts.map +1 -0
  130. package/dist/utils/package-version.js +54 -0
  131. package/dist/utils/package-version.js.map +1 -0
  132. package/dist/utils/redaction.d.ts +4 -0
  133. package/dist/utils/redaction.d.ts.map +1 -1
  134. package/dist/utils/redaction.js +54 -0
  135. package/dist/utils/redaction.js.map +1 -1
  136. package/dist/utils/retry.d.ts +22 -13
  137. package/dist/utils/retry.d.ts.map +1 -1
  138. package/dist/utils/retry.js +76 -50
  139. package/dist/utils/retry.js.map +1 -1
  140. package/docs/DEPLOYMENT.md +1 -1
  141. package/docs/error-retry-strategy.md +16 -6
  142. package/package.json +9 -9
@@ -5,7 +5,12 @@ exports.getToolText = getToolText;
5
5
  exports.parseToolJson = parseToolJson;
6
6
  exports.isToolError = isToolError;
7
7
  const agent_sdk_error_1 = require("../errors/agent-sdk-error");
8
+ const failure_metadata_1 = require("../errors/failure-metadata");
9
+ const redaction_1 = require("../utils/redaction");
8
10
  const retry_1 = require("../utils/retry");
11
+ const MAX_MCP_RESPONSE_BYTES = 1024 * 1024;
12
+ const MAX_MCP_REQUEST_BYTES = 512 * 1024;
13
+ const MAX_BATCH_CALLS = 50;
9
14
  // ── Typed tool call helpers ───────────────────────────────────────────────────
10
15
  /** Extract typed text from a tool call response. Returns empty string on error. */
11
16
  function getToolText(response) {
@@ -33,21 +38,85 @@ class BalchemyMcpClient {
33
38
  timeoutMs;
34
39
  fetchFn;
35
40
  retryOptions;
41
+ publicId;
42
+ toolCatalog = null;
43
+ toolCatalogPromise = null;
36
44
  constructor(config) {
37
- this.endpoint = config.endpoint;
45
+ const endpoint = new URL(config.endpoint);
46
+ if ((endpoint.protocol !== "https:" && endpoint.protocol !== "http:")
47
+ || endpoint.username
48
+ || endpoint.password
49
+ || endpoint.search
50
+ || endpoint.hash) {
51
+ throw new Error("MCP endpoint must not contain credentials, query parameters, or fragments");
52
+ }
53
+ if (!Number.isSafeInteger(config.timeoutMs ?? 15_000) || (config.timeoutMs ?? 15_000) <= 0) {
54
+ throw new Error("MCP timeoutMs must be a positive safe integer");
55
+ }
56
+ const segments = endpoint.pathname.split('/').filter(Boolean);
57
+ if (segments.length < 2 || segments[segments.length - 2] !== 'mcp') {
58
+ throw new Error("MCP endpoint must end with /mcp/{publicId}");
59
+ }
60
+ const publicId = segments[segments.length - 1] ?? '';
61
+ if (!/^[A-Za-z0-9._:-]{1,160}$/.test(publicId)) {
62
+ throw new Error("MCP endpoint publicId is invalid");
63
+ }
64
+ if (typeof config.apiKey !== 'string' || config.apiKey.length === 0 || config.apiKey.length > 4_096) {
65
+ throw new Error("MCP apiKey is invalid");
66
+ }
67
+ this.endpoint = endpoint.toString().replace(/\/+$/, '');
38
68
  this.apiKey = config.apiKey;
69
+ this.publicId = publicId;
39
70
  this.timeoutMs = config.timeoutMs ?? 15_000;
40
71
  this.fetchFn = config.fetchFn ?? fetch;
41
72
  this.retryOptions = config.retry ?? { maxAttempts: 3 };
42
73
  }
43
74
  async listTools() {
44
- return this.rpc("tools/list", {});
75
+ const response = await this.rpc("tools/list", {});
76
+ const tools = typeof response === 'object' && response !== null && !Array.isArray(response)
77
+ ? response.tools
78
+ : undefined;
79
+ this.toolCatalog = this.buildToolCatalog(tools);
80
+ return { tools: Array.from(this.toolCatalog.values()) };
45
81
  }
46
- async callTool(name, argumentsPayload) {
47
- return this.rpc("tools/call", {
82
+ async callTool(name, argumentsPayload, options = {}) {
83
+ const tool = await this.resolveExposedTool(name);
84
+ const readOnly = this.isReadOnlyNonRawTool(tool);
85
+ if (options.stepUpToken !== undefined && (tool["x-balchemy-safety"] !== "manage_step_up"
86
+ || typeof options.stepUpToken !== "string"
87
+ || !/^[\x21-\x7e]{1,4096}$/.test(options.stepUpToken))) {
88
+ throw new agent_sdk_error_1.AgentSdkError({
89
+ code: "policy_error",
90
+ message: "Step-up proof must be a bounded header value for a manage tool call",
91
+ details: { code: "MCP_STEP_UP_INPUT_INVALID", retryable: false },
92
+ });
93
+ }
94
+ if (!readOnly) {
95
+ const idempotencyKey = argumentsPayload.idempotency_key;
96
+ if (typeof idempotencyKey !== 'string' || !/^[A-Za-z0-9._:-]{1,128}$/.test(idempotencyKey)) {
97
+ throw new agent_sdk_error_1.AgentSdkError({
98
+ code: "policy_error",
99
+ message: `Protected tool "${name}" requires a bounded idempotency_key`,
100
+ details: { code: "MCP_IDEMPOTENCY_KEY_REQUIRED", reason: "MCP_IDEMPOTENCY_KEY_REQUIRED", tool: name },
101
+ });
102
+ }
103
+ }
104
+ const headers = readOnly
105
+ ? undefined
106
+ : {
107
+ ...this.createReplayHeaders(),
108
+ ...(options.stepUpToken !== undefined
109
+ ? { "x-balchemy-step-up": options.stepUpToken }
110
+ : {}),
111
+ };
112
+ const response = await this.rpc("tools/call", {
48
113
  name,
49
114
  arguments: argumentsPayload,
115
+ }, {
116
+ headers,
117
+ retryPolicy: readOnly ? "read" : "protected",
50
118
  });
119
+ return this.validateCallToolResponse(response);
51
120
  }
52
121
  /**
53
122
  * Lightweight health check using the `/health` endpoint.
@@ -75,9 +144,12 @@ class BalchemyMcpClient {
75
144
  * Throws `AgentSdkError` if unauthorized or not found.
76
145
  */
77
146
  async healthCheck() {
147
+ return (0, retry_1.withRetry)((attempt) => this.requestHealth(attempt.remainingDeadlineMs), { kind: "read", operation: "mcp:health" }, this.retryOptions);
148
+ }
149
+ async requestHealth(remainingDeadlineMs) {
78
150
  const healthUrl = `${this.endpoint}/health`;
79
151
  const controller = new AbortController();
80
- const timeout = globalThis.setTimeout(() => controller.abort(), this.timeoutMs);
152
+ const timeout = globalThis.setTimeout(() => controller.abort(), Math.max(1, Math.min(this.timeoutMs, remainingDeadlineMs)));
81
153
  try {
82
154
  const response = await this.fetchFn(healthUrl, {
83
155
  method: "GET",
@@ -87,7 +159,7 @@ class BalchemyMcpClient {
87
159
  },
88
160
  signal: controller.signal,
89
161
  });
90
- const raw = await response.text();
162
+ const raw = await (0, redaction_1.readBoundedResponseText)(response, MAX_MCP_RESPONSE_BYTES);
91
163
  if (!response.ok) {
92
164
  let message = `MCP health check failed with status ${response.status}`;
93
165
  try {
@@ -102,22 +174,28 @@ class BalchemyMcpClient {
102
174
  catch {
103
175
  // ignore parse errors — use default message
104
176
  }
105
- const code = response.status === 401
106
- ? "auth_error"
107
- : response.status === 429
108
- ? "rate_limit_error"
109
- : "execution_error";
110
- throw new agent_sdk_error_1.AgentSdkError({ code, status: response.status, message });
177
+ throw this.mapHttpError(response, message);
111
178
  }
112
179
  try {
113
- return JSON.parse(raw);
180
+ const parsed = JSON.parse(raw);
181
+ if (!this.isMcpHealthResponse(parsed)) {
182
+ throw new Error('invalid health envelope');
183
+ }
184
+ if (parsed.publicId !== this.publicId) {
185
+ throw new Error('health principal mismatch');
186
+ }
187
+ return parsed;
114
188
  }
115
189
  catch {
116
190
  throw new agent_sdk_error_1.AgentSdkError({
117
191
  code: "invalid_response",
118
192
  status: response.status,
119
193
  message: "Invalid JSON in health response",
120
- details: raw,
194
+ details: (0, failure_metadata_1.buildFailureDetails)({
195
+ layer: "mcp_ingress",
196
+ code: "INVALID_RESPONSE",
197
+ retryable: false,
198
+ }),
121
199
  });
122
200
  }
123
201
  }
@@ -125,15 +203,14 @@ class BalchemyMcpClient {
125
203
  if (error instanceof agent_sdk_error_1.AgentSdkError) {
126
204
  throw error;
127
205
  }
128
- const message = error instanceof Error ? error.message : "MCP health check failed";
129
- throw new agent_sdk_error_1.AgentSdkError({ code: "network_error", message, details: error });
206
+ throw this.mapNetworkError(error, "MCP health check failed");
130
207
  }
131
208
  finally {
132
209
  globalThis.clearTimeout(timeout);
133
210
  }
134
211
  }
135
212
  /**
136
- * Send multiple tool calls in a single JSON-RPC batch request.
213
+ * Send multiple canonical read-only, non-raw tool calls in one JSON-RPC batch.
137
214
  *
138
215
  * The MCP server processes the batch array and returns an array of
139
216
  * responses in the same order. Each result is individually marked
@@ -146,7 +223,11 @@ class BalchemyMcpClient {
146
223
  if (calls.length === 0) {
147
224
  return [];
148
225
  }
149
- const ids = calls.map((_, i) => `batch-${i}-${Date.now()}`);
226
+ if (calls.length > MAX_BATCH_CALLS) {
227
+ throw new agent_sdk_error_1.AgentSdkError({ code: "policy_error", message: "MCP batch exceeds the SDK call limit" });
228
+ }
229
+ await this.requireReadOnlyBatchTools(calls);
230
+ const ids = calls.map(() => `batch-${crypto.randomUUID()}`);
150
231
  const batchBody = calls.map((call, i) => ({
151
232
  jsonrpc: "2.0",
152
233
  id: ids[i],
@@ -156,17 +237,22 @@ class BalchemyMcpClient {
156
237
  const controller = new AbortController();
157
238
  const timeout = globalThis.setTimeout(() => controller.abort(), this.timeoutMs);
158
239
  try {
240
+ const serializedBatch = this.serializeRequestBody(batchBody);
159
241
  const response = await this.fetchFn(this.endpoint, {
160
242
  method: "POST",
161
243
  headers: {
162
244
  "Content-Type": "application/json",
163
245
  Accept: "application/json, text/event-stream",
164
246
  Authorization: `Bearer ${this.apiKey}`,
247
+ ...this.createReplayHeaders(),
165
248
  },
166
- body: JSON.stringify(batchBody),
249
+ body: serializedBatch,
167
250
  signal: controller.signal,
168
251
  });
169
- const raw = await response.text();
252
+ const raw = await (0, redaction_1.readBoundedResponseText)(response, MAX_MCP_RESPONSE_BYTES);
253
+ if (!response.ok) {
254
+ throw this.mapHttpError(response, this.safeParseUnknown(raw));
255
+ }
170
256
  if (!raw) {
171
257
  throw new agent_sdk_error_1.AgentSdkError({
172
258
  code: "invalid_response",
@@ -184,14 +270,36 @@ class BalchemyMcpClient {
184
270
  code: "invalid_response",
185
271
  status: response.status,
186
272
  message: "Invalid JSON-RPC batch response",
187
- details: raw,
273
+ details: (0, failure_metadata_1.buildFailureDetails)({
274
+ layer: "mcp_ingress",
275
+ code: "INVALID_RESPONSE",
276
+ retryable: false,
277
+ }),
188
278
  });
189
279
  }
190
280
  // Normalize: server may return a single object if batch has 1 item.
191
281
  const responses = Array.isArray(parsed) ? parsed : [parsed];
282
+ const expectedIds = new Set(ids);
283
+ const responseById = new Map();
284
+ for (const candidate of responses) {
285
+ if (!this.isJsonRpcEnvelope(candidate)) {
286
+ throw new agent_sdk_error_1.AgentSdkError({ code: "invalid_response", message: "Invalid JSON-RPC batch envelope" });
287
+ }
288
+ const id = candidate.id;
289
+ if (typeof id !== 'string' || !expectedIds.has(id) || responseById.has(id)) {
290
+ throw new agent_sdk_error_1.AgentSdkError({ code: "invalid_response", message: "JSON-RPC batch response id mismatch" });
291
+ }
292
+ responseById.set(id, candidate);
293
+ }
294
+ const singleEnvelope = responses.length === 1
295
+ ? responses[0]
296
+ : undefined;
297
+ if (singleEnvelope && this.isJsonRpcError(singleEnvelope)) {
298
+ throw this.mapRpcError(response, singleEnvelope.error);
299
+ }
192
300
  return calls.map((call, i) => {
193
- // Match by id; fall back to positional if server reorders.
194
- const envelope = responses.find((r) => typeof r === "object" && r !== null && r.id === ids[i]) ?? responses[i];
301
+ // Match strictly by id so reordered responses remain correlated.
302
+ const envelope = responseById.get(ids[i]);
195
303
  if (!envelope) {
196
304
  return {
197
305
  success: false,
@@ -208,40 +316,47 @@ class BalchemyMcpClient {
208
316
  success: false,
209
317
  name: call.name,
210
318
  index: i,
211
- error: new agent_sdk_error_1.AgentSdkError({
212
- code: "execution_error",
213
- status: response.status,
214
- message: envelope.error.message,
215
- details: envelope.error.data,
216
- }),
319
+ error: this.mapRpcError(response, envelope.error),
320
+ };
321
+ }
322
+ try {
323
+ return {
324
+ success: true,
325
+ name: call.name,
326
+ index: i,
327
+ result: this.validateCallToolResponse(envelope.result),
328
+ };
329
+ }
330
+ catch (error) {
331
+ return {
332
+ success: false,
333
+ name: call.name,
334
+ index: i,
335
+ error: error instanceof agent_sdk_error_1.AgentSdkError
336
+ ? error
337
+ : new agent_sdk_error_1.AgentSdkError({ code: "invalid_response", message: "Invalid tool response envelope" }),
217
338
  };
218
339
  }
219
- return {
220
- success: true,
221
- name: call.name,
222
- index: i,
223
- result: envelope.result,
224
- };
225
340
  });
226
341
  }
227
342
  catch (error) {
228
343
  if (error instanceof agent_sdk_error_1.AgentSdkError) {
229
344
  throw error;
230
345
  }
231
- const message = error instanceof Error ? error.message : "MCP batch request failed";
232
- throw new agent_sdk_error_1.AgentSdkError({ code: "network_error", message, details: error });
346
+ throw this.mapNetworkError(error, "MCP batch request failed");
233
347
  }
234
348
  finally {
235
349
  globalThis.clearTimeout(timeout);
236
350
  }
237
351
  }
238
352
  /**
239
- * Execute multiple tool calls with best-effort parallelism.
353
+ * Execute multiple canonical read-only, non-raw calls with best-effort parallelism.
240
354
  *
241
355
  * Tries `callToolsBatch()` first (single HTTP round-trip). If the server
242
356
  * returns a non-batch-compatible error, falls back to running individual
243
357
  * `callTool()` calls in parallel via `Promise.allSettled`.
244
358
  *
359
+ * Protected or metadata-incomplete calls fail before any batch/parallel request.
245
360
  * The fallback path maps `PromiseSettledResult` to `McpBatchToolCallResult`
246
361
  * so callers always get the same shape regardless of the path taken.
247
362
  */
@@ -249,10 +364,14 @@ class BalchemyMcpClient {
249
364
  if (calls.length === 0) {
250
365
  return [];
251
366
  }
367
+ await this.requireReadOnlyBatchTools(calls);
252
368
  try {
253
369
  return await this.callToolsBatch(calls);
254
370
  }
255
371
  catch (batchError) {
372
+ if (!this.isBatchUnsupportedError(batchError)) {
373
+ throw batchError;
374
+ }
256
375
  // Fallback: individual parallel calls via Promise.allSettled.
257
376
  // This path is taken if the server does not support JSON-RPC batch.
258
377
  const settled = await Promise.allSettled(calls.map((call) => this.callTool(call.name, call.arguments)));
@@ -266,8 +385,12 @@ class BalchemyMcpClient {
266
385
  ? raw
267
386
  : new agent_sdk_error_1.AgentSdkError({
268
387
  code: "execution_error",
269
- message: raw instanceof Error ? raw.message : "Tool call failed",
270
- details: raw,
388
+ message: this.sanitizeMcpErrorMessage(raw instanceof Error ? raw.message : "Tool call failed", "Tool call failed"),
389
+ details: (0, failure_metadata_1.buildFailureDetails)({
390
+ layer: "mcp_ingress",
391
+ code: "EXECUTION_ERROR",
392
+ retryable: false,
393
+ }),
271
394
  });
272
395
  return { success: false, name: call.name, index: i, error };
273
396
  });
@@ -307,8 +430,28 @@ class BalchemyMcpClient {
307
430
  * Returns the raw contents array. Callers extract `.text` from the first item.
308
431
  */
309
432
  async readResource(uri) {
433
+ if (typeof uri !== 'string' || uri.length === 0 || uri.length > 2_048 || /[\u0000\r\n]/.test(uri)) {
434
+ throw new agent_sdk_error_1.AgentSdkError({ code: "policy_error", message: "MCP resource URI is invalid" });
435
+ }
310
436
  const result = await this.rpc('resources/read', { uri });
311
- return result.contents ?? [];
437
+ const contents = typeof result === 'object' && result !== null && !Array.isArray(result)
438
+ ? result.contents
439
+ : undefined;
440
+ if (!Array.isArray(contents) || contents.length > 100) {
441
+ throw new agent_sdk_error_1.AgentSdkError({ code: "invalid_response", message: "Invalid MCP resource response" });
442
+ }
443
+ for (const content of contents) {
444
+ if (typeof content !== 'object'
445
+ || content === null
446
+ || typeof content.uri !== 'string'
447
+ || content.uri.length === 0
448
+ || content.uri.length > 2_048
449
+ || (content.mimeType !== undefined && (typeof content.mimeType !== 'string' || content.mimeType.length > 256))
450
+ || (content.text !== undefined && (typeof content.text !== 'string' || content.text.length > MAX_MCP_RESPONSE_BYTES))) {
451
+ throw new agent_sdk_error_1.AgentSdkError({ code: "invalid_response", message: "Invalid MCP resource content" });
452
+ }
453
+ }
454
+ return contents;
312
455
  }
313
456
  /**
314
457
  * @deprecated Seed pool is disabled. Fund custodial wallet via dashboard or on-chain transfer.
@@ -326,34 +469,44 @@ class BalchemyMcpClient {
326
469
  });
327
470
  }
328
471
  // ── Internal ─────────────────────────────────────────────────────────────
329
- async rpc(method, params) {
330
- return (0, retry_1.withRetry)(async () => {
472
+ createReplayHeaders() {
473
+ return {
474
+ "x-request-nonce": crypto.randomUUID(),
475
+ "x-request-timestamp": String(Math.floor(Date.now() / 1000)),
476
+ };
477
+ }
478
+ async rpc(method, params, options) {
479
+ return (0, retry_1.withRetry)(async (attempt) => {
331
480
  const controller = new AbortController();
332
- const timeout = globalThis.setTimeout(() => controller.abort(), this.timeoutMs);
481
+ const timeout = globalThis.setTimeout(() => controller.abort(), Math.max(1, Math.min(this.timeoutMs, attempt.remainingDeadlineMs)));
333
482
  try {
483
+ const requestId = crypto.randomUUID();
484
+ const body = this.serializeRequestBody({
485
+ jsonrpc: "2.0",
486
+ id: requestId,
487
+ method,
488
+ params,
489
+ });
334
490
  const response = await this.fetchFn(this.endpoint, {
335
491
  method: "POST",
492
+ // A redirect must not forward a protected POST or its custom proof
493
+ // header. The configured MCP endpoint is the only request target.
494
+ redirect: "error",
336
495
  headers: {
337
496
  "Content-Type": "application/json",
338
497
  Accept: "application/json, text/event-stream",
339
498
  Authorization: `Bearer ${this.apiKey}`,
499
+ ...options?.headers,
340
500
  },
341
- body: JSON.stringify({
342
- jsonrpc: "2.0",
343
- id: crypto.randomUUID(),
344
- method,
345
- params,
346
- }),
501
+ body,
347
502
  signal: controller.signal,
348
503
  });
349
- const payload = await this.parseJsonRpc(response);
504
+ const payload = await this.parseJsonRpc(response, requestId);
350
505
  if (this.isJsonRpcError(payload)) {
351
- throw new agent_sdk_error_1.AgentSdkError({
352
- code: "execution_error",
353
- status: response.status,
354
- message: payload.error.message,
355
- details: payload.error.data,
356
- });
506
+ throw this.mapRpcError(response, payload.error);
507
+ }
508
+ if (!response.ok) {
509
+ throw this.mapHttpError(response, payload.result);
357
510
  }
358
511
  return payload.result;
359
512
  }
@@ -361,37 +514,225 @@ class BalchemyMcpClient {
361
514
  if (error instanceof agent_sdk_error_1.AgentSdkError) {
362
515
  throw error;
363
516
  }
364
- const message = error instanceof Error ? error.message : "MCP request failed";
365
- throw new agent_sdk_error_1.AgentSdkError({
366
- code: "network_error",
367
- message,
368
- details: error,
369
- });
517
+ throw this.mapNetworkError(error, "MCP request failed");
370
518
  }
371
519
  finally {
372
520
  globalThis.clearTimeout(timeout);
373
521
  }
374
- }, this.resolveRetryOptions(method));
522
+ }, {
523
+ kind: options?.retryPolicy === "protected" ? "side_effecting" : "read",
524
+ operation: `mcp:${method.replace(/[^a-zA-Z0-9_.:/-]/g, "_").slice(0, 96)}`,
525
+ }, this.resolveRetryOptions(options?.retryPolicy ?? "read"));
375
526
  }
376
- resolveRetryOptions(method) {
377
- const configuredShouldRetry = this.retryOptions.shouldRetry;
527
+ resolveRetryOptions(retryPolicy) {
528
+ if (retryPolicy === "protected") {
529
+ return {
530
+ ...this.retryOptions,
531
+ maxAttempts: 1,
532
+ shouldRetry: () => false,
533
+ };
534
+ }
378
535
  return {
379
536
  ...this.retryOptions,
380
- shouldRetry: (error, context) => {
381
- if (configuredShouldRetry) {
382
- return configuredShouldRetry(error, context);
383
- }
384
- if (method === "tools/call" &&
385
- error instanceof agent_sdk_error_1.AgentSdkError &&
386
- error.code === "execution_error") {
387
- return false;
388
- }
389
- return (0, retry_1.defaultShouldRetry)(error);
390
- },
537
+ shouldRetry: this.retryOptions.shouldRetry
538
+ ?? ((error) => (0, retry_1.defaultShouldRetry)(error)),
391
539
  };
392
540
  }
393
- async parseJsonRpc(response) {
394
- const raw = await response.text();
541
+ mapNetworkError(error, fallbackMessage) {
542
+ if (error instanceof redaction_1.ResponseSizeLimitError) {
543
+ return new agent_sdk_error_1.AgentSdkError({
544
+ code: "invalid_response",
545
+ message: "MCP response exceeds the SDK size limit",
546
+ details: (0, failure_metadata_1.buildFailureDetails)({
547
+ layer: "mcp_ingress",
548
+ code: "INVALID_RESPONSE",
549
+ retryable: false,
550
+ }),
551
+ });
552
+ }
553
+ const aborted = error instanceof Error && error.name === "AbortError";
554
+ return new agent_sdk_error_1.AgentSdkError({
555
+ code: "network_error",
556
+ message: aborted
557
+ ? "MCP request timed out"
558
+ : fallbackMessage,
559
+ details: (0, failure_metadata_1.buildFailureDetails)({
560
+ layer: "transport",
561
+ code: aborted ? "CLIENT_TIMEOUT" : "NETWORK_ERROR",
562
+ retryable: true,
563
+ }),
564
+ });
565
+ }
566
+ mapHttpError(response, details) {
567
+ const status = response.status;
568
+ const code = status === 401
569
+ ? "auth_error"
570
+ : status === 403
571
+ ? "policy_error"
572
+ : status === 429
573
+ ? "rate_limit_error"
574
+ : status >= 500
575
+ ? "execution_error"
576
+ : "invalid_response";
577
+ const metadata = (0, failure_metadata_1.extractFailureMetadata)({ sdkCode: code, status, details });
578
+ const retryAfterSeconds = this.readRetryAfterSeconds(response)
579
+ ?? metadata.retryAfterSeconds;
580
+ return new agent_sdk_error_1.AgentSdkError({
581
+ code,
582
+ status,
583
+ message: `MCP request failed with status ${status}`,
584
+ details: (0, failure_metadata_1.buildFailureDetails)({
585
+ ...metadata,
586
+ ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),
587
+ }),
588
+ });
589
+ }
590
+ mapRpcError(response, rpcError) {
591
+ if (!response.ok) {
592
+ return this.mapHttpError(response, rpcError.data);
593
+ }
594
+ const metadata = (0, failure_metadata_1.extractFailureMetadata)({
595
+ sdkCode: "execution_error",
596
+ status: response.status,
597
+ details: rpcError.data,
598
+ });
599
+ const batchUnsupported = rpcError.code === -32600 || rpcError.code === -32601;
600
+ return new agent_sdk_error_1.AgentSdkError({
601
+ code: "execution_error",
602
+ status: response.status,
603
+ message: "MCP execution failed",
604
+ details: (0, failure_metadata_1.buildFailureDetails)({
605
+ ...metadata,
606
+ code: batchUnsupported ? "MCP_BATCH_UNSUPPORTED" : metadata.code,
607
+ retryable: false,
608
+ }),
609
+ });
610
+ }
611
+ isBatchUnsupportedError(error) {
612
+ return error instanceof agent_sdk_error_1.AgentSdkError
613
+ && error.machineCode === "MCP_BATCH_UNSUPPORTED";
614
+ }
615
+ readRetryAfterSeconds(response) {
616
+ const headers = response.headers;
617
+ return typeof headers?.get === "function"
618
+ ? (0, failure_metadata_1.parseRetryAfterSeconds)(headers.get("retry-after"))
619
+ : undefined;
620
+ }
621
+ safeParseUnknown(raw) {
622
+ try {
623
+ return JSON.parse(raw);
624
+ }
625
+ catch {
626
+ return undefined;
627
+ }
628
+ }
629
+ sanitizeMcpErrorMessage(message, fallback) {
630
+ const redacted = (0, redaction_1.redactSecretLikeText)(message).replace(/https?:\/\/\S+/gi, "[source]");
631
+ return redacted.length > 240 ? fallback : redacted;
632
+ }
633
+ async resolveExposedTool(name) {
634
+ const catalog = await this.getToolCatalog();
635
+ const tool = catalog.get(name);
636
+ if (!tool) {
637
+ throw new agent_sdk_error_1.AgentSdkError({
638
+ code: "execution_error",
639
+ message: `Tool "${name}" is not exposed by tools/list`,
640
+ details: { code: "MCP_TOOL_NOT_EXPOSED", reason: "MCP_TOOL_NOT_EXPOSED", tool: name },
641
+ });
642
+ }
643
+ const scope = tool["x-balchemy-requires-scope"];
644
+ const safety = tool["x-balchemy-safety"];
645
+ const raw = tool["x-balchemy-raw"];
646
+ const category = tool["x-balchemy-category"];
647
+ const dataContract = tool["x-balchemy-data-contract"] ?? tool["x-balchemy-response"];
648
+ const expectedSafety = scope === "read"
649
+ ? "read_only"
650
+ : scope === "trade"
651
+ ? "trade_guarded"
652
+ : scope === "manage"
653
+ ? "manage_step_up"
654
+ : undefined;
655
+ if ((scope !== "read" && scope !== "trade" && scope !== "manage")
656
+ || safety !== expectedSafety
657
+ || typeof raw !== "boolean"
658
+ || typeof category !== "string"
659
+ || !/^[a-zA-Z0-9_-]{1,64}$/.test(category)
660
+ || typeof dataContract !== "object"
661
+ || dataContract === null
662
+ || dataContract["raw"] !== false) {
663
+ throw new agent_sdk_error_1.AgentSdkError({
664
+ code: "execution_error",
665
+ message: `Tool "${name}" has incomplete MCP safety metadata`,
666
+ details: { code: "MCP_TOOL_METADATA_INVALID", reason: "MCP_TOOL_METADATA_INVALID", tool: name },
667
+ });
668
+ }
669
+ return tool;
670
+ }
671
+ async getToolCatalog() {
672
+ if (this.toolCatalog) {
673
+ return this.toolCatalog;
674
+ }
675
+ if (!this.toolCatalogPromise) {
676
+ this.toolCatalogPromise = this.listTools()
677
+ .then(() => this.toolCatalog ?? new Map())
678
+ .finally(() => {
679
+ this.toolCatalogPromise = null;
680
+ });
681
+ }
682
+ return this.toolCatalogPromise;
683
+ }
684
+ buildToolCatalog(tools) {
685
+ if (!Array.isArray(tools)) {
686
+ throw new agent_sdk_error_1.AgentSdkError({
687
+ code: "invalid_response",
688
+ message: "tools/list returned an invalid tool catalog",
689
+ });
690
+ }
691
+ const catalog = new Map();
692
+ for (const tool of tools) {
693
+ if (typeof tool !== "object"
694
+ || tool === null
695
+ || typeof tool.name !== "string"
696
+ || !/^[a-zA-Z0-9_.:-]{1,128}$/.test(tool.name)
697
+ || catalog.has(tool.name)) {
698
+ throw new agent_sdk_error_1.AgentSdkError({
699
+ code: "invalid_response",
700
+ message: "tools/list returned duplicate or invalid tool metadata",
701
+ });
702
+ }
703
+ catalog.set(tool.name, {
704
+ ...tool,
705
+ ...(tool["x-balchemy-data-contract"]
706
+ ? { "x-balchemy-data-contract": { ...tool["x-balchemy-data-contract"] } }
707
+ : {}),
708
+ ...(tool["x-balchemy-response"]
709
+ ? { "x-balchemy-response": { ...tool["x-balchemy-response"] } }
710
+ : {}),
711
+ });
712
+ }
713
+ return catalog;
714
+ }
715
+ isReadOnlyNonRawTool(tool) {
716
+ const dataContract = tool["x-balchemy-data-contract"] ?? tool["x-balchemy-response"];
717
+ return tool["x-balchemy-requires-scope"] === "read"
718
+ && tool["x-balchemy-safety"] === "read_only"
719
+ && tool["x-balchemy-raw"] === false
720
+ && dataContract?.["raw"] === false;
721
+ }
722
+ async requireReadOnlyBatchTools(calls) {
723
+ for (const call of calls) {
724
+ const tool = await this.resolveExposedTool(call.name);
725
+ if (!this.isReadOnlyNonRawTool(tool)) {
726
+ throw new agent_sdk_error_1.AgentSdkError({
727
+ code: "execution_error",
728
+ message: `Protected tool "${call.name}" cannot be submitted through batch or parallel helpers`,
729
+ details: { reason: "PROTECTED_BATCH_NOT_ALLOWED", tool: call.name },
730
+ });
731
+ }
732
+ }
733
+ }
734
+ async parseJsonRpc(response, requestId) {
735
+ const raw = await (0, redaction_1.readBoundedResponseText)(response, MAX_MCP_RESPONSE_BYTES);
395
736
  if (!raw) {
396
737
  throw new agent_sdk_error_1.AgentSdkError({
397
738
  code: "invalid_response",
@@ -401,14 +742,22 @@ class BalchemyMcpClient {
401
742
  }
402
743
  const normalized = this.extractSsePayload(raw);
403
744
  try {
404
- return JSON.parse(normalized);
745
+ const parsed = JSON.parse(normalized);
746
+ if (!this.isJsonRpcEnvelope(parsed) || parsed.id !== requestId) {
747
+ throw new Error('JSON-RPC response id mismatch');
748
+ }
749
+ return parsed;
405
750
  }
406
751
  catch {
407
752
  throw new agent_sdk_error_1.AgentSdkError({
408
753
  code: "invalid_response",
409
754
  status: response.status,
410
755
  message: "Invalid JSON-RPC payload",
411
- details: raw,
756
+ details: (0, failure_metadata_1.buildFailureDetails)({
757
+ layer: "mcp_ingress",
758
+ code: "INVALID_RESPONSE",
759
+ retryable: false,
760
+ }),
412
761
  });
413
762
  }
414
763
  }
@@ -420,14 +769,73 @@ class BalchemyMcpClient {
420
769
  if (lines.length === 0) {
421
770
  return raw;
422
771
  }
423
- const last = lines[lines.length - 1];
424
- return last.replace(/^data:\s*/, "");
772
+ return lines.map((line) => line.replace(/^data:\s*/, "")).join("\n");
425
773
  }
426
774
  isJsonRpcError(payload) {
427
775
  return (typeof payload === "object" &&
428
776
  payload !== null &&
429
777
  "error" in payload);
430
778
  }
779
+ isJsonRpcEnvelope(value) {
780
+ if (typeof value !== "object" || value === null || Array.isArray(value))
781
+ return false;
782
+ const record = value;
783
+ if (record.jsonrpc !== "2.0")
784
+ return false;
785
+ if (!(typeof record.id === "string" || typeof record.id === "number" || record.id === null))
786
+ return false;
787
+ const hasResult = Object.prototype.hasOwnProperty.call(record, "result");
788
+ const error = record.error;
789
+ const hasError = typeof error === "object" && error !== null && !Array.isArray(error)
790
+ && typeof error.code === "number"
791
+ && Number.isSafeInteger(error.code)
792
+ && typeof error.message === "string";
793
+ return hasResult !== hasError;
794
+ }
795
+ isMcpHealthResponse(value) {
796
+ if (typeof value !== "object" || value === null || Array.isArray(value))
797
+ return false;
798
+ const record = value;
799
+ return record.ok === true
800
+ && typeof record.publicId === "string"
801
+ && /^[A-Za-z0-9._:-]{1,160}$/.test(record.publicId)
802
+ && (record.scope === "read" || record.scope === "trade" || record.scope === "manage");
803
+ }
804
+ validateCallToolResponse(value) {
805
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
806
+ throw new agent_sdk_error_1.AgentSdkError({ code: "invalid_response", message: "Invalid tool response envelope" });
807
+ }
808
+ const record = value;
809
+ if (!Array.isArray(record.content)
810
+ || record.content.length > 100
811
+ || (record.isError !== undefined && typeof record.isError !== "boolean")) {
812
+ throw new agent_sdk_error_1.AgentSdkError({ code: "invalid_response", message: "Invalid tool response envelope" });
813
+ }
814
+ for (const item of record.content) {
815
+ if (typeof item !== "object"
816
+ || item === null
817
+ || Array.isArray(item)
818
+ || item.type !== "text"
819
+ || typeof item.text !== "string"
820
+ || item.text.length > MAX_MCP_RESPONSE_BYTES) {
821
+ throw new agent_sdk_error_1.AgentSdkError({ code: "invalid_response", message: "Invalid tool response content" });
822
+ }
823
+ }
824
+ return value;
825
+ }
826
+ serializeRequestBody(value) {
827
+ let serialized;
828
+ try {
829
+ serialized = JSON.stringify(value);
830
+ }
831
+ catch {
832
+ throw new agent_sdk_error_1.AgentSdkError({ code: "policy_error", message: "MCP request is not JSON serializable" });
833
+ }
834
+ if (Buffer.byteLength(serialized, "utf8") > MAX_MCP_REQUEST_BYTES) {
835
+ throw new agent_sdk_error_1.AgentSdkError({ code: "policy_error", message: "MCP request exceeds the SDK size limit" });
836
+ }
837
+ return serialized;
838
+ }
431
839
  }
432
840
  exports.BalchemyMcpClient = BalchemyMcpClient;
433
841
  const connectMcp = (config) => {