@balchemyai/agent-sdk 0.8.1 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +16 -1
- package/README.md +20 -284
- package/dist/agent-loop/llm-adapters/openai.js +1 -1
- package/dist/agent-loop/llm-adapters/openai.js.map +1 -1
- package/dist/agent-loop/types.d.ts +1 -138
- package/dist/agent-loop/types.d.ts.map +1 -1
- package/dist/index.d.ts +1 -33
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -72
- package/dist/index.js.map +1 -1
- package/docs/error-retry-strategy.md +4 -4
- package/docs/release-policy.md +1 -1
- package/package.json +2 -6
- package/dist/agent-loop/agent-loop.d.ts +0 -77
- package/dist/agent-loop/agent-loop.d.ts.map +0 -1
- package/dist/agent-loop/agent-loop.js +0 -1270
- package/dist/agent-loop/agent-loop.js.map +0 -1
- package/dist/agent-loop/decision-handler.d.ts +0 -38
- package/dist/agent-loop/decision-handler.d.ts.map +0 -1
- package/dist/agent-loop/decision-handler.js +0 -231
- package/dist/agent-loop/decision-handler.js.map +0 -1
- package/dist/agent-loop/llm-cost-tracker.d.ts +0 -27
- package/dist/agent-loop/llm-cost-tracker.d.ts.map +0 -1
- package/dist/agent-loop/llm-cost-tracker.js +0 -102
- package/dist/agent-loop/llm-cost-tracker.js.map +0 -1
- package/dist/agent-loop/model-router.d.ts +0 -35
- package/dist/agent-loop/model-router.d.ts.map +0 -1
- package/dist/agent-loop/model-router.js +0 -55
- package/dist/agent-loop/model-router.js.map +0 -1
- package/dist/agent-loop/rule-checker.d.ts +0 -26
- package/dist/agent-loop/rule-checker.d.ts.map +0 -1
- package/dist/agent-loop/rule-checker.js +0 -70
- package/dist/agent-loop/rule-checker.js.map +0 -1
- package/dist/agent-loop/telemetry-reporter.d.ts +0 -70
- package/dist/agent-loop/telemetry-reporter.d.ts.map +0 -1
- package/dist/agent-loop/telemetry-reporter.js +0 -221
- package/dist/agent-loop/telemetry-reporter.js.map +0 -1
- package/dist/agent-loop/webhook-receiver.d.ts +0 -41
- package/dist/agent-loop/webhook-receiver.d.ts.map +0 -1
- package/dist/agent-loop/webhook-receiver.js +0 -308
- package/dist/agent-loop/webhook-receiver.js.map +0 -1
- package/dist/auth/onboarding.d.ts +0 -12
- package/dist/auth/onboarding.d.ts.map +0 -1
- package/dist/auth/onboarding.js +0 -70
- package/dist/auth/onboarding.js.map +0 -1
- package/dist/auth/token-store.d.ts +0 -44
- package/dist/auth/token-store.d.ts.map +0 -1
- package/dist/auth/token-store.js +0 -67
- package/dist/auth/token-store.js.map +0 -1
- package/dist/mcp/mcp-client.d.ts +0 -174
- package/dist/mcp/mcp-client.d.ts.map +0 -1
- package/dist/mcp/mcp-client.js +0 -845
- package/dist/mcp/mcp-client.js.map +0 -1
- package/dist/streaming/sse-event-stream.d.ts +0 -72
- package/dist/streaming/sse-event-stream.d.ts.map +0 -1
- package/dist/streaming/sse-event-stream.js +0 -403
- package/dist/streaming/sse-event-stream.js.map +0 -1
- package/dist/types.d.ts +0 -162
- package/dist/types.d.ts.map +0 -1
- package/dist/types.js +0 -3
- package/dist/types.js.map +0 -1
- package/dist/utils/package-version.d.ts +0 -2
- package/dist/utils/package-version.d.ts.map +0 -1
- package/dist/utils/package-version.js +0 -54
- package/dist/utils/package-version.js.map +0 -1
- package/docs/BEHAVIOR_RULES.md +0 -184
- package/docs/DEPLOYMENT.md +0 -197
- package/docs/QUICKSTART.md +0 -139
- package/docs/examples/custom-strategy.yaml +0 -73
- package/docs/examples/dca-accumulator.yaml +0 -41
- package/docs/examples/memecoin-sniper.yaml +0 -47
- package/docs/examples/swing-trader.yaml +0 -50
- package/docs/partner-integration-checklist.md +0 -47
- package/docs/python-parity-backlog.md +0 -20
package/dist/mcp/mcp-client.js
DELETED
|
@@ -1,845 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.connectMcp = exports.BalchemyMcpClient = void 0;
|
|
4
|
-
exports.getToolText = getToolText;
|
|
5
|
-
exports.parseToolJson = parseToolJson;
|
|
6
|
-
exports.isToolError = isToolError;
|
|
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");
|
|
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;
|
|
14
|
-
// ── Typed tool call helpers ───────────────────────────────────────────────────
|
|
15
|
-
/** Extract typed text from a tool call response. Returns empty string on error. */
|
|
16
|
-
function getToolText(response) {
|
|
17
|
-
const first = response.content.find((c) => c.type === "text");
|
|
18
|
-
return first?.text ?? "";
|
|
19
|
-
}
|
|
20
|
-
/** Parse a tool call response text as JSON. Returns null if not valid JSON. */
|
|
21
|
-
function parseToolJson(response) {
|
|
22
|
-
const text = getToolText(response);
|
|
23
|
-
try {
|
|
24
|
-
return JSON.parse(text);
|
|
25
|
-
}
|
|
26
|
-
catch {
|
|
27
|
-
return null;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
/** Returns true if the tool response indicates an error. */
|
|
31
|
-
function isToolError(response) {
|
|
32
|
-
return response.isError === true;
|
|
33
|
-
}
|
|
34
|
-
// ── Client ───────────────────────────────────────────────────────────────────
|
|
35
|
-
class BalchemyMcpClient {
|
|
36
|
-
endpoint;
|
|
37
|
-
apiKey;
|
|
38
|
-
timeoutMs;
|
|
39
|
-
fetchFn;
|
|
40
|
-
retryOptions;
|
|
41
|
-
publicId;
|
|
42
|
-
toolCatalog = null;
|
|
43
|
-
toolCatalogPromise = null;
|
|
44
|
-
constructor(config) {
|
|
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(/\/+$/, '');
|
|
68
|
-
this.apiKey = config.apiKey;
|
|
69
|
-
this.publicId = publicId;
|
|
70
|
-
this.timeoutMs = config.timeoutMs ?? 15_000;
|
|
71
|
-
this.fetchFn = config.fetchFn ?? fetch;
|
|
72
|
-
this.retryOptions = config.retry ?? { maxAttempts: 3 };
|
|
73
|
-
}
|
|
74
|
-
async listTools() {
|
|
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()) };
|
|
81
|
-
}
|
|
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", {
|
|
113
|
-
name,
|
|
114
|
-
arguments: argumentsPayload,
|
|
115
|
-
}, {
|
|
116
|
-
headers,
|
|
117
|
-
retryPolicy: readOnly ? "read" : "protected",
|
|
118
|
-
});
|
|
119
|
-
return this.validateCallToolResponse(response);
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* Lightweight health check using the `/health` endpoint.
|
|
123
|
-
* Returns `true` if the API key is valid and MCP is enabled.
|
|
124
|
-
* Falls back to `listTools()` if the health endpoint returns 404
|
|
125
|
-
* (e.g. backend not yet upgraded).
|
|
126
|
-
*/
|
|
127
|
-
async ping() {
|
|
128
|
-
try {
|
|
129
|
-
const health = await this.healthCheck();
|
|
130
|
-
return health.ok;
|
|
131
|
-
}
|
|
132
|
-
catch (err) {
|
|
133
|
-
// If backend does not yet have /health, fall back to listTools.
|
|
134
|
-
if (err instanceof agent_sdk_error_1.AgentSdkError &&
|
|
135
|
-
(err.status === 404 || err.status === 405)) {
|
|
136
|
-
const tools = await this.listTools();
|
|
137
|
-
return Array.isArray(tools.tools);
|
|
138
|
-
}
|
|
139
|
-
throw err;
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
/**
|
|
143
|
-
* Call the lightweight `/health` endpoint for this MCP principal.
|
|
144
|
-
* Throws `AgentSdkError` if unauthorized or not found.
|
|
145
|
-
*/
|
|
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) {
|
|
150
|
-
const healthUrl = `${this.endpoint}/health`;
|
|
151
|
-
const controller = new AbortController();
|
|
152
|
-
const timeout = globalThis.setTimeout(() => controller.abort(), Math.max(1, Math.min(this.timeoutMs, remainingDeadlineMs)));
|
|
153
|
-
try {
|
|
154
|
-
const response = await this.fetchFn(healthUrl, {
|
|
155
|
-
method: "GET",
|
|
156
|
-
headers: {
|
|
157
|
-
Accept: "application/json",
|
|
158
|
-
Authorization: `Bearer ${this.apiKey}`,
|
|
159
|
-
},
|
|
160
|
-
signal: controller.signal,
|
|
161
|
-
});
|
|
162
|
-
const raw = await (0, redaction_1.readBoundedResponseText)(response, MAX_MCP_RESPONSE_BYTES);
|
|
163
|
-
if (!response.ok) {
|
|
164
|
-
let message = `MCP health check failed with status ${response.status}`;
|
|
165
|
-
try {
|
|
166
|
-
const parsed = JSON.parse(raw);
|
|
167
|
-
if (typeof parsed.error === "string") {
|
|
168
|
-
message = parsed.error;
|
|
169
|
-
}
|
|
170
|
-
else if (parsed.error?.message) {
|
|
171
|
-
message = parsed.error.message;
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
catch {
|
|
175
|
-
// ignore parse errors — use default message
|
|
176
|
-
}
|
|
177
|
-
throw this.mapHttpError(response, message);
|
|
178
|
-
}
|
|
179
|
-
try {
|
|
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;
|
|
188
|
-
}
|
|
189
|
-
catch {
|
|
190
|
-
throw new agent_sdk_error_1.AgentSdkError({
|
|
191
|
-
code: "invalid_response",
|
|
192
|
-
status: response.status,
|
|
193
|
-
message: "Invalid JSON in health response",
|
|
194
|
-
details: (0, failure_metadata_1.buildFailureDetails)({
|
|
195
|
-
layer: "mcp_ingress",
|
|
196
|
-
code: "INVALID_RESPONSE",
|
|
197
|
-
retryable: false,
|
|
198
|
-
}),
|
|
199
|
-
});
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
catch (error) {
|
|
203
|
-
if (error instanceof agent_sdk_error_1.AgentSdkError) {
|
|
204
|
-
throw error;
|
|
205
|
-
}
|
|
206
|
-
throw this.mapNetworkError(error, "MCP health check failed");
|
|
207
|
-
}
|
|
208
|
-
finally {
|
|
209
|
-
globalThis.clearTimeout(timeout);
|
|
210
|
-
}
|
|
211
|
-
}
|
|
212
|
-
/**
|
|
213
|
-
* Send multiple canonical read-only, non-raw tool calls in one JSON-RPC batch.
|
|
214
|
-
*
|
|
215
|
-
* The MCP server processes the batch array and returns an array of
|
|
216
|
-
* responses in the same order. Each result is individually marked
|
|
217
|
-
* `success: true | false` — a single failed tool does not abort the batch.
|
|
218
|
-
*
|
|
219
|
-
* NOTE: JSON-RPC batch support requires backend MCP SDK >= 1.x.
|
|
220
|
-
* Use `callToolsParallel()` for automatic fallback on unsupported servers.
|
|
221
|
-
*/
|
|
222
|
-
async callToolsBatch(calls) {
|
|
223
|
-
if (calls.length === 0) {
|
|
224
|
-
return [];
|
|
225
|
-
}
|
|
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()}`);
|
|
231
|
-
const batchBody = calls.map((call, i) => ({
|
|
232
|
-
jsonrpc: "2.0",
|
|
233
|
-
id: ids[i],
|
|
234
|
-
method: "tools/call",
|
|
235
|
-
params: { name: call.name, arguments: call.arguments },
|
|
236
|
-
}));
|
|
237
|
-
const controller = new AbortController();
|
|
238
|
-
const timeout = globalThis.setTimeout(() => controller.abort(), this.timeoutMs);
|
|
239
|
-
try {
|
|
240
|
-
const serializedBatch = this.serializeRequestBody(batchBody);
|
|
241
|
-
const response = await this.fetchFn(this.endpoint, {
|
|
242
|
-
method: "POST",
|
|
243
|
-
headers: {
|
|
244
|
-
"Content-Type": "application/json",
|
|
245
|
-
Accept: "application/json, text/event-stream",
|
|
246
|
-
Authorization: `Bearer ${this.apiKey}`,
|
|
247
|
-
...this.createReplayHeaders(),
|
|
248
|
-
},
|
|
249
|
-
body: serializedBatch,
|
|
250
|
-
signal: controller.signal,
|
|
251
|
-
});
|
|
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
|
-
}
|
|
256
|
-
if (!raw) {
|
|
257
|
-
throw new agent_sdk_error_1.AgentSdkError({
|
|
258
|
-
code: "invalid_response",
|
|
259
|
-
status: response.status,
|
|
260
|
-
message: "Empty batch MCP response",
|
|
261
|
-
});
|
|
262
|
-
}
|
|
263
|
-
const normalized = this.extractSsePayload(raw);
|
|
264
|
-
let parsed;
|
|
265
|
-
try {
|
|
266
|
-
parsed = JSON.parse(normalized);
|
|
267
|
-
}
|
|
268
|
-
catch {
|
|
269
|
-
throw new agent_sdk_error_1.AgentSdkError({
|
|
270
|
-
code: "invalid_response",
|
|
271
|
-
status: response.status,
|
|
272
|
-
message: "Invalid JSON-RPC batch response",
|
|
273
|
-
details: (0, failure_metadata_1.buildFailureDetails)({
|
|
274
|
-
layer: "mcp_ingress",
|
|
275
|
-
code: "INVALID_RESPONSE",
|
|
276
|
-
retryable: false,
|
|
277
|
-
}),
|
|
278
|
-
});
|
|
279
|
-
}
|
|
280
|
-
// Normalize: server may return a single object if batch has 1 item.
|
|
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
|
-
}
|
|
300
|
-
return calls.map((call, i) => {
|
|
301
|
-
// Match strictly by id so reordered responses remain correlated.
|
|
302
|
-
const envelope = responseById.get(ids[i]);
|
|
303
|
-
if (!envelope) {
|
|
304
|
-
return {
|
|
305
|
-
success: false,
|
|
306
|
-
name: call.name,
|
|
307
|
-
index: i,
|
|
308
|
-
error: new agent_sdk_error_1.AgentSdkError({
|
|
309
|
-
code: "invalid_response",
|
|
310
|
-
message: `Missing batch response for tool "${call.name}" at index ${i}`,
|
|
311
|
-
}),
|
|
312
|
-
};
|
|
313
|
-
}
|
|
314
|
-
if (this.isJsonRpcError(envelope)) {
|
|
315
|
-
return {
|
|
316
|
-
success: false,
|
|
317
|
-
name: call.name,
|
|
318
|
-
index: i,
|
|
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" }),
|
|
338
|
-
};
|
|
339
|
-
}
|
|
340
|
-
});
|
|
341
|
-
}
|
|
342
|
-
catch (error) {
|
|
343
|
-
if (error instanceof agent_sdk_error_1.AgentSdkError) {
|
|
344
|
-
throw error;
|
|
345
|
-
}
|
|
346
|
-
throw this.mapNetworkError(error, "MCP batch request failed");
|
|
347
|
-
}
|
|
348
|
-
finally {
|
|
349
|
-
globalThis.clearTimeout(timeout);
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
/**
|
|
353
|
-
* Execute multiple canonical read-only, non-raw calls with best-effort parallelism.
|
|
354
|
-
*
|
|
355
|
-
* Tries `callToolsBatch()` first (single HTTP round-trip). If the server
|
|
356
|
-
* returns a non-batch-compatible error, falls back to running individual
|
|
357
|
-
* `callTool()` calls in parallel via `Promise.allSettled`.
|
|
358
|
-
*
|
|
359
|
-
* Protected or metadata-incomplete calls fail before any batch/parallel request.
|
|
360
|
-
* The fallback path maps `PromiseSettledResult` to `McpBatchToolCallResult`
|
|
361
|
-
* so callers always get the same shape regardless of the path taken.
|
|
362
|
-
*/
|
|
363
|
-
async callToolsParallel(calls) {
|
|
364
|
-
if (calls.length === 0) {
|
|
365
|
-
return [];
|
|
366
|
-
}
|
|
367
|
-
await this.requireReadOnlyBatchTools(calls);
|
|
368
|
-
try {
|
|
369
|
-
return await this.callToolsBatch(calls);
|
|
370
|
-
}
|
|
371
|
-
catch (batchError) {
|
|
372
|
-
if (!this.isBatchUnsupportedError(batchError)) {
|
|
373
|
-
throw batchError;
|
|
374
|
-
}
|
|
375
|
-
// Fallback: individual parallel calls via Promise.allSettled.
|
|
376
|
-
// This path is taken if the server does not support JSON-RPC batch.
|
|
377
|
-
const settled = await Promise.allSettled(calls.map((call) => this.callTool(call.name, call.arguments)));
|
|
378
|
-
return settled.map((outcome, i) => {
|
|
379
|
-
const call = calls[i];
|
|
380
|
-
if (outcome.status === "fulfilled") {
|
|
381
|
-
return { success: true, name: call.name, index: i, result: outcome.value };
|
|
382
|
-
}
|
|
383
|
-
const raw = outcome.reason;
|
|
384
|
-
const error = raw instanceof agent_sdk_error_1.AgentSdkError
|
|
385
|
-
? raw
|
|
386
|
-
: new agent_sdk_error_1.AgentSdkError({
|
|
387
|
-
code: "execution_error",
|
|
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
|
-
}),
|
|
394
|
-
});
|
|
395
|
-
return { success: false, name: call.name, index: i, error };
|
|
396
|
-
});
|
|
397
|
-
}
|
|
398
|
-
}
|
|
399
|
-
// ── Safe convenience methods ────────────────────────────────────────────
|
|
400
|
-
/** Natural language query via ask_bot. Use `chat_id` to maintain conversation continuity. */
|
|
401
|
-
async askBot(args) {
|
|
402
|
-
return this.callTool("ask_bot", args);
|
|
403
|
-
}
|
|
404
|
-
/** High-level runtime/auth status endpoint. */
|
|
405
|
-
async agentStatus() {
|
|
406
|
-
return this.callTool("agent_status", {});
|
|
407
|
-
}
|
|
408
|
-
/** Deterministic readiness/config/source-health diagnosis. */
|
|
409
|
-
async agentReadinessReport(args = {}) {
|
|
410
|
-
return this.callTool("agent_readiness_report", args);
|
|
411
|
-
}
|
|
412
|
-
/** Safe portfolio/runtime snapshot with source-health caveats. */
|
|
413
|
-
async agentContextSnapshot(args = {}) {
|
|
414
|
-
return this.callTool("agent_context_snapshot", args);
|
|
415
|
-
}
|
|
416
|
-
/** Safe broad market brief for discovery tasks. */
|
|
417
|
-
async agentMarketBrief(args = {}) {
|
|
418
|
-
return this.callTool("agent_market_brief", args);
|
|
419
|
-
}
|
|
420
|
-
/** Safe report for one specific token, mint, contract, symbol, or name. */
|
|
421
|
-
async agentCandidateReport(args) {
|
|
422
|
-
return this.callTool("agent_candidate_report", args);
|
|
423
|
-
}
|
|
424
|
-
/** Safe risk report for one specific token, mint, contract, symbol, or name. */
|
|
425
|
-
async agentRiskReport(args) {
|
|
426
|
-
return this.callTool("agent_risk_report", args);
|
|
427
|
-
}
|
|
428
|
-
/**
|
|
429
|
-
* Read an MCP resource by URI (JSON-RPC `resources/read`).
|
|
430
|
-
* Returns the raw contents array. Callers extract `.text` from the first item.
|
|
431
|
-
*/
|
|
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
|
-
}
|
|
436
|
-
const result = await this.rpc('resources/read', { uri });
|
|
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;
|
|
455
|
-
}
|
|
456
|
-
/**
|
|
457
|
-
* @deprecated Seed pool is disabled. Fund custodial wallet via dashboard or on-chain transfer.
|
|
458
|
-
* Kept for backward compatibility; always throws a deterministic SDK error.
|
|
459
|
-
*/
|
|
460
|
-
async requestSeed(args) {
|
|
461
|
-
void args;
|
|
462
|
-
throw new agent_sdk_error_1.AgentSdkError({
|
|
463
|
-
code: "execution_error",
|
|
464
|
-
message: "agent_seed_request is disabled. Fund custodial wallet via dashboard or on-chain transfer.",
|
|
465
|
-
details: {
|
|
466
|
-
tool: "agent_seed_request",
|
|
467
|
-
disabled: true,
|
|
468
|
-
},
|
|
469
|
-
});
|
|
470
|
-
}
|
|
471
|
-
// ── Internal ─────────────────────────────────────────────────────────────
|
|
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) => {
|
|
480
|
-
const controller = new AbortController();
|
|
481
|
-
const timeout = globalThis.setTimeout(() => controller.abort(), Math.max(1, Math.min(this.timeoutMs, attempt.remainingDeadlineMs)));
|
|
482
|
-
try {
|
|
483
|
-
const requestId = crypto.randomUUID();
|
|
484
|
-
const body = this.serializeRequestBody({
|
|
485
|
-
jsonrpc: "2.0",
|
|
486
|
-
id: requestId,
|
|
487
|
-
method,
|
|
488
|
-
params,
|
|
489
|
-
});
|
|
490
|
-
const response = await this.fetchFn(this.endpoint, {
|
|
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",
|
|
495
|
-
headers: {
|
|
496
|
-
"Content-Type": "application/json",
|
|
497
|
-
Accept: "application/json, text/event-stream",
|
|
498
|
-
Authorization: `Bearer ${this.apiKey}`,
|
|
499
|
-
...options?.headers,
|
|
500
|
-
},
|
|
501
|
-
body,
|
|
502
|
-
signal: controller.signal,
|
|
503
|
-
});
|
|
504
|
-
const payload = await this.parseJsonRpc(response, requestId);
|
|
505
|
-
if (this.isJsonRpcError(payload)) {
|
|
506
|
-
throw this.mapRpcError(response, payload.error);
|
|
507
|
-
}
|
|
508
|
-
if (!response.ok) {
|
|
509
|
-
throw this.mapHttpError(response, payload.result);
|
|
510
|
-
}
|
|
511
|
-
return payload.result;
|
|
512
|
-
}
|
|
513
|
-
catch (error) {
|
|
514
|
-
if (error instanceof agent_sdk_error_1.AgentSdkError) {
|
|
515
|
-
throw error;
|
|
516
|
-
}
|
|
517
|
-
throw this.mapNetworkError(error, "MCP request failed");
|
|
518
|
-
}
|
|
519
|
-
finally {
|
|
520
|
-
globalThis.clearTimeout(timeout);
|
|
521
|
-
}
|
|
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"));
|
|
526
|
-
}
|
|
527
|
-
resolveRetryOptions(retryPolicy) {
|
|
528
|
-
if (retryPolicy === "protected") {
|
|
529
|
-
return {
|
|
530
|
-
...this.retryOptions,
|
|
531
|
-
maxAttempts: 1,
|
|
532
|
-
shouldRetry: () => false,
|
|
533
|
-
};
|
|
534
|
-
}
|
|
535
|
-
return {
|
|
536
|
-
...this.retryOptions,
|
|
537
|
-
shouldRetry: this.retryOptions.shouldRetry
|
|
538
|
-
?? ((error) => (0, retry_1.defaultShouldRetry)(error)),
|
|
539
|
-
};
|
|
540
|
-
}
|
|
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);
|
|
736
|
-
if (!raw) {
|
|
737
|
-
throw new agent_sdk_error_1.AgentSdkError({
|
|
738
|
-
code: "invalid_response",
|
|
739
|
-
status: response.status,
|
|
740
|
-
message: "Empty MCP response",
|
|
741
|
-
});
|
|
742
|
-
}
|
|
743
|
-
const normalized = this.extractSsePayload(raw);
|
|
744
|
-
try {
|
|
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;
|
|
750
|
-
}
|
|
751
|
-
catch {
|
|
752
|
-
throw new agent_sdk_error_1.AgentSdkError({
|
|
753
|
-
code: "invalid_response",
|
|
754
|
-
status: response.status,
|
|
755
|
-
message: "Invalid JSON-RPC payload",
|
|
756
|
-
details: (0, failure_metadata_1.buildFailureDetails)({
|
|
757
|
-
layer: "mcp_ingress",
|
|
758
|
-
code: "INVALID_RESPONSE",
|
|
759
|
-
retryable: false,
|
|
760
|
-
}),
|
|
761
|
-
});
|
|
762
|
-
}
|
|
763
|
-
}
|
|
764
|
-
extractSsePayload(raw) {
|
|
765
|
-
const lines = raw
|
|
766
|
-
.split("\n")
|
|
767
|
-
.map((line) => line.trim())
|
|
768
|
-
.filter((line) => line.startsWith("data:"));
|
|
769
|
-
if (lines.length === 0) {
|
|
770
|
-
return raw;
|
|
771
|
-
}
|
|
772
|
-
return lines.map((line) => line.replace(/^data:\s*/, "")).join("\n");
|
|
773
|
-
}
|
|
774
|
-
isJsonRpcError(payload) {
|
|
775
|
-
return (typeof payload === "object" &&
|
|
776
|
-
payload !== null &&
|
|
777
|
-
"error" in payload);
|
|
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
|
-
}
|
|
839
|
-
}
|
|
840
|
-
exports.BalchemyMcpClient = BalchemyMcpClient;
|
|
841
|
-
const connectMcp = (config) => {
|
|
842
|
-
return new BalchemyMcpClient(config);
|
|
843
|
-
};
|
|
844
|
-
exports.connectMcp = connectMcp;
|
|
845
|
-
//# sourceMappingURL=mcp-client.js.map
|