@pgnio/helios-mcp 0.2.0 → 0.2.1

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