@pgnio/helios-mcp 0.2.9 → 0.5.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.
@@ -1,3084 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
4
-
5
- // ../../node_modules/.pnpm/tsup@8.5.1_jiti@2.6.1_postcss@8.5.6_tsx@4.20.6_typescript@5.9.3_yaml@2.8.2/node_modules/tsup/assets/esm_shims.js
6
- import path from "path";
7
- import { fileURLToPath } from "url";
8
- var getFilename = () => fileURLToPath(import.meta.url);
9
- var getDirname = () => path.dirname(getFilename());
10
- var __dirname = /* @__PURE__ */ getDirname();
11
-
12
- // ../agent/dist/index.mjs
13
- import { z } from "zod";
14
- import { z as z2 } from "zod";
15
- import { z as z3 } from "zod";
16
- var __defProp2 = Object.defineProperty;
17
- var __defNormalProp2 = (obj, key, value) => key in obj ? __defProp2(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
18
- var __publicField2 = (obj, key, value) => __defNormalProp2(obj, typeof key !== "symbol" ? key + "" : key, value);
19
- var AGENT_SCOPES = {
20
- ACCOUNT_READ: "account:read",
21
- MARKET_READ: "market:read",
22
- ORDERS_WRITE: "orders:write",
23
- ORDERS_CANCEL: "orders:cancel"
24
- };
25
- var AGENT_SCOPE_VALUES = [
26
- AGENT_SCOPES.ACCOUNT_READ,
27
- AGENT_SCOPES.MARKET_READ,
28
- AGENT_SCOPES.ORDERS_WRITE,
29
- AGENT_SCOPES.ORDERS_CANCEL
30
- ];
31
- var agentScopeSchema = z.enum(AGENT_SCOPE_VALUES);
32
- var agentGrantStatusSchema = z.enum(["active", "revoked"]);
33
- var agentDeviceRequestStatusSchema = z.enum(["pending", "approved", "rejected", "exchanged", "expired"]);
34
- var agentConstraintsSchema = z.record(z.string(), z.unknown()).default({});
35
- var agentGrantMetadataSchema = z.object({
36
- id: z.string(),
37
- userId: z.string(),
38
- clientName: z.string(),
39
- status: agentGrantStatusSchema,
40
- scope: z.array(agentScopeSchema).min(1),
41
- constraints: agentConstraintsSchema,
42
- tokenVersion: z.number().int().nonnegative(),
43
- createdAt: z.string(),
44
- approvedAt: z.string().optional(),
45
- lastUsedAt: z.string().optional(),
46
- revokedAt: z.string().optional()
47
- });
48
- var agentDeviceStartInputSchema = z.object({
49
- clientName: z.string().min(1).max(64),
50
- scope: z.array(agentScopeSchema).min(1),
51
- constraints: agentConstraintsSchema.optional()
52
- });
53
- var agentDeviceStartOutputSchema = z.object({
54
- deviceCode: z.string(),
55
- userCode: z.string(),
56
- verificationUri: z.string().url(),
57
- verificationUriComplete: z.string().url(),
58
- expiresInSeconds: z.number().int().positive(),
59
- pollIntervalSeconds: z.number().int().positive()
60
- });
61
- var agentDeviceTokenInputSchema = z.object({
62
- deviceCode: z.string().min(1)
63
- });
64
- var agentDeviceRequestViewSchema = z.object({
65
- userCode: z.string(),
66
- clientName: z.string(),
67
- scope: z.array(agentScopeSchema).min(1),
68
- constraints: agentConstraintsSchema,
69
- status: agentDeviceRequestStatusSchema,
70
- expiresAt: z.string()
71
- });
72
- var agentTokenResponseSchema = z.object({
73
- accessToken: z.string(),
74
- refreshToken: z.string(),
75
- tokenType: z.literal("Bearer"),
76
- expiresInSeconds: z.number().int().positive(),
77
- scope: z.array(agentScopeSchema).min(1),
78
- ownerUserId: z.string(),
79
- agentGrantId: z.string()
80
- });
81
- var agentRefreshInputSchema = z.object({
82
- refreshToken: z.string().min(1)
83
- });
84
- var agentApprovalResponseSchema = z.object({
85
- request: agentDeviceRequestViewSchema,
86
- grant: agentGrantMetadataSchema
87
- });
88
- var agentSessionStateSchema = z.object({
89
- status: z.enum(["pending", "authorized", "rejected", "revoked"]),
90
- request: agentDeviceRequestViewSchema.optional(),
91
- grant: agentGrantMetadataSchema.optional()
92
- });
93
- var providerSchema = z.enum(["hyperliquid"]);
94
- var walletStateSchema = z.object({
95
- provider: z.literal("hyperliquid"),
96
- accountValue: z.number(),
97
- availableBalance: z.number(),
98
- withdrawable: z.number(),
99
- totalMarginUsed: z.number(),
100
- totalNotionalPosition: z.number(),
101
- crossMarginAccountValue: z.number(),
102
- isActivated: z.boolean(),
103
- fetchedAt: z.string().datetime()
104
- });
105
- var openPositionSchema = z.object({
106
- symbol: z.string(),
107
- side: z.enum(["LONG", "SHORT"]),
108
- size: z.number(),
109
- entryPrice: z.number(),
110
- markPrice: z.number(),
111
- unrealizedPnl: z.number(),
112
- margin: z.number(),
113
- leverage: z.number(),
114
- liquidationPrice: z.number().optional()
115
- });
116
- var openPositionsSnapshotSchema = z.object({
117
- provider: z.literal("hyperliquid"),
118
- fetchedAt: z.string().datetime(),
119
- totalUnrealizedPnl: z.number(),
120
- positions: z.array(openPositionSchema)
121
- });
122
- var protectiveOrderKindSchema = z.enum(["STOP_LOSS", "TAKE_PROFIT"]);
123
- var protectiveOrderSideSchema = z.enum(["BUY", "SELL"]);
124
- var protectiveOrderPositionSideSchema = z.enum(["BOTH", "LONG", "SHORT"]);
125
- var protectiveOrderSchema = z.object({
126
- /** Helios's record id: what helios_positions_delete_tp_sl takes (the Hyperliquid order id works there too). */
127
- id: z.string(),
128
- /** The Hyperliquid order id (named after the retired Binance field). */
129
- binanceOrderId: z.number().int().nonnegative().nullish(),
130
- clientOrderId: z.string().nullish(),
131
- symbol: z.string(),
132
- side: protectiveOrderSideSchema,
133
- positionSide: protectiveOrderPositionSideSchema.nullish().transform((value) => value ?? "BOTH"),
134
- status: z.string(),
135
- kind: protectiveOrderKindSchema,
136
- groupId: z.string().nullish(),
137
- stopPrice: z.union([z.string(), z.number()]).nullish().transform((value) => value == null ? value : String(value)),
138
- parentClientOrderId: z.string().nullish(),
139
- assetId: z.number().int().nonnegative().nullish(),
140
- createdAt: z.string().nullish()
141
- });
142
- var hyperliquidPortfolioSnapshotSchema = z.object({
143
- provider: z.literal("hyperliquid"),
144
- totalBalance: z.number(),
145
- availableBalance: z.number(),
146
- totalMargin: z.number(),
147
- unrealizedPnl: z.number(),
148
- positions: z.array(openPositionSchema),
149
- /** Unreadable entries are dropped (see readProtectiveOrders) rather than failing the read. */
150
- protectiveOrders: z.array(protectiveOrderSchema)
151
- });
152
- var portfolioInputSchema = z.object({
153
- provider: providerSchema
154
- });
155
- var portfolioSnapshotSchema = hyperliquidPortfolioSnapshotSchema;
156
- var ledgerWindowSchema = z.enum(["24h", "7d", "30d"]);
157
- var ledgerFillsInputSchema = z.object({
158
- window: ledgerWindowSchema.optional(),
159
- limit: z.number().int().positive().max(200).optional(),
160
- before: z.number().int().nonnegative().optional()
161
- });
162
- var ledgerFillSchema = z.object({
163
- coin: z.string(),
164
- px: z.number(),
165
- sz: z.number(),
166
- side: z.enum(["B", "A"]),
167
- time: z.number().int().nonnegative(),
168
- dir: z.string(),
169
- closedPnl: z.number(),
170
- fee: z.number(),
171
- crossed: z.boolean(),
172
- oid: z.number().int().nonnegative(),
173
- tid: z.number().int().nonnegative()
174
- });
175
- var ledgerFillsPageSchema = z.object({
176
- window: ledgerWindowSchema,
177
- limit: z.number().int().positive(),
178
- before: z.number().int().nonnegative().optional(),
179
- hasMore: z.boolean(),
180
- nextBefore: z.number().int().nonnegative().optional(),
181
- fetchedAt: z.string().datetime(),
182
- fills: z.array(ledgerFillSchema)
183
- });
184
- var ledgerPeriodSummarySchema = z.object({
185
- realizedPnl: z.number(),
186
- totalFees: z.number(),
187
- fillCount: z.number().int().nonnegative(),
188
- closeCount: z.number().int().nonnegative(),
189
- winCount: z.number().int().nonnegative(),
190
- lossCount: z.number().int().nonnegative(),
191
- averageWin: z.number(),
192
- averageLoss: z.number()
193
- });
194
- var ledgerSummaryInputSchema = z.object({
195
- window: ledgerWindowSchema.optional()
196
- });
197
- var ledgerSummarySchema = ledgerPeriodSummarySchema.extend({
198
- window: ledgerWindowSchema,
199
- generatedAt: z.string().datetime(),
200
- periods: z.object({
201
- "24h": ledgerPeriodSummarySchema,
202
- "7d": ledgerPeriodSummarySchema
203
- })
204
- });
205
- var marketSnapshotScopeSchema = z.enum(["selected", "all"]);
206
- var marketSnapshotResolvedScopeSchema = z.enum(["selected", "all", "explicit"]);
207
- var marketSnapshotValueSchema = z.union([z.string(), z.number(), z.boolean(), z.null()]);
208
- var marketSnapshotInputSchema = z.object({
209
- scope: marketSnapshotScopeSchema.optional(),
210
- symbols: z.array(z.string().min(1)).min(1).optional(),
211
- fields: z.array(z.string().min(1)).min(1).optional().describe("Table columns to return; sym and base always come back. Ids: rank, lp, bv, qv, ts, r1m, r3m, r5m, r15m, r30m, r1h, r2h, r4h, r6h, r8h, r12h, r24h, r3d, r7d, hmi, hmiv, reg, ob, de, hfi, ar, ms, vcc, vcp, obosd, obosp, vwap, vwz, poc, pocd, vap, macdh, macds, macdd, srs, srr, fh24, fl24, fh7, fl7, sr, az, hfiw, trv, tri, trh, hs."),
212
- sort: z.enum(["rank"]).optional().describe('"rank" orders rows by market cap rank, unranked last.')
213
- });
214
- var marketSnapshotChunkInputSchema = marketSnapshotInputSchema.extend({
215
- offset: z.number().int().nonnegative().optional(),
216
- limit: z.number().int().positive().max(100).optional()
217
- });
218
- var marketFieldBlockSchema = z.object({
219
- fieldIds: z.array(z.string()).min(1),
220
- values: z.array(marketSnapshotValueSchema),
221
- symbolLists: z.record(z.string(), z.array(z.string())).optional()
222
- });
223
- var marketMatrixSchema = z.object({
224
- fieldIds: z.array(z.string()).min(1),
225
- rows: z.array(z.array(marketSnapshotValueSchema))
226
- });
227
- var marketFieldSemanticsSchema = z.object({
228
- nullMeans: z.literal("unavailable"),
229
- percentScale: z.literal("already_percent"),
230
- percentFields: z.array(z.string()).min(1),
231
- changeMapPercentKeys: z.array(z.string()).min(1)
232
- });
233
- var marketSnapshotSchema = z.object({
234
- schema: z.literal("helios.market_snapshot.v1"),
235
- view: z.literal("market_overview"),
236
- scope: marketSnapshotResolvedScopeSchema,
237
- symbolCount: z.number().int().nonnegative(),
238
- generatedAt: z.string().datetime(),
239
- returnedSymbols: z.array(z.string()),
240
- semantics: marketFieldSemanticsSchema,
241
- market: marketFieldBlockSchema,
242
- table: marketMatrixSchema,
243
- legend: z.record(z.string(), z.union([z.string(), z.array(z.string())]))
244
- });
245
- var marketSnapshotChunkSchema = z.object({
246
- schema: z.literal("helios.market_snapshot_chunk.v1"),
247
- view: z.literal("market_overview_chunk"),
248
- scope: marketSnapshotResolvedScopeSchema,
249
- totalSymbolCount: z.number().int().nonnegative(),
250
- generatedAt: z.string().datetime(),
251
- offset: z.number().int().nonnegative(),
252
- limit: z.number().int().positive(),
253
- chunkSymbolCount: z.number().int().nonnegative(),
254
- hasMore: z.boolean(),
255
- nextOffset: z.number().int().nonnegative().optional(),
256
- returnedSymbols: z.array(z.string()),
257
- semantics: marketFieldSemanticsSchema,
258
- market: marketFieldBlockSchema,
259
- table: marketMatrixSchema,
260
- legend: z.record(z.string(), z.union([z.string(), z.array(z.string())]))
261
- });
262
- var marketSymbolDetailInputSchema = z.object({
263
- symbol: z.string().min(1),
264
- full: z.boolean().optional().describe("true adds every raw indicator and the price history (large, ~25 KB). Omit for the compact row and market context.")
265
- });
266
- var marketSymbolDetailSchema = z.object({
267
- schema: z.literal("helios.market_symbol_detail.v1"),
268
- generatedAt: z.string().datetime(),
269
- symbol: z.string(),
270
- semantics: marketFieldSemanticsSchema,
271
- market: marketFieldBlockSchema,
272
- row: z.record(z.string(), marketSnapshotValueSchema),
273
- symbolCtx: z.record(z.string(), marketSnapshotValueSchema),
274
- changeMap: z.record(z.string(), z.number().nullable()),
275
- metrics: z.record(z.string(), z.unknown()).nullable(),
276
- legend: z.record(z.string(), z.union([z.string(), z.array(z.string())]))
277
- });
278
- var tradingDirectionSchema = z.enum(["LONG", "SHORT"]);
279
- var tradingExecutionStyleSchema = z.enum(["MARKET", "LIMIT_TAKER", "LIMIT_MAKER", "LIMIT_GTC"]);
280
- var tradingSizeSchema = z.object({
281
- mode: z.enum(["MARGIN_USD", "BASE_QUANTITY"]),
282
- value: z.number().positive()
283
- });
284
- var tradingProtectionLegSchema = z.object({
285
- kind: z.enum(["LIMIT", "MARKET"]),
286
- triggerPrice: z.number().positive(),
287
- limitPrice: z.number().positive().optional()
288
- });
289
- var tradingProtectionSchema = z.object({
290
- takeProfit: tradingProtectionLegSchema.optional(),
291
- stopLoss: tradingProtectionLegSchema.optional()
292
- });
293
- var tradeIntentTypeSchema = z.enum(["OPEN", "DCA", "REVERSE", "CLOSE"]);
294
- var submitTradeIntentInputSchema = z.object({
295
- provider: providerSchema.optional(),
296
- symbol: z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
297
- intentType: tradeIntentTypeSchema,
298
- direction: tradingDirectionSchema,
299
- size: tradingSizeSchema,
300
- execution: z.object({
301
- style: tradingExecutionStyleSchema,
302
- timeInForce: z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
303
- limitPrice: z.number().positive().optional()
304
- }),
305
- maxSlippageBps: z.number().int().nonnegative().max(1e3).optional(),
306
- leverageOverride: z.number().positive().optional(),
307
- marginModeOverride: z.enum(["ISOLATED", "CROSS"]).optional(),
308
- reduceOnly: z.boolean().optional(),
309
- protection: tradingProtectionSchema.optional(),
310
- /** One per user action, reused on retries: the data-bridge never places a second order for the same key. */
311
- idempotencyKey: z.string().regex(/^[A-Za-z0-9_-]{8,64}$/).optional()
312
- });
313
- var submitTradeIntentResultSchema = z.object({
314
- status: z.literal("submitted"),
315
- /** `replayed`: an earlier attempt of this action already placed the order; nothing new was sent. */
316
- outcome: z.enum(["placed", "replayed"]).optional(),
317
- clientOrderId: z.string().optional(),
318
- orderStatus: z.string().optional(),
319
- /** TP/SL legs Hyperliquid refused while the entry went through: the position is open without them. */
320
- rejectedProtection: z.array(z.object({ kind: z.string(), reason: z.string() })).optional(),
321
- provider: providerSchema.optional(),
322
- symbol: z.string(),
323
- intentType: tradeIntentTypeSchema,
324
- direction: tradingDirectionSchema,
325
- size: tradingSizeSchema,
326
- execution: z.object({
327
- style: tradingExecutionStyleSchema,
328
- timeInForce: z.enum(["GTC", "IOC", "FOK", "GTX"]).optional(),
329
- limitPrice: z.number().positive().optional()
330
- }),
331
- maxSlippageBps: z.number().int().nonnegative().max(1e3).optional(),
332
- leverageOverride: z.number().positive().optional(),
333
- marginModeOverride: z.enum(["ISOLATED", "CROSS"]).optional(),
334
- reduceOnly: z.boolean(),
335
- hasProtection: z.boolean()
336
- });
337
- var closePositionInputSchema = z.object({
338
- provider: providerSchema.optional(),
339
- symbol: z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
340
- maxSlippageBps: z.number().int().nonnegative().max(1e3).optional()
341
- });
342
- var closePositionResultSchema = z.object({
343
- status: z.literal("submitted"),
344
- /** `no_position`: nothing was open on this coin, so no order was sent. Absent from older data-bridges. */
345
- outcome: z.enum(["closed", "no_position"]).optional(),
346
- provider: providerSchema.optional(),
347
- symbol: z.string(),
348
- mode: z.literal("FULL"),
349
- maxSlippageBps: z.number().int().nonnegative().max(1e3).optional()
350
- });
351
- var setTpSlInputSchema = z.object({
352
- provider: providerSchema.optional(),
353
- symbol: z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
354
- applyTo: z.enum(["FULL_POSITION", "CUSTOM_QUANTITY"]),
355
- quantity: z.number().positive().optional(),
356
- parentClientOrderId: z.string(),
357
- takeProfit: tradingProtectionLegSchema.optional(),
358
- stopLoss: tradingProtectionLegSchema.optional()
359
- });
360
- var setTpSlResultSchema = z.object({
361
- status: z.literal("submitted"),
362
- provider: providerSchema.optional(),
363
- symbol: z.string(),
364
- applyTo: z.enum(["FULL_POSITION", "CUSTOM_QUANTITY"]),
365
- quantity: z.number().positive().optional(),
366
- parentClientOrderId: z.string(),
367
- hasTakeProfit: z.boolean(),
368
- hasStopLoss: z.boolean()
369
- });
370
- var deleteTpSlInputSchema = z.object({
371
- provider: providerSchema.optional(),
372
- symbol: z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
373
- orderId: z.string()
374
- });
375
- var deleteTpSlResultSchema = z.object({
376
- status: z.literal("deleted"),
377
- provider: providerSchema.optional(),
378
- symbol: z.string(),
379
- orderId: z.string()
380
- });
381
- var openOrderSchema = z.object({
382
- coin: z.string(),
383
- side: z.enum(["B", "A"]),
384
- limitPx: z.string(),
385
- sz: z.string(),
386
- oid: z.number().int().nonnegative(),
387
- timestamp: z.number().int().nonnegative(),
388
- origSz: z.string(),
389
- orderType: z.string(),
390
- tif: z.string().nullable(),
391
- reduceOnly: z.boolean(),
392
- isTrigger: z.boolean(),
393
- triggerPx: z.string(),
394
- cloid: z.string().nullable(),
395
- assetId: z.number().int().nonnegative().optional()
396
- });
397
- var cancelOrderInputSchema = z.object({
398
- symbol: z.string().regex(/^[a-zA-Z0-9]+(?:USDT)?$/),
399
- oid: z.number().int().nonnegative()
400
- });
401
- var cancelOrderResultSchema = z.object({
402
- status: z.literal("cancelled"),
403
- symbol: z.string(),
404
- oid: z.number().int().nonnegative()
405
- });
406
- var heliosAgentErrorResponseSchema = z2.object({
407
- error: z2.string().optional(),
408
- errorDescription: z2.string().optional(),
409
- message: z2.string().optional()
410
- });
411
- var HeliosAgentApiError = class extends Error {
412
- constructor(options) {
413
- super(options.message);
414
- __publicField2(this, "status");
415
- __publicField2(this, "code");
416
- __publicField2(this, "errorDescription");
417
- __publicField2(this, "payload");
418
- this.name = "HeliosAgentApiError";
419
- this.status = options.status;
420
- this.code = options.code;
421
- this.errorDescription = options.errorDescription;
422
- this.payload = options.payload;
423
- if (options.cause !== void 0) {
424
- Object.defineProperty(this, "cause", {
425
- configurable: true,
426
- enumerable: false,
427
- value: options.cause,
428
- writable: true
429
- });
430
- }
431
- }
432
- };
433
- function isHeliosAgentApiError(error) {
434
- return error instanceof HeliosAgentApiError;
435
- }
436
- var HeliosAgentAuthClient = class {
437
- constructor(options) {
438
- __publicField2(this, "baseUrl");
439
- __publicField2(this, "fetchImpl");
440
- __publicField2(this, "headers");
441
- this.baseUrl = options.baseUrl.replace(/\/+$/, "");
442
- this.fetchImpl = options.fetch ?? fetch;
443
- this.headers = options.headers ?? {};
444
- }
445
- async startLogin(input) {
446
- const parsed = agentDeviceStartInputSchema.parse(input);
447
- return this.post("/api/agents/device/start", parsed, agentDeviceStartOutputSchema);
448
- }
449
- async exchangeDeviceCode(deviceCode) {
450
- const parsed = agentDeviceStartOutputSchema.shape.deviceCode.parse(deviceCode);
451
- return this.post("/api/agents/device/token", { deviceCode: parsed }, agentTokenResponseSchema);
452
- }
453
- async refreshSession(refreshToken) {
454
- const parsed = agentRefreshInputSchema.parse({ refreshToken });
455
- return this.post("/api/agents/auth/refresh", parsed, agentTokenResponseSchema);
456
- }
457
- async post(path4, body, schema) {
458
- let response;
459
- try {
460
- response = await this.fetchImpl(`${this.baseUrl}${path4}`, {
461
- method: "POST",
462
- headers: {
463
- Accept: "application/json",
464
- "Content-Type": "application/json",
465
- ...this.headers
466
- },
467
- body: JSON.stringify(body)
468
- });
469
- } catch (error) {
470
- throw new HeliosAgentApiError({
471
- status: 0,
472
- code: "network_error",
473
- message: error instanceof Error ? error.message : "Network error",
474
- cause: error
475
- });
476
- }
477
- const payload = await this.parseJson(response);
478
- if (!response.ok) {
479
- const parsed = heliosAgentErrorResponseSchema.safeParse(payload);
480
- throw new HeliosAgentApiError({
481
- status: response.status,
482
- code: parsed.success ? parsed.data.error ?? "request_failed" : "request_failed",
483
- message: parsed.success ? parsed.data.errorDescription ?? parsed.data.message ?? `Request failed with status ${response.status}` : `Request failed with status ${response.status}`,
484
- errorDescription: parsed.success ? parsed.data.errorDescription : void 0,
485
- payload
486
- });
487
- }
488
- return schema.parse(payload);
489
- }
490
- async parseJson(response) {
491
- const text = await response.text();
492
- if (!text) {
493
- return null;
494
- }
495
- try {
496
- return JSON.parse(text);
497
- } catch (error) {
498
- throw new HeliosAgentApiError({
499
- status: response.status,
500
- code: "invalid_json",
501
- message: "Received an invalid JSON response from Helios",
502
- cause: error
503
- });
504
- }
505
- }
506
- };
507
- var HeliosAgentDataBridgeClient = class {
508
- constructor(options) {
509
- __publicField2(this, "baseUrl");
510
- __publicField2(this, "fetchImpl");
511
- this.baseUrl = options.baseUrl.replace(/\/+$/, "");
512
- this.fetchImpl = options.fetch ?? fetch;
513
- }
514
- async getWalletState(accessToken) {
515
- const payload = await this.request(accessToken, "account.getWalletState");
516
- return walletStateSchema.parse(this.unwrapResult(payload));
517
- }
518
- async getOpenPositions(accessToken) {
519
- const payload = await this.request(accessToken, "positions.getOpen");
520
- return openPositionsSnapshotSchema.parse(this.unwrapResult(payload));
521
- }
522
- async getPortfolio(accessToken, input) {
523
- const parsedInput = portfolioInputSchema.parse(input);
524
- const payload = await this.request(accessToken, "positions.getPortfolio", parsedInput);
525
- const result = this.unwrapResult(payload);
526
- if (!result || typeof result !== "object" || Array.isArray(result)) {
527
- throw new HeliosAgentApiError({
528
- status: 200,
529
- code: "invalid_response",
530
- message: "Helios data bridge returned an invalid portfolio payload",
531
- payload
532
- });
533
- }
534
- return portfolioSnapshotSchema.parse({
535
- ...result,
536
- provider: parsedInput.provider,
537
- protectiveOrders: readProtectiveOrders(result.protectiveOrders)
538
- });
539
- }
540
- async getLedgerFills(accessToken, input = {}) {
541
- const parsedInput = ledgerFillsInputSchema.parse(input);
542
- const payload = await this.request(accessToken, "ledger.getFills", parsedInput);
543
- return ledgerFillsPageSchema.parse(this.unwrapResult(payload));
544
- }
545
- async getLedgerSummary(accessToken, input = {}) {
546
- const parsedInput = ledgerSummaryInputSchema.parse(input);
547
- const payload = await this.request(accessToken, "ledger.getSummary", parsedInput);
548
- return ledgerSummarySchema.parse(this.unwrapResult(payload));
549
- }
550
- async getMarketSnapshot(accessToken, input = {}) {
551
- const parsedInput = marketSnapshotInputSchema.parse(input);
552
- const payload = await this.request(accessToken, "market.getSnapshot", parsedInput);
553
- return marketSnapshotSchema.parse(this.unwrapResult(payload));
554
- }
555
- async getMarketSnapshotChunk(accessToken, input = {}) {
556
- const parsedInput = marketSnapshotChunkInputSchema.parse(input);
557
- const payload = await this.request(accessToken, "market.getSnapshotChunk", parsedInput);
558
- return marketSnapshotChunkSchema.parse(this.unwrapResult(payload));
559
- }
560
- async getMarketSymbolDetail(accessToken, input) {
561
- const parsedInput = marketSymbolDetailInputSchema.parse(input);
562
- const payload = await this.request(accessToken, "market.getSymbolDetail", parsedInput);
563
- return marketSymbolDetailSchema.parse(this.unwrapResult(payload));
564
- }
565
- async submitTradeIntent(accessToken, input) {
566
- const parsedInput = submitTradeIntentInputSchema.parse(input);
567
- const payload = await this.request(accessToken, "trading.submitIntent", parsedInput, "POST");
568
- const answer = this.unwrapResult(payload) ?? {};
569
- return submitTradeIntentResultSchema.parse({
570
- status: "submitted",
571
- ...answer.outcome === "placed" || answer.outcome === "replayed" ? { outcome: answer.outcome } : {},
572
- ...typeof answer.clientOrderId === "string" ? { clientOrderId: answer.clientOrderId } : {},
573
- ...typeof answer.orderStatus === "string" ? { orderStatus: answer.orderStatus } : {},
574
- ...Array.isArray(answer.rejectedProtection) ? { rejectedProtection: answer.rejectedProtection } : {},
575
- provider: parsedInput.provider,
576
- symbol: parsedInput.symbol,
577
- intentType: parsedInput.intentType,
578
- direction: parsedInput.direction,
579
- size: parsedInput.size,
580
- execution: parsedInput.execution,
581
- maxSlippageBps: parsedInput.maxSlippageBps,
582
- leverageOverride: parsedInput.leverageOverride,
583
- marginModeOverride: parsedInput.marginModeOverride,
584
- reduceOnly: Boolean(parsedInput.reduceOnly),
585
- hasProtection: Boolean(parsedInput.protection?.takeProfit || parsedInput.protection?.stopLoss)
586
- });
587
- }
588
- async closePosition(accessToken, input) {
589
- const parsedInput = closePositionInputSchema.parse(input);
590
- const payload = await this.request(
591
- accessToken,
592
- "positions.close",
593
- {
594
- ...parsedInput.provider !== void 0 ? { provider: parsedInput.provider } : {},
595
- symbol: parsedInput.symbol,
596
- mode: "FULL",
597
- ...parsedInput.maxSlippageBps !== void 0 ? { maxSlippageBps: parsedInput.maxSlippageBps } : {}
598
- },
599
- "POST"
600
- );
601
- const outcome = this.tryUnwrapResult(payload)?.outcome;
602
- return closePositionResultSchema.parse({
603
- status: "submitted",
604
- ...outcome === "closed" || outcome === "no_position" ? { outcome } : {},
605
- provider: parsedInput.provider,
606
- symbol: parsedInput.symbol,
607
- mode: "FULL",
608
- maxSlippageBps: parsedInput.maxSlippageBps
609
- });
610
- }
611
- async setTpSl(accessToken, input) {
612
- const parsedInput = setTpSlInputSchema.parse(input);
613
- await this.request(accessToken, "positions.setTpSl", parsedInput, "POST");
614
- return setTpSlResultSchema.parse({
615
- status: "submitted",
616
- provider: parsedInput.provider,
617
- symbol: parsedInput.symbol,
618
- applyTo: parsedInput.applyTo,
619
- quantity: parsedInput.quantity,
620
- parentClientOrderId: parsedInput.parentClientOrderId,
621
- hasTakeProfit: Boolean(parsedInput.takeProfit),
622
- hasStopLoss: Boolean(parsedInput.stopLoss)
623
- });
624
- }
625
- async deleteTpSl(accessToken, input) {
626
- const parsedInput = deleteTpSlInputSchema.parse(input);
627
- await this.request(accessToken, "positions.deleteTpSl", parsedInput, "POST");
628
- return deleteTpSlResultSchema.parse({
629
- status: "deleted",
630
- provider: parsedInput.provider,
631
- symbol: parsedInput.symbol,
632
- orderId: parsedInput.orderId
633
- });
634
- }
635
- async getOpenOrders(accessToken) {
636
- const payload = await this.request(accessToken, "positions.getOpenOrders");
637
- return openOrderSchema.array().parse(this.unwrapResult(payload));
638
- }
639
- async cancelOrder(accessToken, input) {
640
- const parsedInput = cancelOrderInputSchema.parse(input);
641
- await this.request(accessToken, "positions.cancelOrder", parsedInput, "POST");
642
- return cancelOrderResultSchema.parse({
643
- status: "cancelled",
644
- symbol: parsedInput.symbol,
645
- oid: parsedInput.oid
646
- });
647
- }
648
- async request(accessToken, procedure, input, method = "GET") {
649
- let response;
650
- try {
651
- response = await this.fetchImpl(this.buildProcedureUrl(procedure, method === "GET" ? input : void 0), {
652
- method,
653
- headers: {
654
- Accept: "application/json",
655
- ...method === "POST" ? { "Content-Type": "application/json" } : {},
656
- Authorization: `Bearer ${accessToken}`
657
- },
658
- ...method === "POST" && input !== void 0 ? { body: JSON.stringify({ json: input }) } : {}
659
- });
660
- } catch (error) {
661
- throw new HeliosAgentApiError({
662
- status: 0,
663
- code: "network_error",
664
- message: error instanceof Error ? error.message : "Network error",
665
- cause: error
666
- });
667
- }
668
- const payload = await this.parseJson(response);
669
- if (!response.ok) {
670
- throw new HeliosAgentApiError({
671
- status: response.status,
672
- code: this.extractErrorCode(payload),
673
- message: this.extractErrorMessage(payload, response.status),
674
- payload
675
- });
676
- }
677
- return payload;
678
- }
679
- buildProcedureUrl(procedure, input) {
680
- const url = new URL(`${this.baseUrl}/api/trpc/${procedure}`);
681
- if (input !== void 0) {
682
- url.searchParams.set("input", JSON.stringify({ json: input }));
683
- }
684
- return url.toString();
685
- }
686
- async parseJson(response) {
687
- const text = await response.text();
688
- if (!text) {
689
- return null;
690
- }
691
- try {
692
- return JSON.parse(text);
693
- } catch (error) {
694
- throw new HeliosAgentApiError({
695
- status: response.status,
696
- code: "invalid_json",
697
- message: "Received an invalid JSON response from Helios data bridge",
698
- cause: error
699
- });
700
- }
701
- }
702
- /** The result of a mutation older data-bridges answer with nothing; null when there is none. */
703
- tryUnwrapResult(payload) {
704
- try {
705
- return this.unwrapResult(payload) ?? null;
706
- } catch {
707
- return null;
708
- }
709
- }
710
- unwrapResult(payload) {
711
- if (!payload || typeof payload !== "object") {
712
- throw new HeliosAgentApiError({
713
- status: 200,
714
- code: "invalid_response",
715
- message: "Helios data bridge returned an invalid response payload",
716
- payload
717
- });
718
- }
719
- const result = payload.result;
720
- if (!result) {
721
- throw new HeliosAgentApiError({
722
- status: 200,
723
- code: "invalid_response",
724
- message: "Helios data bridge response is missing a result payload",
725
- payload
726
- });
727
- }
728
- const data = result.data;
729
- if (data && typeof data === "object" && "json" in data) {
730
- return data.json;
731
- }
732
- return data;
733
- }
734
- extractErrorCode(payload) {
735
- if (payload && typeof payload === "object") {
736
- const errorShape = this.unwrapTrpcError(payload);
737
- if (errorShape?.data?.code) {
738
- return errorShape.data.code;
739
- }
740
- }
741
- return "request_failed";
742
- }
743
- extractErrorMessage(payload, status) {
744
- if (payload && typeof payload === "object") {
745
- const errorShape = this.unwrapTrpcError(payload);
746
- if (errorShape?.message) {
747
- return errorShape.message;
748
- }
749
- }
750
- return `Request failed with status ${status}`;
751
- }
752
- /**
753
- * Unwrap a tRPC error envelope, handling the superjson `{ json: ... }` wrapper
754
- * that the data-bridge applies via its transformer configuration.
755
- */
756
- unwrapTrpcError(payload) {
757
- const envelope = payload.error;
758
- if (!envelope || typeof envelope !== "object") {
759
- return void 0;
760
- }
761
- if ("json" in envelope) {
762
- const inner = envelope.json;
763
- if (inner && typeof inner === "object") {
764
- return inner;
765
- }
766
- }
767
- return envelope;
768
- }
769
- };
770
- function readProtectiveOrders(value) {
771
- if (!Array.isArray(value)) return [];
772
- return value.flatMap((entry) => {
773
- const parsed = protectiveOrderSchema.safeParse(entry);
774
- return parsed.success ? [parsed.data] : [];
775
- });
776
- }
777
- var DEFAULT_AGENT_REFRESH_WINDOW_MS = 60 * 1e3;
778
- var agentConnectionStatusSchema = z3.enum([
779
- "disconnected",
780
- "pending",
781
- "connected",
782
- "rejected",
783
- "expired",
784
- "failed"
785
- ]);
786
- var storedAgentSessionSchema = z3.object({
787
- accessToken: z3.string(),
788
- refreshToken: z3.string(),
789
- tokenType: agentTokenResponseSchema.shape.tokenType,
790
- ownerUserId: z3.string(),
791
- agentGrantId: z3.string(),
792
- scope: z3.array(agentScopeSchema).min(1),
793
- accessTokenExpiresAt: z3.string().datetime(),
794
- createdAt: z3.string().datetime(),
795
- lastRefreshedAt: z3.string().datetime()
796
- });
797
- var agentSessionViewSchema = z3.object({
798
- connected: z3.boolean(),
799
- status: agentConnectionStatusSchema,
800
- ownerUserId: z3.string().optional(),
801
- agentGrantId: z3.string().optional(),
802
- scope: z3.array(agentScopeSchema).optional(),
803
- accessTokenExpiresAt: z3.string().datetime().optional(),
804
- lastRefreshedAt: z3.string().datetime().optional()
805
- });
806
- function createStoredAgentSession(tokenResponse, now = /* @__PURE__ */ new Date()) {
807
- const createdAt = now.toISOString();
808
- return {
809
- accessToken: tokenResponse.accessToken,
810
- refreshToken: tokenResponse.refreshToken,
811
- tokenType: tokenResponse.tokenType,
812
- ownerUserId: tokenResponse.ownerUserId,
813
- agentGrantId: tokenResponse.agentGrantId,
814
- scope: tokenResponse.scope,
815
- accessTokenExpiresAt: new Date(now.getTime() + tokenResponse.expiresInSeconds * 1e3).toISOString(),
816
- createdAt,
817
- lastRefreshedAt: createdAt
818
- };
819
- }
820
- function sanitizeAgentSession(session, status = session ? "connected" : "disconnected") {
821
- if (!session) {
822
- return {
823
- connected: false,
824
- status: status === "connected" ? "disconnected" : status
825
- };
826
- }
827
- return {
828
- connected: true,
829
- status,
830
- ownerUserId: session.ownerUserId,
831
- agentGrantId: session.agentGrantId,
832
- scope: session.scope,
833
- accessTokenExpiresAt: session.accessTokenExpiresAt,
834
- lastRefreshedAt: session.lastRefreshedAt
835
- };
836
- }
837
- function shouldRefreshAgentSession(session, now = /* @__PURE__ */ new Date(), refreshWindowMs = DEFAULT_AGENT_REFRESH_WINDOW_MS) {
838
- return new Date(session.accessTokenExpiresAt).getTime() - now.getTime() <= refreshWindowMs;
839
- }
840
-
841
- // src/auth-service.ts
842
- var HOSTED_RECONNECT_MESSAGE = "Helios no longer accepts this connection (it expired or was revoked). Reconnect Helios in your AI app to continue.";
843
- var HeliosAgentMcpAuthService = class {
844
- constructor(options) {
845
- __publicField(this, "client");
846
- __publicField(this, "sessionStore");
847
- __publicField(this, "refreshWindowMs");
848
- __publicField(this, "now");
849
- __publicField(this, "deviceLogin");
850
- this.client = options.client;
851
- this.sessionStore = options.sessionStore;
852
- this.refreshWindowMs = options.refreshWindowMs ?? 60 * 1e3;
853
- this.now = options.now ?? (() => /* @__PURE__ */ new Date());
854
- this.deviceLogin = options.deviceLogin ?? true;
855
- }
856
- async startLogin(input) {
857
- const response = await this.startDeviceLogin(input);
858
- const result = this.buildStartLoginResult(response, input.scope);
859
- await this.sessionStore.setPendingLogin(result);
860
- return result;
861
- }
862
- async resetSessionAndStartLogin(input) {
863
- await this.sessionStore.clearSession();
864
- await this.sessionStore.clearPendingLogin();
865
- const response = await this.startDeviceLogin(input);
866
- const result = this.buildStartLoginResult(response, input.scope);
867
- await this.sessionStore.setPendingLogin(result);
868
- return result;
869
- }
870
- async startDeviceLogin(input) {
871
- if (!this.deviceLogin) {
872
- throw new Error(HOSTED_RECONNECT_MESSAGE);
873
- }
874
- return this.client.startLogin(input);
875
- }
876
- buildStartLoginResult(response, requestedScope) {
877
- return {
878
- status: "pending",
879
- ...response,
880
- requestedScope,
881
- startedAt: this.now().toISOString()
882
- };
883
- }
884
- async startRelogin(options = {}) {
885
- const requestedScope = options.scope ?? [AGENT_SCOPES.ACCOUNT_READ, AGENT_SCOPES.MARKET_READ];
886
- const started = await this.resetSessionAndStartLogin({
887
- clientName: options.clientName ?? "Helios MCP",
888
- scope: requestedScope,
889
- constraints: options.constraints
890
- });
891
- return {
892
- ...started,
893
- connected: false,
894
- message: formatHeliosLoginPrompt(started)
895
- };
896
- }
897
- async clearSessionState() {
898
- await this.sessionStore.clearSession();
899
- await this.sessionStore.clearPendingLogin();
900
- }
901
- async invalidateIfUnauthorized(error, options = {}) {
902
- if (!isHeliosAgentApiError(error) || error.status !== 401) {
903
- return null;
904
- }
905
- return this.startRelogin(options);
906
- }
907
- async refreshSessionAfterUnauthorized(error) {
908
- if (!isHeliosAgentApiError(error) || error.status !== 401) {
909
- return null;
910
- }
911
- const session = await this.sessionStore.getSession();
912
- if (!session) {
913
- return null;
914
- }
915
- return this.refreshStoredSession(session);
916
- }
917
- async ensureLogin(options = {}) {
918
- const requestedScope = options.scope ?? [AGENT_SCOPES.ACCOUNT_READ, AGENT_SCOPES.MARKET_READ];
919
- const requestedConstraints = options.constraints ?? {};
920
- const session = await this.getValidSession();
921
- if (session) {
922
- return {
923
- ...sanitizeAgentSession(session),
924
- connected: true,
925
- status: "connected"
926
- };
927
- }
928
- const pendingLogin = await this.getPendingLogin({
929
- requestedScope,
930
- requestedConstraints
931
- });
932
- if (pendingLogin) {
933
- const polled = await this.pollLogin(pendingLogin.deviceCode).catch(() => null);
934
- if (polled?.status === "connected") return polled;
935
- if (polled?.status !== "rejected" && polled?.status !== "expired") {
936
- return {
937
- ...pendingLogin,
938
- connected: false,
939
- message: formatHeliosLoginPrompt(pendingLogin)
940
- };
941
- }
942
- }
943
- const started = await this.startLogin({
944
- clientName: options.clientName ?? "Helios MCP",
945
- scope: requestedScope,
946
- constraints: options.constraints
947
- });
948
- return {
949
- ...started,
950
- connected: false,
951
- message: formatHeliosLoginPrompt(started)
952
- };
953
- }
954
- /** Polls the given login, or the stored pending one when no device code is given. */
955
- async pollLogin(deviceCode) {
956
- if (!deviceCode) {
957
- const pending = await this.sessionStore.getPendingLogin();
958
- if (!pending) {
959
- const session = await this.getValidSession();
960
- if (session) return { ...sanitizeAgentSession(session), connected: true, status: "connected" };
961
- return {
962
- status: "failed",
963
- connected: false,
964
- message: "No Helios login is in progress. Call helios_auth_ensure_login to start one."
965
- };
966
- }
967
- deviceCode = pending.deviceCode;
968
- } else {
969
- const pending = await this.sessionStore.getPendingLogin();
970
- if (pending && pending.userCode.toUpperCase() === deviceCode.trim().toUpperCase()) deviceCode = pending.deviceCode;
971
- }
972
- try {
973
- const response = await this.client.exchangeDeviceCode(deviceCode);
974
- const session = createStoredAgentSession(response, this.now());
975
- await this.sessionStore.setSession(session);
976
- await this.sessionStore.clearPendingLogin();
977
- return {
978
- ...sanitizeAgentSession(session),
979
- connected: true,
980
- status: "connected"
981
- };
982
- } catch (error) {
983
- if (isHeliosAgentApiError(error)) {
984
- if (error.code === "authorization_pending") {
985
- return {
986
- status: "pending",
987
- connected: false,
988
- message: error.message
989
- };
990
- }
991
- if (error.code === "access_denied") {
992
- await this.clearPendingLoginIfMatches(deviceCode);
993
- return {
994
- status: "rejected",
995
- connected: false,
996
- message: error.message
997
- };
998
- }
999
- if (error.code === "expired_token") {
1000
- await this.clearPendingLoginIfMatches(deviceCode);
1001
- return {
1002
- status: "expired",
1003
- connected: false,
1004
- message: error.message
1005
- };
1006
- }
1007
- return {
1008
- status: "failed",
1009
- connected: false,
1010
- message: error.message
1011
- };
1012
- }
1013
- return {
1014
- status: "failed",
1015
- connected: false,
1016
- message: error instanceof Error ? error.message : "Unexpected Helios login error"
1017
- };
1018
- }
1019
- }
1020
- async whoami() {
1021
- const session = await this.getValidSession();
1022
- return sanitizeAgentSession(session);
1023
- }
1024
- async getAccessToken() {
1025
- const session = await this.getValidSession();
1026
- return session?.accessToken ?? null;
1027
- }
1028
- async requireSession() {
1029
- const session = await this.getValidSession();
1030
- if (!session) {
1031
- throw new Error("No Helios delegated agent session is connected");
1032
- }
1033
- return session;
1034
- }
1035
- async getValidSession() {
1036
- const session = await this.sessionStore.getSession();
1037
- if (!session) {
1038
- return null;
1039
- }
1040
- if (!shouldRefreshAgentSession(session, this.now(), this.refreshWindowMs)) {
1041
- return session;
1042
- }
1043
- return this.refreshStoredSession(session);
1044
- }
1045
- async refreshStoredSession(session) {
1046
- try {
1047
- const refreshed = await this.client.refreshSession(session.refreshToken);
1048
- const nextSession = createStoredAgentSession(refreshed, this.now());
1049
- await this.sessionStore.setSession(nextSession);
1050
- return nextSession;
1051
- } catch (error) {
1052
- if (isHeliosAgentApiError(error) && error.code === "invalid_grant") {
1053
- await this.sessionStore.clearSession();
1054
- await this.sessionStore.clearPendingLogin();
1055
- return null;
1056
- }
1057
- throw error;
1058
- }
1059
- }
1060
- async getPendingLogin(options) {
1061
- const pendingLogin = await this.sessionStore.getPendingLogin();
1062
- if (!pendingLogin) {
1063
- return null;
1064
- }
1065
- const expiresAt = new Date(pendingLogin.startedAt).getTime() + pendingLogin.expiresInSeconds * 1e3;
1066
- if (this.now().getTime() >= expiresAt) {
1067
- await this.sessionStore.clearPendingLogin();
1068
- return null;
1069
- }
1070
- if (!isPendingLoginCompatible(pendingLogin, options.requestedScope, options.requestedConstraints)) {
1071
- return null;
1072
- }
1073
- return pendingLogin;
1074
- }
1075
- async clearPendingLoginIfMatches(deviceCode) {
1076
- const pendingLogin = await this.sessionStore.getPendingLogin();
1077
- if (pendingLogin?.deviceCode === deviceCode) {
1078
- await this.sessionStore.clearPendingLogin();
1079
- }
1080
- }
1081
- };
1082
- async function retryAfterUnauthorizedRefresh(options) {
1083
- const refreshedSession = await options.authService.refreshSessionAfterUnauthorized(options.error);
1084
- if (!refreshedSession) {
1085
- return options.authService.invalidateIfUnauthorized(options.error, options.loginOptions);
1086
- }
1087
- try {
1088
- return await options.retry(refreshedSession.accessToken);
1089
- } catch (retryError) {
1090
- const relogin = await options.authService.invalidateIfUnauthorized(retryError, options.loginOptions);
1091
- if (relogin) {
1092
- return relogin;
1093
- }
1094
- throw retryError;
1095
- }
1096
- }
1097
- function formatHeliosLoginPrompt(result) {
1098
- return `Log in to Helios by opening this URL in your browser:
1099
-
1100
- ${result.verificationUriComplete}
1101
-
1102
- User code: ${result.userCode}
1103
-
1104
- Requested scopes: ${result.requestedScope.join(", ")}
1105
-
1106
- After approving access, call helios_auth_ensure_login (or helios_auth_poll_login) again to finish connecting.`;
1107
- }
1108
- function isPendingLoginCompatible(pendingLogin, requestedScope, requestedConstraints) {
1109
- const pendingScope = new Set(pendingLogin.requestedScope);
1110
- const scopeCompatible = requestedScope.every((scope) => pendingScope.has(scope));
1111
- if (!scopeCompatible) {
1112
- return false;
1113
- }
1114
- return Object.keys(requestedConstraints ?? {}).length === 0;
1115
- }
1116
-
1117
- // src/account-service.ts
1118
- var HeliosAgentMcpAccountService = class {
1119
- constructor(options) {
1120
- __publicField(this, "authService");
1121
- __publicField(this, "dataBridgeClient");
1122
- __publicField(this, "providerService");
1123
- this.authService = options.authService;
1124
- this.dataBridgeClient = options.dataBridgeClient;
1125
- this.providerService = options.providerService;
1126
- }
1127
- async getWalletState() {
1128
- const loginOptions = this.accountReadOptions();
1129
- const login = await this.authService.ensureLogin(loginOptions);
1130
- if (login.status !== "connected") {
1131
- return {
1132
- ...login,
1133
- status: "pending",
1134
- connected: false
1135
- };
1136
- }
1137
- const session = await this.authService.requireSession();
1138
- try {
1139
- const walletState = await this.dataBridgeClient.getWalletState(session.accessToken);
1140
- return {
1141
- status: "connected",
1142
- connected: true,
1143
- walletState
1144
- };
1145
- } catch (error) {
1146
- const recovery = await retryAfterUnauthorizedRefresh({
1147
- authService: this.authService,
1148
- error,
1149
- loginOptions,
1150
- retry: async (accessToken) => {
1151
- const walletState = await this.dataBridgeClient.getWalletState(accessToken);
1152
- return {
1153
- status: "connected",
1154
- connected: true,
1155
- walletState
1156
- };
1157
- }
1158
- });
1159
- if (recovery) {
1160
- return recovery;
1161
- }
1162
- throw error;
1163
- }
1164
- }
1165
- async getPortfolio(input = {}) {
1166
- const loginOptions = this.accountReadOptions();
1167
- const login = await this.authService.ensureLogin(loginOptions);
1168
- if (login.status !== "connected") {
1169
- return {
1170
- ...login,
1171
- status: "pending",
1172
- connected: false
1173
- };
1174
- }
1175
- const session = await this.authService.requireSession();
1176
- try {
1177
- const provider = await this.providerService.resolveProvider(input.provider);
1178
- const portfolio = await this.dataBridgeClient.getPortfolio(session.accessToken, { provider });
1179
- return {
1180
- status: "connected",
1181
- connected: true,
1182
- portfolio
1183
- };
1184
- } catch (error) {
1185
- const recovery = await retryAfterUnauthorizedRefresh({
1186
- authService: this.authService,
1187
- error,
1188
- loginOptions,
1189
- retry: async (accessToken) => {
1190
- const provider = await this.providerService.resolveProvider(input.provider);
1191
- const portfolio = await this.dataBridgeClient.getPortfolio(accessToken, { provider });
1192
- return {
1193
- status: "connected",
1194
- connected: true,
1195
- portfolio
1196
- };
1197
- }
1198
- });
1199
- if (recovery) {
1200
- return recovery;
1201
- }
1202
- throw error;
1203
- }
1204
- }
1205
- accountReadOptions() {
1206
- return {
1207
- clientName: "Helios MCP",
1208
- scope: [AGENT_SCOPES.ACCOUNT_READ]
1209
- };
1210
- }
1211
- };
1212
-
1213
- // src/docs-service.ts
1214
- import { existsSync, readdirSync, readFileSync, statSync } from "fs";
1215
- import path2 from "path";
1216
- var HeliosAgentMcpDocsService = class {
1217
- constructor(options) {
1218
- __publicField(this, "docsRoot");
1219
- this.docsRoot = options.docsRoot;
1220
- }
1221
- async getIndex() {
1222
- const documents = listDocumentPaths(this.docsRoot).map((documentPath) => this.readDocumentMetadata(documentPath));
1223
- return {
1224
- root: "docs",
1225
- documents
1226
- };
1227
- }
1228
- async getDocument(input) {
1229
- const documentPath = resolveDocumentPath(this.docsRoot, input.path);
1230
- if (!existsSync(documentPath) || !statSync(documentPath).isFile()) {
1231
- throw new Error(`No document "${input.path}". helios_docs_get_index lists the documents.`);
1232
- }
1233
- const body = readFileSync(documentPath, "utf8");
1234
- const stats = statSync(documentPath);
1235
- const relativePath = toPosixPath(path2.relative(this.docsRoot, documentPath));
1236
- return {
1237
- path: relativePath,
1238
- section: getDocumentSection(relativePath),
1239
- title: extractDocumentTitle(body, relativePath),
1240
- body,
1241
- bytes: stats.size
1242
- };
1243
- }
1244
- readDocumentMetadata(documentPath) {
1245
- const body = readFileSync(documentPath, "utf8");
1246
- const stats = statSync(documentPath);
1247
- const relativePath = toPosixPath(path2.relative(this.docsRoot, documentPath));
1248
- return {
1249
- path: relativePath,
1250
- section: getDocumentSection(relativePath),
1251
- title: extractDocumentTitle(body, relativePath),
1252
- bytes: stats.size
1253
- };
1254
- }
1255
- };
1256
- function getDefaultHeliosAgentMcpDocsRoot() {
1257
- return path2.resolve(__dirname, "..", "docs");
1258
- }
1259
- function listDocumentPaths(root) {
1260
- return walk(root).filter((filePath) => filePath.endsWith(".txt")).sort((left, right) => left.localeCompare(right));
1261
- }
1262
- function walk(currentPath) {
1263
- const entries = readdirSync(currentPath, { withFileTypes: true });
1264
- const files = [];
1265
- for (const entry of entries) {
1266
- const nextPath = path2.join(currentPath, entry.name);
1267
- if (entry.isDirectory()) {
1268
- files.push(...walk(nextPath));
1269
- continue;
1270
- }
1271
- if (entry.isFile()) {
1272
- files.push(nextPath);
1273
- }
1274
- }
1275
- return files;
1276
- }
1277
- function resolveDocumentPath(root, relativeDocumentPath) {
1278
- const normalizedPath = relativeDocumentPath.replace(/\\/g, "/").replace(/^\/+/, "");
1279
- const resolvedPath = path2.resolve(root, normalizedPath);
1280
- const relativePath = path2.relative(root, resolvedPath);
1281
- if (!normalizedPath) {
1282
- throw new Error("Document path is required.");
1283
- }
1284
- if (path2.isAbsolute(normalizedPath) || relativePath.startsWith("..") || path2.isAbsolute(relativePath)) {
1285
- throw new Error(`Document path "${relativeDocumentPath}" is outside the docs root.`);
1286
- }
1287
- if (!resolvedPath.endsWith(".txt")) {
1288
- throw new Error(`Document path "${relativeDocumentPath}" must point to a .txt file.`);
1289
- }
1290
- return resolvedPath;
1291
- }
1292
- function extractDocumentTitle(body, relativePath) {
1293
- const lines = body.split(/\r?\n/);
1294
- for (const line of lines) {
1295
- const trimmed = line.trim();
1296
- if (!trimmed || /^=+$/.test(trimmed)) {
1297
- continue;
1298
- }
1299
- if (trimmed.startsWith("TITLE:")) {
1300
- return trimmed.slice("TITLE:".length).trim();
1301
- }
1302
- return trimmed;
1303
- }
1304
- return path2.basename(relativePath, ".txt");
1305
- }
1306
- function getDocumentSection(relativePath) {
1307
- return relativePath.split("/")[0] ?? "docs";
1308
- }
1309
- function toPosixPath(value) {
1310
- return value.split(path2.sep).join("/");
1311
- }
1312
-
1313
- // src/ledger-service.ts
1314
- var HeliosAgentMcpLedgerService = class {
1315
- constructor(options) {
1316
- __publicField(this, "authService");
1317
- __publicField(this, "dataBridgeClient");
1318
- this.authService = options.authService;
1319
- this.dataBridgeClient = options.dataBridgeClient;
1320
- }
1321
- async getOpenPositions() {
1322
- const loginOptions = this.accountReadOptions();
1323
- const login = await this.authService.ensureLogin(loginOptions);
1324
- if (login.status !== "connected") {
1325
- return asPending(login);
1326
- }
1327
- const session = await this.authService.requireSession();
1328
- try {
1329
- const openPositions = await this.dataBridgeClient.getOpenPositions(session.accessToken);
1330
- return {
1331
- status: "connected",
1332
- connected: true,
1333
- openPositions
1334
- };
1335
- } catch (error) {
1336
- const recovery = await retryAfterUnauthorizedRefresh({
1337
- authService: this.authService,
1338
- error,
1339
- loginOptions,
1340
- retry: async (accessToken) => {
1341
- const openPositions = await this.dataBridgeClient.getOpenPositions(accessToken);
1342
- return {
1343
- status: "connected",
1344
- connected: true,
1345
- openPositions
1346
- };
1347
- }
1348
- });
1349
- if (recovery) {
1350
- return recovery;
1351
- }
1352
- throw error;
1353
- }
1354
- }
1355
- async getFills(input = {}) {
1356
- const loginOptions = this.accountReadOptions();
1357
- const login = await this.authService.ensureLogin(loginOptions);
1358
- if (login.status !== "connected") {
1359
- return asPending(login);
1360
- }
1361
- const session = await this.authService.requireSession();
1362
- try {
1363
- const fills = await this.dataBridgeClient.getLedgerFills(session.accessToken, input);
1364
- return {
1365
- status: "connected",
1366
- connected: true,
1367
- fills
1368
- };
1369
- } catch (error) {
1370
- const recovery = await retryAfterUnauthorizedRefresh({
1371
- authService: this.authService,
1372
- error,
1373
- loginOptions,
1374
- retry: async (accessToken) => {
1375
- const fills = await this.dataBridgeClient.getLedgerFills(accessToken, input);
1376
- return {
1377
- status: "connected",
1378
- connected: true,
1379
- fills
1380
- };
1381
- }
1382
- });
1383
- if (recovery) {
1384
- return recovery;
1385
- }
1386
- throw error;
1387
- }
1388
- }
1389
- async getSummary(input = {}) {
1390
- const loginOptions = this.accountReadOptions();
1391
- const login = await this.authService.ensureLogin(loginOptions);
1392
- if (login.status !== "connected") {
1393
- return asPending(login);
1394
- }
1395
- const session = await this.authService.requireSession();
1396
- try {
1397
- const summary = await this.dataBridgeClient.getLedgerSummary(session.accessToken, input);
1398
- return {
1399
- status: "connected",
1400
- connected: true,
1401
- summary
1402
- };
1403
- } catch (error) {
1404
- const recovery = await retryAfterUnauthorizedRefresh({
1405
- authService: this.authService,
1406
- error,
1407
- loginOptions,
1408
- retry: async (accessToken) => {
1409
- const summary = await this.dataBridgeClient.getLedgerSummary(accessToken, input);
1410
- return {
1411
- status: "connected",
1412
- connected: true,
1413
- summary
1414
- };
1415
- }
1416
- });
1417
- if (recovery) {
1418
- return recovery;
1419
- }
1420
- throw error;
1421
- }
1422
- }
1423
- accountReadOptions() {
1424
- return {
1425
- clientName: "Helios MCP",
1426
- scope: [AGENT_SCOPES.ACCOUNT_READ]
1427
- };
1428
- }
1429
- };
1430
- function asPending(login) {
1431
- return {
1432
- ...login,
1433
- status: "pending",
1434
- connected: false
1435
- };
1436
- }
1437
-
1438
- // src/market-service.ts
1439
- var DEFAULT_SNAPSHOT_TOP = 50;
1440
- var DEFAULT_SNAPSHOT_FIELDS = [
1441
- // Price, size and returns.
1442
- "rank",
1443
- "lp",
1444
- "qv",
1445
- "r15m",
1446
- "r1h",
1447
- "r4h",
1448
- "r24h",
1449
- "r7d",
1450
- // Regime and momentum turn: the one edge that held out of sample is buying a sharp turn up in a BREAKDOWN/CRASH coin.
1451
- "reg",
1452
- "hmi",
1453
- "hmiv",
1454
- "hs",
1455
- // Stretch and location: fades beat chases in the wallet research.
1456
- "ob",
1457
- "obosp",
1458
- "de",
1459
- "ms",
1460
- "srs",
1461
- "srr",
1462
- "fh24",
1463
- "fl24",
1464
- "fh7",
1465
- "fl7",
1466
- "vwz",
1467
- "tri"
1468
- ];
1469
- function withSnapshotDefaults(input) {
1470
- return {
1471
- ...input,
1472
- fields: input.fields ?? [...DEFAULT_SNAPSHOT_FIELDS],
1473
- sort: input.sort ?? "rank"
1474
- };
1475
- }
1476
- function topOfSnapshot(snapshot, input, top = DEFAULT_SNAPSHOT_TOP) {
1477
- if (input.symbols?.length || snapshot.table.rows.length <= top) return snapshot;
1478
- const baseIndex = snapshot.table.fieldIds.indexOf("base");
1479
- const rows = snapshot.table.rows.slice(0, top);
1480
- const returnedSymbols = baseIndex === -1 ? snapshot.returnedSymbols.slice(0, top) : rows.map((row) => String(row[baseIndex]));
1481
- return { ...snapshot, symbolCount: rows.length, returnedSymbols, table: { ...snapshot.table, rows } };
1482
- }
1483
- function compactSymbolDetail(detail, full) {
1484
- if (full) return detail;
1485
- return { ...detail, changeMap: {}, metrics: null };
1486
- }
1487
- var HeliosAgentMcpMarketService = class {
1488
- constructor(options) {
1489
- __publicField(this, "authService");
1490
- __publicField(this, "dataBridgeClient");
1491
- this.authService = options.authService;
1492
- this.dataBridgeClient = options.dataBridgeClient;
1493
- }
1494
- async getSnapshot(input = {}) {
1495
- const loginOptions = {
1496
- clientName: "Helios MCP",
1497
- scope: [AGENT_SCOPES.MARKET_READ]
1498
- };
1499
- const login = await this.authService.ensureLogin(loginOptions);
1500
- if (login.status !== "connected") {
1501
- return {
1502
- ...login,
1503
- status: "pending",
1504
- connected: false
1505
- };
1506
- }
1507
- const session = await this.authService.requireSession();
1508
- try {
1509
- const snapshot = topOfSnapshot(await this.dataBridgeClient.getMarketSnapshot(session.accessToken, withSnapshotDefaults(input)), input);
1510
- return {
1511
- status: "connected",
1512
- connected: true,
1513
- snapshot
1514
- };
1515
- } catch (error) {
1516
- const recovery = await retryAfterUnauthorizedRefresh({
1517
- authService: this.authService,
1518
- error,
1519
- loginOptions,
1520
- retry: async (accessToken) => {
1521
- const snapshot = topOfSnapshot(await this.dataBridgeClient.getMarketSnapshot(accessToken, withSnapshotDefaults(input)), input);
1522
- return {
1523
- status: "connected",
1524
- connected: true,
1525
- snapshot
1526
- };
1527
- }
1528
- });
1529
- if (recovery) {
1530
- return recovery;
1531
- }
1532
- throw error;
1533
- }
1534
- }
1535
- async getSnapshotChunk(input = {}) {
1536
- const loginOptions = {
1537
- clientName: "Helios MCP",
1538
- scope: [AGENT_SCOPES.MARKET_READ]
1539
- };
1540
- const login = await this.authService.ensureLogin(loginOptions);
1541
- if (login.status !== "connected") {
1542
- return {
1543
- ...login,
1544
- status: "pending",
1545
- connected: false
1546
- };
1547
- }
1548
- const session = await this.authService.requireSession();
1549
- try {
1550
- const snapshotChunk = await this.dataBridgeClient.getMarketSnapshotChunk(session.accessToken, withSnapshotDefaults(input));
1551
- return {
1552
- status: "connected",
1553
- connected: true,
1554
- snapshotChunk
1555
- };
1556
- } catch (error) {
1557
- const recovery = await retryAfterUnauthorizedRefresh({
1558
- authService: this.authService,
1559
- error,
1560
- loginOptions,
1561
- retry: async (accessToken) => {
1562
- const snapshotChunk = await this.dataBridgeClient.getMarketSnapshotChunk(accessToken, withSnapshotDefaults(input));
1563
- return {
1564
- status: "connected",
1565
- connected: true,
1566
- snapshotChunk
1567
- };
1568
- }
1569
- });
1570
- if (recovery) {
1571
- return recovery;
1572
- }
1573
- throw error;
1574
- }
1575
- }
1576
- async getSymbolDetail(input) {
1577
- const loginOptions = {
1578
- clientName: "Helios MCP",
1579
- scope: [AGENT_SCOPES.MARKET_READ]
1580
- };
1581
- const login = await this.authService.ensureLogin(loginOptions);
1582
- if (login.status !== "connected") {
1583
- return {
1584
- ...login,
1585
- status: "pending",
1586
- connected: false
1587
- };
1588
- }
1589
- const session = await this.authService.requireSession();
1590
- try {
1591
- const detail = compactSymbolDetail(await this.dataBridgeClient.getMarketSymbolDetail(session.accessToken, { symbol: input.symbol }), input.full);
1592
- return {
1593
- status: "connected",
1594
- connected: true,
1595
- detail
1596
- };
1597
- } catch (error) {
1598
- const recovery = await retryAfterUnauthorizedRefresh({
1599
- authService: this.authService,
1600
- error,
1601
- loginOptions,
1602
- retry: async (accessToken) => {
1603
- const detail = compactSymbolDetail(await this.dataBridgeClient.getMarketSymbolDetail(accessToken, { symbol: input.symbol }), input.full);
1604
- return {
1605
- status: "connected",
1606
- connected: true,
1607
- detail
1608
- };
1609
- }
1610
- });
1611
- if (recovery) {
1612
- return recovery;
1613
- }
1614
- throw error;
1615
- }
1616
- }
1617
- };
1618
-
1619
- // src/provider-service.ts
1620
- var HeliosAgentMcpProviderService = class {
1621
- constructor(options) {
1622
- __publicField(this, "sessionStore");
1623
- this.sessionStore = options.sessionStore;
1624
- }
1625
- async getActiveProvider() {
1626
- const provider = await this.sessionStore.getActiveProvider();
1627
- if (!provider) {
1628
- return {
1629
- configured: false,
1630
- provider: null
1631
- };
1632
- }
1633
- return {
1634
- configured: true,
1635
- provider
1636
- };
1637
- }
1638
- async setActiveProvider(provider) {
1639
- await this.sessionStore.setActiveProvider(provider);
1640
- return {
1641
- configured: true,
1642
- provider
1643
- };
1644
- }
1645
- async resolveProvider(explicitProvider) {
1646
- if (explicitProvider) {
1647
- return explicitProvider;
1648
- }
1649
- const activeProvider = await this.sessionStore.getActiveProvider();
1650
- if (activeProvider) {
1651
- return activeProvider;
1652
- }
1653
- throw new Error("No active provider configured. Call helios_provider_set_active or pass provider explicitly.");
1654
- }
1655
- };
1656
-
1657
- // src/session-store.ts
1658
- import { chmod, mkdir, readFile, rm, writeFile } from "fs/promises";
1659
- import { homedir } from "os";
1660
- import path3 from "path";
1661
- import { z as z4 } from "zod";
1662
- function getDefaultHeliosAgentMcpSessionPath() {
1663
- return path3.join(homedir(), ".helios-agent-mcp", "session.json");
1664
- }
1665
- var pendingAgentLoginSchema = z4.object({
1666
- status: z4.literal("pending"),
1667
- deviceCode: z4.string(),
1668
- userCode: z4.string(),
1669
- verificationUri: z4.string().url(),
1670
- verificationUriComplete: z4.string().url(),
1671
- expiresInSeconds: z4.number().int().positive(),
1672
- pollIntervalSeconds: z4.number().int().positive(),
1673
- requestedScope: z4.array(agentScopeSchema).min(1),
1674
- startedAt: z4.string().datetime()
1675
- });
1676
- var mcpSessionStateSchema = z4.object({
1677
- session: storedAgentSessionSchema.nullish(),
1678
- pendingLogin: pendingAgentLoginSchema.nullish(),
1679
- // A provider pinned before Binance was retired ('binance') reads as unpinned, so the agent must pick again, rather than
1680
- // failing the whole file (which would drop the session) or silently switching it to Hyperliquid.
1681
- activeProvider: providerSchema.nullish().catch(null)
1682
- });
1683
- var FileAgentSessionStore = class {
1684
- constructor(filePath = getDefaultHeliosAgentMcpSessionPath()) {
1685
- this.filePath = filePath;
1686
- }
1687
- async getSession() {
1688
- return (await this.readState()).session;
1689
- }
1690
- async getPendingLogin() {
1691
- return (await this.readState()).pendingLogin;
1692
- }
1693
- async getActiveProvider() {
1694
- return (await this.readState()).activeProvider;
1695
- }
1696
- async setSession(session) {
1697
- const state = await this.readState();
1698
- await this.writeState({
1699
- ...state,
1700
- session
1701
- });
1702
- }
1703
- async setPendingLogin(pendingLogin) {
1704
- const state = await this.readState();
1705
- await this.writeState({
1706
- ...state,
1707
- pendingLogin
1708
- });
1709
- }
1710
- async setActiveProvider(activeProvider) {
1711
- const state = await this.readState();
1712
- await this.writeState({
1713
- ...state,
1714
- activeProvider
1715
- });
1716
- }
1717
- async clearSession() {
1718
- const state = await this.readState();
1719
- await this.writeStateOrDelete({
1720
- ...state,
1721
- session: null
1722
- });
1723
- }
1724
- async clearPendingLogin() {
1725
- const state = await this.readState();
1726
- await this.writeStateOrDelete({
1727
- ...state,
1728
- pendingLogin: null
1729
- });
1730
- }
1731
- async clearActiveProvider() {
1732
- const state = await this.readState();
1733
- await this.writeStateOrDelete({
1734
- ...state,
1735
- activeProvider: null
1736
- });
1737
- }
1738
- async readState() {
1739
- try {
1740
- const raw = await readFile(this.filePath, "utf8");
1741
- const parsed = JSON.parse(raw);
1742
- if (parsed && typeof parsed === "object" && ("session" in parsed || "pendingLogin" in parsed || "activeProvider" in parsed)) {
1743
- const envelope = mcpSessionStateSchema.safeParse(parsed);
1744
- if (envelope.success) {
1745
- return {
1746
- session: envelope.data.session ?? null,
1747
- pendingLogin: envelope.data.pendingLogin ?? null,
1748
- activeProvider: envelope.data.activeProvider ?? null
1749
- };
1750
- }
1751
- }
1752
- const legacySession = storedAgentSessionSchema.safeParse(parsed);
1753
- if (legacySession.success) {
1754
- return {
1755
- session: legacySession.data,
1756
- pendingLogin: null,
1757
- activeProvider: null
1758
- };
1759
- }
1760
- return {
1761
- session: null,
1762
- pendingLogin: null,
1763
- activeProvider: null
1764
- };
1765
- } catch (error) {
1766
- if (isMissingFileError(error)) {
1767
- return {
1768
- session: null,
1769
- pendingLogin: null,
1770
- activeProvider: null
1771
- };
1772
- }
1773
- if (error instanceof Error && error.name === "ZodError") {
1774
- return {
1775
- session: null,
1776
- pendingLogin: null,
1777
- activeProvider: null
1778
- };
1779
- }
1780
- throw error;
1781
- }
1782
- }
1783
- async writeState(state) {
1784
- await mkdir(path3.dirname(this.filePath), { recursive: true });
1785
- await writeFile(this.filePath, `${JSON.stringify(state, null, 2)}
1786
- `, { encoding: "utf8", mode: 384 });
1787
- await chmod(this.filePath, 384).catch(() => void 0);
1788
- }
1789
- async writeStateOrDelete(state) {
1790
- if (!state.session && !state.pendingLogin && !state.activeProvider) {
1791
- await this.deleteFile();
1792
- return;
1793
- }
1794
- await this.writeState(state);
1795
- }
1796
- async deleteFile() {
1797
- try {
1798
- await rm(this.filePath, { force: true });
1799
- } catch (error) {
1800
- if (!isMissingFileError(error)) {
1801
- throw error;
1802
- }
1803
- }
1804
- }
1805
- };
1806
- var MemoryAgentMcpSessionStore = class {
1807
- constructor(session = null, activeProvider = "hyperliquid") {
1808
- this.session = session;
1809
- this.activeProvider = activeProvider;
1810
- __publicField(this, "pendingLogin", null);
1811
- }
1812
- async getSession() {
1813
- return this.session;
1814
- }
1815
- async setSession(session) {
1816
- this.session = session;
1817
- }
1818
- async clearSession() {
1819
- this.session = null;
1820
- }
1821
- async getActiveProvider() {
1822
- return this.activeProvider;
1823
- }
1824
- async setActiveProvider(provider) {
1825
- this.activeProvider = provider;
1826
- }
1827
- async clearActiveProvider() {
1828
- this.activeProvider = null;
1829
- }
1830
- async getPendingLogin() {
1831
- return this.pendingLogin;
1832
- }
1833
- async setPendingLogin(pendingLogin) {
1834
- this.pendingLogin = pendingLogin;
1835
- }
1836
- async clearPendingLogin() {
1837
- this.pendingLogin = null;
1838
- }
1839
- };
1840
- function isMissingFileError(error) {
1841
- return error instanceof Error && "code" in error && error.code === "ENOENT";
1842
- }
1843
-
1844
- // src/trading-service.ts
1845
- import { randomUUID } from "crypto";
1846
- var HeliosAgentMcpTradingService = class {
1847
- constructor(options) {
1848
- __publicField(this, "authService");
1849
- __publicField(this, "dataBridgeClient");
1850
- __publicField(this, "providerService");
1851
- this.authService = options.authService;
1852
- this.dataBridgeClient = options.dataBridgeClient;
1853
- this.providerService = options.providerService;
1854
- }
1855
- async open(input) {
1856
- return this.submitIntent("OPEN", input);
1857
- }
1858
- async dca(input) {
1859
- return this.submitIntent("DCA", input);
1860
- }
1861
- async reverse(input) {
1862
- return this.submitIntent("REVERSE", input);
1863
- }
1864
- async close(input) {
1865
- const loginOptions = {
1866
- clientName: "Helios MCP",
1867
- scope: [AGENT_SCOPES.ORDERS_WRITE]
1868
- };
1869
- const login = await this.authService.ensureLogin(loginOptions);
1870
- if (login.status !== "connected") {
1871
- return asPending2(login);
1872
- }
1873
- const session = await this.authService.requireSession();
1874
- try {
1875
- const provider = await this.providerService.resolveProvider(input.provider);
1876
- const closure = await this.dataBridgeClient.closePosition(session.accessToken, {
1877
- ...input,
1878
- provider
1879
- });
1880
- return {
1881
- status: "connected",
1882
- connected: true,
1883
- closure
1884
- };
1885
- } catch (error) {
1886
- const recovery = await retryAfterUnauthorizedRefresh({
1887
- authService: this.authService,
1888
- error,
1889
- loginOptions,
1890
- retry: async (accessToken) => {
1891
- const provider = await this.providerService.resolveProvider(input.provider);
1892
- const closure = await this.dataBridgeClient.closePosition(accessToken, {
1893
- ...input,
1894
- provider
1895
- });
1896
- return {
1897
- status: "connected",
1898
- connected: true,
1899
- closure
1900
- };
1901
- }
1902
- });
1903
- if (recovery) {
1904
- return recovery;
1905
- }
1906
- throw error;
1907
- }
1908
- }
1909
- async setTpSl(input) {
1910
- const loginOptions = {
1911
- clientName: "Helios MCP",
1912
- scope: [AGENT_SCOPES.ORDERS_WRITE]
1913
- };
1914
- const login = await this.authService.ensureLogin(loginOptions);
1915
- if (login.status !== "connected") {
1916
- return asPending2(login);
1917
- }
1918
- const session = await this.authService.requireSession();
1919
- try {
1920
- const provider = await this.providerService.resolveProvider(input.provider);
1921
- const protection = await this.dataBridgeClient.setTpSl(session.accessToken, {
1922
- ...input,
1923
- provider
1924
- });
1925
- return {
1926
- status: "connected",
1927
- connected: true,
1928
- protection
1929
- };
1930
- } catch (error) {
1931
- const recovery = await retryAfterUnauthorizedRefresh({
1932
- authService: this.authService,
1933
- error,
1934
- loginOptions,
1935
- retry: async (accessToken) => {
1936
- const provider = await this.providerService.resolveProvider(input.provider);
1937
- const protection = await this.dataBridgeClient.setTpSl(accessToken, {
1938
- ...input,
1939
- provider
1940
- });
1941
- return {
1942
- status: "connected",
1943
- connected: true,
1944
- protection
1945
- };
1946
- }
1947
- });
1948
- if (recovery) {
1949
- return recovery;
1950
- }
1951
- throw error;
1952
- }
1953
- }
1954
- async deleteTpSl(input) {
1955
- const loginOptions = {
1956
- clientName: "Helios MCP",
1957
- scope: [AGENT_SCOPES.ORDERS_CANCEL]
1958
- };
1959
- const login = await this.authService.ensureLogin(loginOptions);
1960
- if (login.status !== "connected") {
1961
- return asPending2(login);
1962
- }
1963
- const session = await this.authService.requireSession();
1964
- try {
1965
- const provider = await this.providerService.resolveProvider(input.provider);
1966
- const deletion = await this.dataBridgeClient.deleteTpSl(session.accessToken, {
1967
- ...input,
1968
- provider
1969
- });
1970
- return {
1971
- status: "connected",
1972
- connected: true,
1973
- deletion
1974
- };
1975
- } catch (error) {
1976
- const recovery = await retryAfterUnauthorizedRefresh({
1977
- authService: this.authService,
1978
- error,
1979
- loginOptions,
1980
- retry: async (accessToken) => {
1981
- const provider = await this.providerService.resolveProvider(input.provider);
1982
- const deletion = await this.dataBridgeClient.deleteTpSl(accessToken, {
1983
- ...input,
1984
- provider
1985
- });
1986
- return {
1987
- status: "connected",
1988
- connected: true,
1989
- deletion
1990
- };
1991
- }
1992
- });
1993
- if (recovery) {
1994
- return recovery;
1995
- }
1996
- throw error;
1997
- }
1998
- }
1999
- async getOpenOrders() {
2000
- const loginOptions = {
2001
- clientName: "Helios MCP",
2002
- scope: [AGENT_SCOPES.ACCOUNT_READ]
2003
- };
2004
- const login = await this.authService.ensureLogin(loginOptions);
2005
- if (login.status !== "connected") {
2006
- return asPending2(login);
2007
- }
2008
- const session = await this.authService.requireSession();
2009
- try {
2010
- const orders = await this.dataBridgeClient.getOpenOrders(session.accessToken);
2011
- return {
2012
- status: "connected",
2013
- connected: true,
2014
- orders
2015
- };
2016
- } catch (error) {
2017
- const recovery = await retryAfterUnauthorizedRefresh({
2018
- authService: this.authService,
2019
- error,
2020
- loginOptions,
2021
- retry: async (accessToken) => {
2022
- const orders = await this.dataBridgeClient.getOpenOrders(accessToken);
2023
- return {
2024
- status: "connected",
2025
- connected: true,
2026
- orders
2027
- };
2028
- }
2029
- });
2030
- if (recovery) {
2031
- return recovery;
2032
- }
2033
- throw error;
2034
- }
2035
- }
2036
- async cancelOrder(input) {
2037
- const loginOptions = {
2038
- clientName: "Helios MCP",
2039
- scope: [AGENT_SCOPES.ORDERS_CANCEL]
2040
- };
2041
- const login = await this.authService.ensureLogin(loginOptions);
2042
- if (login.status !== "connected") {
2043
- return asPending2(login);
2044
- }
2045
- const session = await this.authService.requireSession();
2046
- try {
2047
- const cancellation = await this.dataBridgeClient.cancelOrder(session.accessToken, input);
2048
- return {
2049
- status: "connected",
2050
- connected: true,
2051
- cancellation
2052
- };
2053
- } catch (error) {
2054
- const recovery = await retryAfterUnauthorizedRefresh({
2055
- authService: this.authService,
2056
- error,
2057
- loginOptions,
2058
- retry: async (accessToken) => {
2059
- const cancellation = await this.dataBridgeClient.cancelOrder(accessToken, input);
2060
- return {
2061
- status: "connected",
2062
- connected: true,
2063
- cancellation
2064
- };
2065
- }
2066
- });
2067
- if (recovery) {
2068
- return recovery;
2069
- }
2070
- throw error;
2071
- }
2072
- }
2073
- async submitIntent(intentType, input) {
2074
- const loginOptions = {
2075
- clientName: "Helios MCP",
2076
- scope: [AGENT_SCOPES.ORDERS_WRITE]
2077
- };
2078
- const login = await this.authService.ensureLogin(loginOptions);
2079
- if (login.status !== "connected") {
2080
- return asPending2(login);
2081
- }
2082
- const session = await this.authService.requireSession();
2083
- const idempotencyKey = input.idempotencyKey ?? randomUUID().replace(/-/g, "");
2084
- try {
2085
- const provider = await this.providerService.resolveProvider(input.provider);
2086
- const submission = await this.dataBridgeClient.submitTradeIntent(session.accessToken, {
2087
- ...input,
2088
- provider,
2089
- intentType,
2090
- idempotencyKey
2091
- });
2092
- return {
2093
- status: "connected",
2094
- connected: true,
2095
- submission
2096
- };
2097
- } catch (error) {
2098
- const recovery = await retryAfterUnauthorizedRefresh({
2099
- authService: this.authService,
2100
- error,
2101
- loginOptions,
2102
- retry: async (accessToken) => {
2103
- const provider = await this.providerService.resolveProvider(input.provider);
2104
- const submission = await this.dataBridgeClient.submitTradeIntent(accessToken, {
2105
- ...input,
2106
- provider,
2107
- intentType,
2108
- idempotencyKey
2109
- });
2110
- return {
2111
- status: "connected",
2112
- connected: true,
2113
- submission
2114
- };
2115
- }
2116
- });
2117
- if (recovery) {
2118
- return recovery;
2119
- }
2120
- throw error;
2121
- }
2122
- }
2123
- };
2124
- function asPending2(login) {
2125
- return {
2126
- ...login,
2127
- status: "pending",
2128
- connected: false
2129
- };
2130
- }
2131
-
2132
- // src/tools.ts
2133
- import { z as z5 } from "zod";
2134
- var pollLoginInputSchema = z5.object({
2135
- /** Optional: defaults to the login started by helios_auth_ensure_login / helios_auth_start_login. */
2136
- deviceCode: z5.string().min(1).optional()
2137
- });
2138
- var startLoginOutputSchema = z5.object({
2139
- status: z5.literal("pending"),
2140
- deviceCode: z5.string(),
2141
- userCode: z5.string(),
2142
- verificationUri: z5.string().url(),
2143
- verificationUriComplete: z5.string().url(),
2144
- expiresInSeconds: z5.number().int().positive(),
2145
- pollIntervalSeconds: z5.number().int().positive(),
2146
- requestedScope: z5.array(agentScopeSchema).min(1),
2147
- startedAt: z5.string().datetime()
2148
- });
2149
- var ensureLoginInputSchema = z5.object({
2150
- clientName: z5.string().min(1).max(64).optional(),
2151
- scope: z5.array(agentScopeSchema).min(1).optional(),
2152
- constraints: agentConstraintsSchema.optional()
2153
- });
2154
- var providerSelectionInputSchema = z5.object({
2155
- provider: providerSchema.optional()
2156
- });
2157
- var providerSetInputSchema = z5.object({
2158
- provider: providerSchema
2159
- });
2160
- var activeProviderSchema = z5.object({
2161
- configured: z5.boolean(),
2162
- provider: providerSchema.nullable()
2163
- });
2164
- var ensureLoginOutputSchema = z5.discriminatedUnion("status", [
2165
- agentSessionViewSchema.extend({
2166
- status: z5.literal("connected"),
2167
- connected: z5.literal(true)
2168
- }),
2169
- startLoginOutputSchema.extend({
2170
- status: z5.literal("pending"),
2171
- connected: z5.literal(false),
2172
- message: z5.string()
2173
- })
2174
- ]);
2175
- var pollLoginOutputSchema = z5.discriminatedUnion("status", [
2176
- agentSessionViewSchema.extend({
2177
- status: z5.literal("connected"),
2178
- connected: z5.literal(true)
2179
- }),
2180
- z5.object({
2181
- status: z5.enum(["pending", "rejected", "expired", "failed"]),
2182
- connected: z5.literal(false),
2183
- message: z5.string()
2184
- })
2185
- ]);
2186
- var walletStateToolOutputSchema = z5.discriminatedUnion("status", [
2187
- z5.object({
2188
- status: z5.literal("connected"),
2189
- connected: z5.literal(true),
2190
- walletState: walletStateSchema
2191
- }),
2192
- startLoginOutputSchema.extend({
2193
- status: z5.literal("pending"),
2194
- connected: z5.literal(false),
2195
- message: z5.string()
2196
- })
2197
- ]);
2198
- var portfolioToolOutputSchema = z5.discriminatedUnion("status", [
2199
- z5.object({
2200
- status: z5.literal("connected"),
2201
- connected: z5.literal(true),
2202
- portfolio: portfolioSnapshotSchema
2203
- }),
2204
- startLoginOutputSchema.extend({
2205
- status: z5.literal("pending"),
2206
- connected: z5.literal(false),
2207
- message: z5.string()
2208
- })
2209
- ]);
2210
- var openPositionsToolOutputSchema = z5.discriminatedUnion("status", [
2211
- z5.object({
2212
- status: z5.literal("connected"),
2213
- connected: z5.literal(true),
2214
- openPositions: openPositionsSnapshotSchema
2215
- }),
2216
- startLoginOutputSchema.extend({
2217
- status: z5.literal("pending"),
2218
- connected: z5.literal(false),
2219
- message: z5.string()
2220
- })
2221
- ]);
2222
- var ledgerFillsToolOutputSchema = z5.discriminatedUnion("status", [
2223
- z5.object({
2224
- status: z5.literal("connected"),
2225
- connected: z5.literal(true),
2226
- fills: ledgerFillsPageSchema
2227
- }),
2228
- startLoginOutputSchema.extend({
2229
- status: z5.literal("pending"),
2230
- connected: z5.literal(false),
2231
- message: z5.string()
2232
- })
2233
- ]);
2234
- var ledgerSummaryToolOutputSchema = z5.discriminatedUnion("status", [
2235
- z5.object({
2236
- status: z5.literal("connected"),
2237
- connected: z5.literal(true),
2238
- summary: ledgerSummarySchema
2239
- }),
2240
- startLoginOutputSchema.extend({
2241
- status: z5.literal("pending"),
2242
- connected: z5.literal(false),
2243
- message: z5.string()
2244
- })
2245
- ]);
2246
- var marketSnapshotToolOutputSchema = z5.discriminatedUnion("status", [
2247
- z5.object({
2248
- status: z5.literal("connected"),
2249
- connected: z5.literal(true),
2250
- snapshot: marketSnapshotSchema
2251
- }),
2252
- startLoginOutputSchema.extend({
2253
- status: z5.literal("pending"),
2254
- connected: z5.literal(false),
2255
- message: z5.string()
2256
- })
2257
- ]);
2258
- var marketSnapshotChunkToolOutputSchema = z5.discriminatedUnion("status", [
2259
- z5.object({
2260
- status: z5.literal("connected"),
2261
- connected: z5.literal(true),
2262
- snapshotChunk: marketSnapshotChunkSchema
2263
- }),
2264
- startLoginOutputSchema.extend({
2265
- status: z5.literal("pending"),
2266
- connected: z5.literal(false),
2267
- message: z5.string()
2268
- })
2269
- ]);
2270
- var marketSymbolDetailToolOutputSchema = z5.discriminatedUnion("status", [
2271
- z5.object({
2272
- status: z5.literal("connected"),
2273
- connected: z5.literal(true),
2274
- detail: marketSymbolDetailSchema
2275
- }),
2276
- startLoginOutputSchema.extend({
2277
- status: z5.literal("pending"),
2278
- connected: z5.literal(false),
2279
- message: z5.string()
2280
- })
2281
- ]);
2282
- var tradeActionInputSchema = submitTradeIntentInputSchema.omit({
2283
- intentType: true
2284
- });
2285
- var tradeActionToolOutputSchema = z5.discriminatedUnion("status", [
2286
- z5.object({
2287
- status: z5.literal("connected"),
2288
- connected: z5.literal(true),
2289
- submission: submitTradeIntentResultSchema
2290
- }),
2291
- startLoginOutputSchema.extend({
2292
- status: z5.literal("pending"),
2293
- connected: z5.literal(false),
2294
- message: z5.string()
2295
- })
2296
- ]);
2297
- var closeTradeToolOutputSchema = z5.discriminatedUnion("status", [
2298
- z5.object({
2299
- status: z5.literal("connected"),
2300
- connected: z5.literal(true),
2301
- closure: closePositionResultSchema
2302
- }),
2303
- startLoginOutputSchema.extend({
2304
- status: z5.literal("pending"),
2305
- connected: z5.literal(false),
2306
- message: z5.string()
2307
- })
2308
- ]);
2309
- var setTpSlToolOutputSchema = z5.discriminatedUnion("status", [
2310
- z5.object({
2311
- status: z5.literal("connected"),
2312
- connected: z5.literal(true),
2313
- protection: setTpSlResultSchema
2314
- }),
2315
- startLoginOutputSchema.extend({
2316
- status: z5.literal("pending"),
2317
- connected: z5.literal(false),
2318
- message: z5.string()
2319
- })
2320
- ]);
2321
- var deleteTpSlToolOutputSchema = z5.discriminatedUnion("status", [
2322
- z5.object({
2323
- status: z5.literal("connected"),
2324
- connected: z5.literal(true),
2325
- deletion: deleteTpSlResultSchema
2326
- }),
2327
- startLoginOutputSchema.extend({
2328
- status: z5.literal("pending"),
2329
- connected: z5.literal(false),
2330
- message: z5.string()
2331
- })
2332
- ]);
2333
- var openOrdersToolOutputSchema = z5.discriminatedUnion("status", [
2334
- z5.object({
2335
- status: z5.literal("connected"),
2336
- connected: z5.literal(true),
2337
- orders: z5.array(openOrderSchema)
2338
- }),
2339
- startLoginOutputSchema.extend({
2340
- status: z5.literal("pending"),
2341
- connected: z5.literal(false),
2342
- message: z5.string()
2343
- })
2344
- ]);
2345
- var cancelOrderToolOutputSchema = z5.discriminatedUnion("status", [
2346
- z5.object({
2347
- status: z5.literal("connected"),
2348
- connected: z5.literal(true),
2349
- cancellation: cancelOrderResultSchema
2350
- }),
2351
- startLoginOutputSchema.extend({
2352
- status: z5.literal("pending"),
2353
- connected: z5.literal(false),
2354
- message: z5.string()
2355
- })
2356
- ]);
2357
- var documentPathInputSchema = z5.object({
2358
- path: z5.string().min(1)
2359
- });
2360
- var docsIndexSchema = z5.object({
2361
- root: z5.literal("docs"),
2362
- documents: z5.array(
2363
- z5.object({
2364
- path: z5.string(),
2365
- section: z5.string(),
2366
- title: z5.string(),
2367
- bytes: z5.number().int().nonnegative()
2368
- })
2369
- )
2370
- });
2371
- var documentSchema = z5.object({
2372
- path: z5.string(),
2373
- section: z5.string(),
2374
- title: z5.string(),
2375
- body: z5.string(),
2376
- bytes: z5.number().int().nonnegative()
2377
- });
2378
- function createHeliosDocsToolDefinitions(service) {
2379
- return [
2380
- {
2381
- name: "helios_docs_get_index",
2382
- title: "Get Helios Docs Index",
2383
- description: "Lists the package-local Helios MCP and indicator .txt documentation available to the agent.",
2384
- inputSchema: z5.object({}),
2385
- async execute() {
2386
- const result = docsIndexSchema.parse(await service.getIndex());
2387
- return {
2388
- content: [
2389
- {
2390
- type: "text",
2391
- text: `Helios docs index: ${result.documents.length} documents across ${new Set(result.documents.map((document) => document.section)).size} sections.`
2392
- }
2393
- ],
2394
- structuredContent: result
2395
- };
2396
- }
2397
- },
2398
- {
2399
- name: "helios_docs_get_document",
2400
- title: "Get Helios Doc",
2401
- description: "Returns one package-local Helios .txt document by relative docs path.",
2402
- inputSchema: documentPathInputSchema,
2403
- async execute(input) {
2404
- const result = documentSchema.parse(await service.getDocument(input));
2405
- return {
2406
- content: [
2407
- {
2408
- type: "text",
2409
- text: result.body
2410
- }
2411
- ],
2412
- structuredContent: result
2413
- };
2414
- }
2415
- }
2416
- ];
2417
- }
2418
- function createHeliosAuthToolDefinitions(service) {
2419
- return [
2420
- {
2421
- name: "helios_auth_start_login",
2422
- title: "Start Helios Login",
2423
- description: "Starts the delegated Helios login flow and returns the approval URL for the user.",
2424
- inputSchema: agentDeviceStartInputSchema,
2425
- async execute(input) {
2426
- const result = startLoginOutputSchema.parse(await service.startLogin(input));
2427
- const manualResult = {
2428
- ...result,
2429
- ...withManualLoginFields(result)
2430
- };
2431
- return {
2432
- content: [
2433
- {
2434
- type: "text",
2435
- text: buildManualLoginText(result)
2436
- }
2437
- ],
2438
- structuredContent: manualResult
2439
- };
2440
- }
2441
- },
2442
- {
2443
- name: "helios_auth_ensure_login",
2444
- title: "Ensure Helios Login",
2445
- description: "Ensures a delegated Helios session exists, or starts a login flow and returns a ready-to-display approval prompt. Call it again after the person approves: it finishes connecting.",
2446
- inputSchema: ensureLoginInputSchema,
2447
- async execute(input) {
2448
- const result = ensureLoginOutputSchema.parse(await service.ensureLogin(input));
2449
- const structuredContent = result.status === "connected" ? result : {
2450
- ...result,
2451
- ...withManualLoginFields(result)
2452
- };
2453
- return {
2454
- content: [
2455
- {
2456
- type: "text",
2457
- text: result.status === "connected" ? `Connected to Helios as user ${result.ownerUserId}.` : result.message
2458
- }
2459
- ],
2460
- structuredContent
2461
- };
2462
- }
2463
- },
2464
- {
2465
- name: "helios_auth_poll_login",
2466
- title: "Poll Helios Login",
2467
- description: "Checks whether the Helios login was approved and finishes connecting. The device code is optional; without it, the login in progress is checked.",
2468
- inputSchema: pollLoginInputSchema,
2469
- async execute(input) {
2470
- const result = pollLoginOutputSchema.parse(await service.pollLogin(input.deviceCode));
2471
- return {
2472
- content: [
2473
- {
2474
- type: "text",
2475
- text: result.status === "connected" ? `Connected to Helios as user ${result.ownerUserId}.` : `Helios login is ${result.status}: ${result.message}`
2476
- }
2477
- ],
2478
- structuredContent: result
2479
- };
2480
- }
2481
- },
2482
- {
2483
- name: "helios_auth_whoami",
2484
- title: "Helios Login Status",
2485
- description: "Returns the delegated Helios session state currently stored by the MCP server.",
2486
- inputSchema: z5.object({}),
2487
- async execute() {
2488
- const result = agentSessionViewSchema.parse(await service.whoami());
2489
- return {
2490
- content: [
2491
- {
2492
- type: "text",
2493
- text: result.connected ? `Connected to Helios as user ${result.ownerUserId}.` : "No delegated Helios session is connected."
2494
- }
2495
- ],
2496
- structuredContent: result
2497
- };
2498
- }
2499
- }
2500
- ];
2501
- }
2502
- function createHeliosProviderToolDefinitions(service) {
2503
- return [
2504
- {
2505
- name: "helios_provider_get_active",
2506
- title: "Get Helios Active Provider",
2507
- description: "Returns the provider currently pinned for this MCP session, if any.",
2508
- inputSchema: z5.object({}),
2509
- async execute() {
2510
- const result = activeProviderSchema.parse(await service.getActiveProvider());
2511
- return {
2512
- content: [
2513
- {
2514
- type: "text",
2515
- text: result.configured ? `Helios active provider is ${result.provider}.` : "No Helios active provider is configured for this session."
2516
- }
2517
- ],
2518
- structuredContent: result
2519
- };
2520
- }
2521
- },
2522
- {
2523
- name: "helios_provider_set_active",
2524
- title: "Set Helios Active Provider",
2525
- description: "Pins the active provider for this MCP session so portfolio and trading tools can omit provider.",
2526
- inputSchema: providerSetInputSchema,
2527
- async execute(input) {
2528
- const result = activeProviderSchema.parse(await service.setActiveProvider(input.provider));
2529
- return {
2530
- content: [
2531
- {
2532
- type: "text",
2533
- text: `Helios active provider set to ${result.provider}.`
2534
- }
2535
- ],
2536
- structuredContent: result
2537
- };
2538
- }
2539
- }
2540
- ];
2541
- }
2542
- function createHeliosAccountToolDefinitions(service) {
2543
- return [
2544
- {
2545
- name: "helios_account_get_wallet_state",
2546
- title: "Get Helios Wallet State",
2547
- description: "Returns the current Hyperliquid wallet snapshot for the connected Helios account.",
2548
- inputSchema: z5.object({}),
2549
- async execute() {
2550
- const result = walletStateToolOutputSchema.parse(await service.getWalletState());
2551
- const structuredContent = result.status === "connected" ? result : {
2552
- ...result,
2553
- ...withManualLoginFields(result)
2554
- };
2555
- return {
2556
- content: [
2557
- {
2558
- type: "text",
2559
- text: result.status === "connected" ? `Helios wallet state: available balance ${result.walletState.availableBalance}, account value ${result.walletState.accountValue}.` : result.message
2560
- }
2561
- ],
2562
- structuredContent
2563
- };
2564
- }
2565
- },
2566
- {
2567
- name: "helios_portfolio_get",
2568
- title: "Get Helios Portfolio",
2569
- description: "Returns balances, open positions and their TP/SL (protectiveOrders, each with the id helios_positions_delete_tp_sl takes). Provider may be omitted if one is already pinned with helios_provider_set_active.",
2570
- inputSchema: providerSelectionInputSchema,
2571
- async execute(input) {
2572
- const result = portfolioToolOutputSchema.parse(await service.getPortfolio(input));
2573
- const structuredContent = result.status === "connected" ? result : {
2574
- ...result,
2575
- ...withManualLoginFields(result)
2576
- };
2577
- return {
2578
- content: [
2579
- {
2580
- type: "text",
2581
- text: result.status === "connected" ? buildPortfolioText(result.portfolio) : result.message
2582
- }
2583
- ],
2584
- structuredContent
2585
- };
2586
- }
2587
- }
2588
- ];
2589
- }
2590
- function createHeliosLedgerToolDefinitions(service) {
2591
- return [
2592
- {
2593
- name: "helios_positions_get_open",
2594
- title: "Get Helios Open Positions",
2595
- description: "Returns the current open Hyperliquid positions for the connected Helios account.",
2596
- inputSchema: z5.object({}),
2597
- async execute() {
2598
- const result = openPositionsToolOutputSchema.parse(await service.getOpenPositions());
2599
- const structuredContent = result.status === "connected" ? result : {
2600
- ...result,
2601
- ...withManualLoginFields(result)
2602
- };
2603
- return {
2604
- content: [
2605
- {
2606
- type: "text",
2607
- text: result.status === "connected" ? `Helios open positions: ${result.openPositions.positions.length} positions, total unrealized PnL ${result.openPositions.totalUnrealizedPnl}.` : result.message
2608
- }
2609
- ],
2610
- structuredContent
2611
- };
2612
- }
2613
- },
2614
- {
2615
- name: "helios_ledger_get_fills",
2616
- title: "Get Helios Ledger Fills",
2617
- description: "Returns recent Hyperliquid fills/trade history for the connected Helios account.",
2618
- inputSchema: ledgerFillsInputSchema,
2619
- async execute(input) {
2620
- const result = ledgerFillsToolOutputSchema.parse(await service.getFills(input));
2621
- const structuredContent = result.status === "connected" ? result : {
2622
- ...result,
2623
- ...withManualLoginFields(result)
2624
- };
2625
- return {
2626
- content: [
2627
- {
2628
- type: "text",
2629
- text: result.status === "connected" ? `Helios ledger fills: ${result.fills.fills.length} fills from ${result.fills.window}${result.fills.hasMore ? ", more available" : ""}.` : result.message
2630
- }
2631
- ],
2632
- structuredContent
2633
- };
2634
- }
2635
- },
2636
- {
2637
- name: "helios_ledger_get_summary",
2638
- title: "Get Helios Ledger Summary",
2639
- description: "Returns realized PnL, fees, and win/loss metrics over a recent Hyperliquid fill window.",
2640
- inputSchema: ledgerSummaryInputSchema,
2641
- async execute(input) {
2642
- const result = ledgerSummaryToolOutputSchema.parse(await service.getSummary(input));
2643
- const structuredContent = result.status === "connected" ? result : {
2644
- ...result,
2645
- ...withManualLoginFields(result)
2646
- };
2647
- return {
2648
- content: [
2649
- {
2650
- type: "text",
2651
- text: result.status === "connected" ? `Helios ledger summary (${result.summary.window}): realized PnL ${result.summary.realizedPnl}, fees ${result.summary.totalFees}, wins ${result.summary.winCount}, losses ${result.summary.lossCount}.` : result.message
2652
- }
2653
- ],
2654
- structuredContent
2655
- };
2656
- }
2657
- }
2658
- ];
2659
- }
2660
- function createHeliosMarketToolDefinitions(service) {
2661
- return [
2662
- {
2663
- name: "helios_market_get_snapshot",
2664
- title: "Get Helios Market Snapshot",
2665
- description: "Returns a compact market snapshot for the selected, all, or explicitly requested symbols. By default: the top 50 coins by market cap with the main columns; name symbols to get other coins, pass fields for other columns. What each column means: helios_docs_get_document with path ai-agent-indicators/00_columns.txt (read it once).",
2666
- inputSchema: marketSnapshotInputSchema,
2667
- async execute(input) {
2668
- const result = marketSnapshotToolOutputSchema.parse(await service.getSnapshot(input));
2669
- const structuredContent = result.status === "connected" ? result : {
2670
- ...result,
2671
- ...withManualLoginFields(result)
2672
- };
2673
- return {
2674
- content: [
2675
- {
2676
- type: "text",
2677
- text: result.status === "connected" ? `Helios market snapshot: ${result.snapshot.symbolCount} symbols (${result.snapshot.scope}) at ${result.snapshot.generatedAt}. Timeframe return fields are already percentages; do not multiply by 100. Null means unavailable, not zero.` : result.message
2678
- }
2679
- ],
2680
- structuredContent
2681
- };
2682
- }
2683
- },
2684
- {
2685
- name: "helios_market_get_snapshot_chunk",
2686
- title: "Get Helios Market Snapshot Chunk",
2687
- description: "Returns one chunk of the Helios market snapshot for batch analysis when the full snapshot is too large.",
2688
- inputSchema: marketSnapshotChunkInputSchema,
2689
- async execute(input) {
2690
- const result = marketSnapshotChunkToolOutputSchema.parse(await service.getSnapshotChunk(input));
2691
- const structuredContent = result.status === "connected" ? result : {
2692
- ...result,
2693
- ...withManualLoginFields(result)
2694
- };
2695
- return {
2696
- content: [
2697
- {
2698
- type: "text",
2699
- text: result.status === "connected" ? `Helios market snapshot chunk: ${result.snapshotChunk.chunkSymbolCount}/${result.snapshotChunk.totalSymbolCount} symbols at offset ${result.snapshotChunk.offset} (limit ${result.snapshotChunk.limit}). ${result.snapshotChunk.hasMore ? `Read next chunk at offset ${result.snapshotChunk.nextOffset}.` : "No more chunks remain."} Timeframe return fields are already percentages; do not multiply by 100. Null means unavailable, not zero.` : result.message
2700
- }
2701
- ],
2702
- structuredContent
2703
- };
2704
- }
2705
- },
2706
- {
2707
- name: "helios_market_get_symbol_detail",
2708
- title: "Get Helios Symbol Detail",
2709
- description: "Returns one coin: every snapshot column plus Hyperliquid context (funding, open interest, max leverage, mark price). For several coins, use helios_market_get_snapshot with symbols instead; pass full only when you need raw indicators.",
2710
- inputSchema: marketSymbolDetailInputSchema,
2711
- async execute(input) {
2712
- const result = marketSymbolDetailToolOutputSchema.parse(await service.getSymbolDetail(input));
2713
- const structuredContent = result.status === "connected" ? result : {
2714
- ...result,
2715
- ...withManualLoginFields(result)
2716
- };
2717
- return {
2718
- content: [
2719
- {
2720
- type: "text",
2721
- text: result.status === "connected" ? `Helios symbol detail: ${result.detail.symbol} at ${result.detail.generatedAt}. Timeframe return fields are already percentages; do not multiply by 100. Null means unavailable, not zero.` : result.message
2722
- }
2723
- ],
2724
- structuredContent
2725
- };
2726
- }
2727
- }
2728
- ];
2729
- }
2730
- function createHeliosTradingToolDefinitions(service) {
2731
- return [
2732
- {
2733
- name: "helios_trading_open",
2734
- title: "Open Helios Position",
2735
- description: "Submits a Helios OPEN trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2736
- inputSchema: tradeActionInputSchema,
2737
- async execute(input) {
2738
- const result = tradeActionToolOutputSchema.parse(await service.open(input));
2739
- return {
2740
- content: [
2741
- {
2742
- type: "text",
2743
- text: result.status === "connected" ? `Submitted Helios OPEN intent for ${result.submission.provider ?? input.provider} ${result.submission.symbol} ${result.submission.direction} with ${result.submission.execution.style} execution.` : result.message
2744
- }
2745
- ],
2746
- structuredContent: result.status === "connected" ? result : {
2747
- ...result,
2748
- ...withManualLoginFields(result)
2749
- }
2750
- };
2751
- }
2752
- },
2753
- {
2754
- name: "helios_trading_dca",
2755
- title: "DCA Helios Position",
2756
- description: "Submits a Helios DCA trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2757
- inputSchema: tradeActionInputSchema,
2758
- async execute(input) {
2759
- const result = tradeActionToolOutputSchema.parse(await service.dca(input));
2760
- return {
2761
- content: [
2762
- {
2763
- type: "text",
2764
- text: result.status === "connected" ? `Submitted Helios DCA intent for ${result.submission.provider ?? input.provider} ${result.submission.symbol} ${result.submission.direction} with ${result.submission.execution.style} execution.` : result.message
2765
- }
2766
- ],
2767
- structuredContent: result.status === "connected" ? result : {
2768
- ...result,
2769
- ...withManualLoginFields(result)
2770
- }
2771
- };
2772
- }
2773
- },
2774
- {
2775
- name: "helios_trading_reverse",
2776
- title: "Reverse Helios Position",
2777
- description: "Submits a Helios REVERSE trading intent. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2778
- inputSchema: tradeActionInputSchema,
2779
- async execute(input) {
2780
- const result = tradeActionToolOutputSchema.parse(await service.reverse(input));
2781
- return {
2782
- content: [
2783
- {
2784
- type: "text",
2785
- text: result.status === "connected" ? `Submitted Helios REVERSE intent for ${result.submission.provider ?? input.provider} ${result.submission.symbol} ${result.submission.direction} with ${result.submission.execution.style} execution.` : result.message
2786
- }
2787
- ],
2788
- structuredContent: result.status === "connected" ? result : {
2789
- ...result,
2790
- ...withManualLoginFields(result)
2791
- }
2792
- };
2793
- }
2794
- },
2795
- {
2796
- name: "helios_trading_close",
2797
- title: "Close Helios Position",
2798
- description: "Closes the full Helios position using the dedicated backend close route. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2799
- inputSchema: closePositionInputSchema,
2800
- async execute(input) {
2801
- const result = closeTradeToolOutputSchema.parse(await service.close(input));
2802
- return {
2803
- content: [
2804
- {
2805
- type: "text",
2806
- text: result.status !== "connected" ? result.message : result.closure.outcome === "no_position" ? `No open ${result.closure.symbol} position: nothing was closed and no order was sent.` : `Sent a market order closing the full ${result.closure.provider ?? input.provider ?? "hyperliquid"} ${result.closure.symbol} position. Check helios_positions_get_open to confirm.`
2807
- }
2808
- ],
2809
- structuredContent: result.status === "connected" ? result : {
2810
- ...result,
2811
- ...withManualLoginFields(result)
2812
- }
2813
- };
2814
- }
2815
- },
2816
- {
2817
- name: "helios_positions_set_tp_sl",
2818
- title: "Set Helios TP/SL",
2819
- description: "Creates or replaces take-profit and stop-loss protection for an existing Helios position. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2820
- inputSchema: setTpSlInputSchema,
2821
- async execute(input) {
2822
- const result = setTpSlToolOutputSchema.parse(await service.setTpSl(input));
2823
- return {
2824
- content: [
2825
- {
2826
- type: "text",
2827
- text: result.status === "connected" ? `Submitted ${result.protection.provider ?? input.provider} TP/SL protection update for ${result.protection.symbol}.` : result.message
2828
- }
2829
- ],
2830
- structuredContent: result.status === "connected" ? result : {
2831
- ...result,
2832
- ...withManualLoginFields(result)
2833
- }
2834
- };
2835
- }
2836
- },
2837
- {
2838
- name: "helios_positions_delete_tp_sl",
2839
- title: "Delete Helios TP/SL",
2840
- description: "Deletes a take-profit or stop-loss. orderId is the id from helios_portfolio_get protectiveOrders, or the Hyperliquid order id of the TP/SL. Provider may be omitted if one is already pinned with helios_provider_set_active.",
2841
- inputSchema: deleteTpSlInputSchema,
2842
- async execute(input) {
2843
- const result = deleteTpSlToolOutputSchema.parse(await service.deleteTpSl(input));
2844
- return {
2845
- content: [
2846
- {
2847
- type: "text",
2848
- text: result.status === "connected" ? `Deleted ${result.deletion.provider ?? input.provider} TP/SL order ${result.deletion.orderId} for ${result.deletion.symbol}.` : result.message
2849
- }
2850
- ],
2851
- structuredContent: result.status === "connected" ? result : {
2852
- ...result,
2853
- ...withManualLoginFields(result)
2854
- }
2855
- };
2856
- }
2857
- },
2858
- {
2859
- name: "helios_orders_get_open",
2860
- title: "Get Helios Open Orders",
2861
- description: "Lists the currently open Hyperliquid orders for the connected account.",
2862
- inputSchema: z5.object({}),
2863
- async execute() {
2864
- const result = openOrdersToolOutputSchema.parse(await service.getOpenOrders());
2865
- return {
2866
- content: [
2867
- {
2868
- type: "text",
2869
- text: result.status === "connected" ? `Retrieved ${result.orders.length} open Helios orders.` : result.message
2870
- }
2871
- ],
2872
- structuredContent: result.status === "connected" ? result : {
2873
- ...result,
2874
- ...withManualLoginFields(result)
2875
- }
2876
- };
2877
- }
2878
- },
2879
- {
2880
- name: "helios_orders_cancel",
2881
- title: "Cancel Helios Order",
2882
- description: "Cancels an open Hyperliquid order by symbol and order id.",
2883
- inputSchema: cancelOrderInputSchema,
2884
- async execute(input) {
2885
- const result = cancelOrderToolOutputSchema.parse(await service.cancelOrder(input));
2886
- return {
2887
- content: [
2888
- {
2889
- type: "text",
2890
- text: result.status === "connected" ? `Cancelled Helios order ${result.cancellation.oid} for ${result.cancellation.symbol}.` : result.message
2891
- }
2892
- ],
2893
- structuredContent: result.status === "connected" ? result : {
2894
- ...result,
2895
- ...withManualLoginFields(result)
2896
- }
2897
- };
2898
- }
2899
- }
2900
- ];
2901
- }
2902
- function withManualLoginFields(result) {
2903
- return {
2904
- actionRequired: true,
2905
- loginUrl: result.verificationUriComplete,
2906
- nextStep: "Open the login URL in your browser, approve Helios access, then call helios_auth_ensure_login again to finish connecting."
2907
- };
2908
- }
2909
- function buildPortfolioText(result) {
2910
- return `Helios Hyperliquid portfolio: ${result.positions.length} positions, available balance ${result.availableBalance}, total balance ${result.totalBalance}.`;
2911
- }
2912
- function buildManualLoginText(result) {
2913
- return `Log in to Helios by opening this URL in your browser:
2914
-
2915
- ${result.verificationUriComplete}
2916
-
2917
- User code: ${result.userCode}
2918
-
2919
- After approving access, call helios_auth_ensure_login (or helios_auth_poll_login) again to finish connecting.`;
2920
- }
2921
-
2922
- // src/server.ts
2923
- async function createHeliosAgentMcpServer(options) {
2924
- if (!options.identityServiceUrl) {
2925
- throw new Error("identityServiceUrl is required");
2926
- }
2927
- if (!options.dataBridgeUrl) {
2928
- throw new Error("dataBridgeUrl is required");
2929
- }
2930
- const { McpServer } = await import("@modelcontextprotocol/sdk/server/mcp.js");
2931
- const server = new McpServer({
2932
- name: "helios",
2933
- version: "0.2.9"
2934
- });
2935
- const sessionStore = options.sessionStore ?? new FileAgentSessionStore(options.sessionPath ?? getDefaultHeliosAgentMcpSessionPath());
2936
- const client = new HeliosAgentAuthClient({
2937
- baseUrl: options.identityServiceUrl,
2938
- fetch: options.fetch
2939
- });
2940
- const dataBridgeClient = new HeliosAgentDataBridgeClient({
2941
- baseUrl: options.dataBridgeUrl,
2942
- fetch: options.fetch
2943
- });
2944
- const authService = new HeliosAgentMcpAuthService({
2945
- client,
2946
- sessionStore,
2947
- refreshWindowMs: options.refreshWindowMs,
2948
- deviceLogin: !options.hosted
2949
- });
2950
- const providerService = new HeliosAgentMcpProviderService({
2951
- sessionStore
2952
- });
2953
- const accountService = new HeliosAgentMcpAccountService({
2954
- authService,
2955
- dataBridgeClient,
2956
- providerService
2957
- });
2958
- const marketService = new HeliosAgentMcpMarketService({
2959
- authService,
2960
- dataBridgeClient
2961
- });
2962
- const ledgerService = new HeliosAgentMcpLedgerService({
2963
- authService,
2964
- dataBridgeClient
2965
- });
2966
- const tradingService = new HeliosAgentMcpTradingService({
2967
- authService,
2968
- dataBridgeClient,
2969
- providerService
2970
- });
2971
- const docsService = new HeliosAgentMcpDocsService({
2972
- docsRoot: options.docsRoot ?? getDefaultHeliosAgentMcpDocsRoot()
2973
- });
2974
- const docsTools = createHeliosDocsToolDefinitions(docsService);
2975
- const authTools = createHeliosAuthToolDefinitions(authService);
2976
- const providerTools = createHeliosProviderToolDefinitions(providerService);
2977
- const accountTools = createHeliosAccountToolDefinitions(accountService);
2978
- const ledgerTools = createHeliosLedgerToolDefinitions(ledgerService);
2979
- const marketTools = createHeliosMarketToolDefinitions(marketService);
2980
- const tradingTools = createHeliosTradingToolDefinitions(tradingService);
2981
- registerTool(server, docsTools[0]);
2982
- registerTool(server, docsTools[1]);
2983
- if (!options.hosted) {
2984
- registerTool(server, authTools[0]);
2985
- registerTool(server, authTools[1]);
2986
- registerTool(server, authTools[2]);
2987
- }
2988
- registerTool(server, authTools[3]);
2989
- registerTool(server, providerTools[0]);
2990
- registerTool(server, providerTools[1]);
2991
- registerTool(server, accountTools[0]);
2992
- registerTool(server, accountTools[1]);
2993
- registerTool(server, ledgerTools[0]);
2994
- registerTool(server, ledgerTools[1]);
2995
- registerTool(server, ledgerTools[2]);
2996
- registerTool(server, marketTools[0]);
2997
- registerTool(server, marketTools[1]);
2998
- registerTool(server, marketTools[2]);
2999
- registerTool(server, tradingTools[0]);
3000
- registerTool(server, tradingTools[1]);
3001
- registerTool(server, tradingTools[2]);
3002
- registerTool(server, tradingTools[3]);
3003
- registerTool(server, tradingTools[4]);
3004
- registerTool(server, tradingTools[5]);
3005
- registerTool(server, tradingTools[6]);
3006
- registerTool(server, tradingTools[7]);
3007
- return {
3008
- server,
3009
- authService,
3010
- providerService,
3011
- accountService,
3012
- docsService,
3013
- ledgerService,
3014
- marketService,
3015
- tradingService,
3016
- sessionStore
3017
- };
3018
- }
3019
- var ACTS_ON_ACCOUNT = /^helios_(trading_|positions_set_tp_sl|positions_delete_tp_sl|orders_cancel)/;
3020
- var CHANGES_SESSION = /^helios_(auth_start_login|auth_ensure_login|auth_poll_login|provider_set_active)$/;
3021
- function toolAnnotations(name) {
3022
- if (ACTS_ON_ACCOUNT.test(name)) return { readOnlyHint: false, destructiveHint: true, openWorldHint: true };
3023
- if (CHANGES_SESSION.test(name)) return { readOnlyHint: false, destructiveHint: false, openWorldHint: false };
3024
- return { readOnlyHint: true, destructiveHint: false, openWorldHint: true };
3025
- }
3026
- var TEXT_IS_RESULT = /* @__PURE__ */ new Set(["helios_docs_get_document"]);
3027
- function withDataText(name, content, structuredContent) {
3028
- if (TEXT_IS_RESULT.has(name)) return content;
3029
- const summary = content.map((block) => block.text).join("\n\n");
3030
- return [{ type: "text", text: `${summary}
3031
-
3032
- ${JSON.stringify(structuredContent)}` }];
3033
- }
3034
- function registerTool(server, tool) {
3035
- server.registerTool(
3036
- tool.name,
3037
- {
3038
- title: tool.title,
3039
- description: tool.description,
3040
- inputSchema: tool.inputSchema,
3041
- annotations: { title: tool.title, ...toolAnnotations(tool.name) }
3042
- },
3043
- async (input) => {
3044
- const result = await tool.execute(tool.inputSchema.parse(input));
3045
- return {
3046
- content: withDataText(tool.name, result.content, result.structuredContent),
3047
- structuredContent: result.structuredContent
3048
- };
3049
- }
3050
- );
3051
- }
3052
-
3053
- export {
3054
- HOSTED_RECONNECT_MESSAGE,
3055
- HeliosAgentMcpAuthService,
3056
- retryAfterUnauthorizedRefresh,
3057
- formatHeliosLoginPrompt,
3058
- HeliosAgentMcpAccountService,
3059
- HeliosAgentMcpDocsService,
3060
- getDefaultHeliosAgentMcpDocsRoot,
3061
- HeliosAgentMcpLedgerService,
3062
- DEFAULT_SNAPSHOT_TOP,
3063
- DEFAULT_SNAPSHOT_FIELDS,
3064
- withSnapshotDefaults,
3065
- topOfSnapshot,
3066
- compactSymbolDetail,
3067
- HeliosAgentMcpMarketService,
3068
- HeliosAgentMcpProviderService,
3069
- getDefaultHeliosAgentMcpSessionPath,
3070
- pendingAgentLoginSchema,
3071
- FileAgentSessionStore,
3072
- MemoryAgentMcpSessionStore,
3073
- HeliosAgentMcpTradingService,
3074
- createHeliosDocsToolDefinitions,
3075
- createHeliosAuthToolDefinitions,
3076
- createHeliosProviderToolDefinitions,
3077
- createHeliosAccountToolDefinitions,
3078
- createHeliosLedgerToolDefinitions,
3079
- createHeliosMarketToolDefinitions,
3080
- createHeliosTradingToolDefinitions,
3081
- createHeliosAgentMcpServer,
3082
- toolAnnotations,
3083
- withDataText
3084
- };