fixparser-plugin-mcp 9.1.7-9d6b5ca3 → 9.1.7-9eab5b4d

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/MCPRemote.ts
@@ -39,1212 +29,29 @@ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
39
29
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
40
30
  var import_types = require("@modelcontextprotocol/sdk/types.js");
41
31
  var import_zod = require("zod");
42
-
43
- // src/MCPBase.ts
44
- var MCPBase = class {
32
+ var import_fixparser = require("fixparser");
33
+ var transports = {};
34
+ var MCPRemote = class {
35
+ /**
36
+ * Port number the server will listen on.
37
+ * @private
38
+ */
39
+ port;
45
40
  /**
46
41
  * Optional logger instance for diagnostics and output.
47
- * @protected
42
+ * @private
48
43
  */
49
44
  logger;
50
45
  /**
51
46
  * FIXParser instance, set during plugin register().
52
- * @protected
53
- */
54
- parser;
55
- /**
56
- * Called when server is setup and listening.
57
- * @protected
58
- */
59
- onReady = void 0;
60
- /**
61
- * Map to store verified orders before execution
62
- * @protected
63
- */
64
- verifiedOrders = /* @__PURE__ */ new Map();
65
- /**
66
- * Map to store pending market data requests
67
- * @protected
68
- */
69
- pendingRequests = /* @__PURE__ */ new Map();
70
- /**
71
- * Map to store market data prices
72
- * @protected
73
- */
74
- marketDataPrices = /* @__PURE__ */ new Map();
75
- /**
76
- * Maximum number of price history entries to keep per symbol
77
- * @protected
78
- */
79
- MAX_PRICE_HISTORY = 1e5;
80
- constructor({ logger, onReady }) {
81
- this.logger = logger;
82
- this.onReady = onReady;
83
- }
84
- };
85
-
86
- // src/schemas/schemas.ts
87
- var toolSchemas = {
88
- parse: {
89
- description: "Parses a FIX message and describes it in plain language",
90
- schema: {
91
- type: "object",
92
- properties: {
93
- fixString: { type: "string" }
94
- },
95
- required: ["fixString"]
96
- }
97
- },
98
- parseToJSON: {
99
- description: "Parses a FIX message into JSON",
100
- schema: {
101
- type: "object",
102
- properties: {
103
- fixString: { type: "string" }
104
- },
105
- required: ["fixString"]
106
- }
107
- },
108
- verifyOrder: {
109
- description: "Verifies order parameters before execution. verifyOrder must be called before executeOrder.",
110
- schema: {
111
- type: "object",
112
- properties: {
113
- clOrdID: { type: "string" },
114
- handlInst: {
115
- type: "string",
116
- enum: ["1", "2", "3"],
117
- description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
118
- },
119
- quantity: { type: "string" },
120
- price: { type: "string" },
121
- ordType: {
122
- type: "string",
123
- enum: [
124
- "1",
125
- "2",
126
- "3",
127
- "4",
128
- "5",
129
- "6",
130
- "7",
131
- "8",
132
- "9",
133
- "A",
134
- "B",
135
- "C",
136
- "D",
137
- "E",
138
- "F",
139
- "G",
140
- "H",
141
- "I",
142
- "J",
143
- "K",
144
- "L",
145
- "M",
146
- "P",
147
- "Q",
148
- "R",
149
- "S"
150
- ],
151
- description: "Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"
152
- },
153
- side: {
154
- type: "string",
155
- enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
156
- description: "Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"
157
- },
158
- symbol: { type: "string" },
159
- timeInForce: {
160
- type: "string",
161
- enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
162
- description: "Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"
163
- }
164
- },
165
- required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
166
- }
167
- },
168
- executeOrder: {
169
- description: "Executes a verified order. verifyOrder must be called before executeOrder.",
170
- schema: {
171
- type: "object",
172
- properties: {
173
- clOrdID: { type: "string" },
174
- handlInst: {
175
- type: "string",
176
- enum: ["1", "2", "3"],
177
- description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
178
- },
179
- quantity: { type: "string" },
180
- price: { type: "string" },
181
- ordType: {
182
- type: "string",
183
- enum: [
184
- "1",
185
- "2",
186
- "3",
187
- "4",
188
- "5",
189
- "6",
190
- "7",
191
- "8",
192
- "9",
193
- "A",
194
- "B",
195
- "C",
196
- "D",
197
- "E",
198
- "F",
199
- "G",
200
- "H",
201
- "I",
202
- "J",
203
- "K",
204
- "L",
205
- "M",
206
- "P",
207
- "Q",
208
- "R",
209
- "S"
210
- ],
211
- description: "Order Type: 1=Market, 2=Limit, 3=Stop, 4=StopLimit, 5=MarketOnClose, 6=WithOrWithout, 7=LimitOrBetter, 8=LimitWithOrWithout, 9=OnBasis, A=OnClose, B=LimitOnClose, C=ForexMarket, D=PreviouslyQuoted, E=PreviouslyIndicated, F=ForexLimit, G=ForexSwap, H=ForexPreviouslyQuoted, I=Funari, J=MarketIfTouched, K=MarketWithLeftOverAsLimit, L=PreviousFundValuationPoint, M=NextFundValuationPoint, P=Pegged, Q=CounterOrderSelection, R=StopOnBidOrOffer, S=StopLimitOnBidOrOffer"
212
- },
213
- side: {
214
- type: "string",
215
- enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
216
- description: "Side: 1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed"
217
- },
218
- symbol: { type: "string" },
219
- timeInForce: {
220
- type: "string",
221
- enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
222
- description: "Time In Force: 0=Day, 1=GoodTillCancel, 2=AtTheOpening, 3=ImmediateOrCancel, 4=FillOrKill, 5=GoodTillCrossing, 6=GoodTillDate, 7=AtTheClose, 8=GoodThroughCrossing, 9=AtCrossing, A=GoodForTime, B=GoodForAuction, C=GoodForMonth"
223
- }
224
- },
225
- required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
226
- }
227
- },
228
- marketDataRequest: {
229
- description: "Requests market data for specified symbols",
230
- schema: {
231
- type: "object",
232
- properties: {
233
- mdUpdateType: {
234
- type: "string",
235
- enum: ["0", "1"],
236
- description: "Market Data Update Type: 0=Full Refresh, 1=Incremental Refresh"
237
- },
238
- symbols: { type: "array", items: { type: "string" } },
239
- mdReqID: { type: "string" },
240
- subscriptionRequestType: {
241
- type: "string",
242
- enum: ["0", "1", "2"],
243
- description: "Subscription Request Type: 0=Snapshot, 1=Snapshot + Updates, 2=Disable Previous Snapshot + Update Request"
244
- },
245
- mdEntryTypes: {
246
- type: "array",
247
- items: {
248
- type: "string",
249
- enum: [
250
- "0",
251
- "1",
252
- "2",
253
- "3",
254
- "4",
255
- "5",
256
- "6",
257
- "7",
258
- "8",
259
- "9",
260
- "A",
261
- "B",
262
- "C",
263
- "D",
264
- "E",
265
- "F",
266
- "G",
267
- "H",
268
- "I",
269
- "J",
270
- "K",
271
- "L",
272
- "M",
273
- "N",
274
- "O",
275
- "P",
276
- "Q",
277
- "R",
278
- "S",
279
- "T",
280
- "U",
281
- "V",
282
- "W",
283
- "X",
284
- "Y",
285
- "Z"
286
- ]
287
- },
288
- description: "Market Data Entry Types: 0=Bid, 1=Offer, 2=Trade, 3=Index Value, 4=Opening Price, 5=Closing Price, 6=Settlement Price, 7=High Price, 8=Low Price, 9=Trade Volume, A=Open Interest, B=Simulated Sell Price, C=Simulated Buy Price, D=Empty Book, E=Session High Bid, F=Session Low Offer, G=Fixing Price, H=Electronic Volume, I=Threshold Limits and Price Band Variation, J=Clearing Price, K=Open Interest Change, L=Last Trade Price, M=Last Trade Volume, N=Last Trade Time, O=Last Trade Tick, P=Last Trade Exchange, Q=Last Trade ID, R=Last Trade Side, S=Last Trade Price Change, T=Last Trade Price Change Percent, U=Last Trade Price Change Basis Points, V=Last Trade Price Change Points, W=Last Trade Price Change Ticks, X=Last Trade Price Change Ticks Percent, Y=Last Trade Price Change Ticks Basis Points, Z=Last Trade Price Change Ticks Points"
289
- }
290
- },
291
- required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType"]
292
- }
293
- },
294
- getStockGraph: {
295
- description: "Generates a price chart for a given symbol",
296
- schema: {
297
- type: "object",
298
- properties: {
299
- symbol: { type: "string" }
300
- },
301
- required: ["symbol"]
302
- }
303
- },
304
- getStockPriceHistory: {
305
- description: "Returns price history for a given symbol",
306
- schema: {
307
- type: "object",
308
- properties: {
309
- symbol: { type: "string" }
310
- },
311
- required: ["symbol"]
312
- }
313
- }
314
- };
315
-
316
- // src/tools/marketData.ts
317
- var import_fixparser = require("fixparser");
318
- var import_quickchart_js = __toESM(require("quickchart-js"), 1);
319
- var createMarketDataRequestHandler = (parser, pendingRequests) => {
320
- return async (args) => {
321
- try {
322
- parser.logger.log({
323
- level: "info",
324
- message: `Sending market data request for symbols: ${args.symbols.join(", ")}`
325
- });
326
- const response = new Promise((resolve) => {
327
- pendingRequests.set(args.mdReqID, resolve);
328
- parser.logger.log({
329
- level: "info",
330
- message: `Registered callback for market data request ID: ${args.mdReqID}`
331
- });
332
- });
333
- const entryTypes = args.mdEntryTypes || [
334
- import_fixparser.MDEntryType.Bid,
335
- import_fixparser.MDEntryType.Offer,
336
- import_fixparser.MDEntryType.Trade,
337
- import_fixparser.MDEntryType.IndexValue,
338
- import_fixparser.MDEntryType.OpeningPrice,
339
- import_fixparser.MDEntryType.ClosingPrice,
340
- import_fixparser.MDEntryType.SettlementPrice,
341
- import_fixparser.MDEntryType.TradingSessionHighPrice,
342
- import_fixparser.MDEntryType.TradingSessionLowPrice,
343
- import_fixparser.MDEntryType.VWAP,
344
- import_fixparser.MDEntryType.Imbalance,
345
- import_fixparser.MDEntryType.TradeVolume,
346
- import_fixparser.MDEntryType.OpenInterest,
347
- import_fixparser.MDEntryType.CompositeUnderlyingPrice,
348
- import_fixparser.MDEntryType.SimulatedSellPrice,
349
- import_fixparser.MDEntryType.SimulatedBuyPrice,
350
- import_fixparser.MDEntryType.MarginRate,
351
- import_fixparser.MDEntryType.MidPrice,
352
- import_fixparser.MDEntryType.EmptyBook,
353
- import_fixparser.MDEntryType.SettleHighPrice,
354
- import_fixparser.MDEntryType.SettleLowPrice,
355
- import_fixparser.MDEntryType.PriorSettlePrice,
356
- import_fixparser.MDEntryType.SessionHighBid,
357
- import_fixparser.MDEntryType.SessionLowOffer,
358
- import_fixparser.MDEntryType.EarlyPrices,
359
- import_fixparser.MDEntryType.AuctionClearingPrice,
360
- import_fixparser.MDEntryType.SwapValueFactor,
361
- import_fixparser.MDEntryType.DailyValueAdjustmentForLongPositions,
362
- import_fixparser.MDEntryType.CumulativeValueAdjustmentForLongPositions,
363
- import_fixparser.MDEntryType.DailyValueAdjustmentForShortPositions,
364
- import_fixparser.MDEntryType.CumulativeValueAdjustmentForShortPositions,
365
- import_fixparser.MDEntryType.FixingPrice,
366
- import_fixparser.MDEntryType.CashRate,
367
- import_fixparser.MDEntryType.RecoveryRate,
368
- import_fixparser.MDEntryType.RecoveryRateForLong,
369
- import_fixparser.MDEntryType.RecoveryRateForShort,
370
- import_fixparser.MDEntryType.MarketBid,
371
- import_fixparser.MDEntryType.MarketOffer,
372
- import_fixparser.MDEntryType.ShortSaleMinPrice,
373
- import_fixparser.MDEntryType.PreviousClosingPrice,
374
- import_fixparser.MDEntryType.ThresholdLimitPriceBanding,
375
- import_fixparser.MDEntryType.DailyFinancingValue,
376
- import_fixparser.MDEntryType.AccruedFinancingValue,
377
- import_fixparser.MDEntryType.TWAP
378
- ];
379
- const messageFields = [
380
- new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
381
- new import_fixparser.Field(import_fixparser.Fields.SenderCompID, parser.sender),
382
- new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
383
- new import_fixparser.Field(import_fixparser.Fields.TargetCompID, parser.target),
384
- new import_fixparser.Field(import_fixparser.Fields.SendingTime, parser.getTimestamp()),
385
- new import_fixparser.Field(import_fixparser.Fields.MDReqID, args.mdReqID),
386
- new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, args.subscriptionRequestType),
387
- new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
388
- new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, args.mdUpdateType)
389
- ];
390
- messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, args.symbols.length));
391
- args.symbols.forEach((symbol) => {
392
- messageFields.push(new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol));
393
- });
394
- messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, entryTypes.length));
395
- entryTypes.forEach((entryType) => {
396
- messageFields.push(new import_fixparser.Field(import_fixparser.Fields.MDEntryType, entryType));
397
- });
398
- const mdr = parser.createMessage(...messageFields);
399
- if (!parser.connected) {
400
- parser.logger.log({
401
- level: "error",
402
- message: "Not connected. Cannot send market data request."
403
- });
404
- return {
405
- content: [
406
- {
407
- type: "text",
408
- text: "Error: Not connected. Ignoring message.",
409
- uri: "marketDataRequest"
410
- }
411
- ],
412
- isError: true
413
- };
414
- }
415
- parser.logger.log({
416
- level: "info",
417
- message: `Sending market data request message: ${JSON.stringify(mdr?.toFIXJSON())}`
418
- });
419
- parser.send(mdr);
420
- const fixData = await response;
421
- parser.logger.log({
422
- level: "info",
423
- message: `Received market data response for request ID: ${args.mdReqID}`
424
- });
425
- return {
426
- content: [
427
- {
428
- type: "text",
429
- text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
430
- uri: "marketDataRequest"
431
- }
432
- ]
433
- };
434
- } catch (error) {
435
- return {
436
- content: [
437
- {
438
- type: "text",
439
- text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
440
- uri: "marketDataRequest"
441
- }
442
- ],
443
- isError: true
444
- };
445
- }
446
- };
447
- };
448
- var createGetStockGraphHandler = (marketDataPrices) => {
449
- return async (args) => {
450
- try {
451
- const symbol = args.symbol;
452
- const priceHistory = marketDataPrices.get(symbol) || [];
453
- if (priceHistory.length === 0) {
454
- return {
455
- content: [
456
- {
457
- type: "text",
458
- text: `No price data available for ${symbol}`,
459
- uri: "getStockGraph"
460
- }
461
- ]
462
- };
463
- }
464
- const chart = new import_quickchart_js.default();
465
- chart.setWidth(1200);
466
- chart.setHeight(600);
467
- chart.setBackgroundColor("transparent");
468
- const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
469
- const bidData = priceHistory.map((point) => point.bid);
470
- const offerData = priceHistory.map((point) => point.offer);
471
- const spreadData = priceHistory.map((point) => point.spread);
472
- const volumeData = priceHistory.map((point) => point.volume);
473
- const tradeData = priceHistory.map((point) => point.trade);
474
- const vwapData = priceHistory.map((point) => point.vwap);
475
- const twapData = priceHistory.map((point) => point.twap);
476
- const config = {
477
- type: "line",
478
- data: {
479
- labels,
480
- datasets: [
481
- {
482
- label: "Bid",
483
- data: bidData,
484
- borderColor: "#28a745",
485
- backgroundColor: "rgba(40, 167, 69, 0.1)",
486
- fill: false,
487
- tension: 0.4
488
- },
489
- {
490
- label: "Offer",
491
- data: offerData,
492
- borderColor: "#dc3545",
493
- backgroundColor: "rgba(220, 53, 69, 0.1)",
494
- fill: false,
495
- tension: 0.4
496
- },
497
- {
498
- label: "Spread",
499
- data: spreadData,
500
- borderColor: "#6c757d",
501
- backgroundColor: "rgba(108, 117, 125, 0.1)",
502
- fill: false,
503
- tension: 0.4
504
- },
505
- {
506
- label: "Trade",
507
- data: tradeData,
508
- borderColor: "#ffc107",
509
- backgroundColor: "rgba(255, 193, 7, 0.1)",
510
- fill: false,
511
- tension: 0.4
512
- },
513
- {
514
- label: "VWAP",
515
- data: vwapData,
516
- borderColor: "#17a2b8",
517
- backgroundColor: "rgba(23, 162, 184, 0.1)",
518
- fill: false,
519
- tension: 0.4
520
- },
521
- {
522
- label: "TWAP",
523
- data: twapData,
524
- borderColor: "#6610f2",
525
- backgroundColor: "rgba(102, 16, 242, 0.1)",
526
- fill: false,
527
- tension: 0.4
528
- },
529
- {
530
- label: "Volume",
531
- data: volumeData,
532
- borderColor: "#007bff",
533
- backgroundColor: "rgba(0, 123, 255, 0.1)",
534
- fill: true,
535
- tension: 0.4
536
- }
537
- ]
538
- },
539
- options: {
540
- responsive: true,
541
- plugins: {
542
- title: {
543
- display: true,
544
- text: `${symbol} Market Data`
545
- }
546
- },
547
- scales: {
548
- y: {
549
- beginAtZero: false
550
- }
551
- }
552
- }
553
- };
554
- chart.setConfig(config);
555
- const imageBuffer = await chart.toBinary();
556
- const base64 = imageBuffer.toString("base64");
557
- return {
558
- content: [
559
- {
560
- type: "resource",
561
- resource: {
562
- uri: "resource://graph",
563
- mimeType: "image/png",
564
- blob: base64
565
- }
566
- }
567
- ]
568
- };
569
- } catch (error) {
570
- return {
571
- content: [
572
- {
573
- type: "text",
574
- text: `Error: ${error instanceof Error ? error.message : "Failed to generate graph"}`,
575
- uri: "getStockGraph"
576
- }
577
- ],
578
- isError: true
579
- };
580
- }
581
- };
582
- };
583
- var createGetStockPriceHistoryHandler = (marketDataPrices) => {
584
- return async (args) => {
585
- try {
586
- const symbol = args.symbol;
587
- const priceHistory = marketDataPrices.get(symbol) || [];
588
- if (priceHistory.length === 0) {
589
- return {
590
- content: [
591
- {
592
- type: "text",
593
- text: `No price data available for ${symbol}`,
594
- uri: "getStockPriceHistory"
595
- }
596
- ]
597
- };
598
- }
599
- return {
600
- content: [
601
- {
602
- type: "text",
603
- text: JSON.stringify(
604
- {
605
- symbol,
606
- count: priceHistory.length,
607
- data: priceHistory.map((point) => ({
608
- timestamp: new Date(point.timestamp).toISOString(),
609
- bid: point.bid,
610
- offer: point.offer,
611
- spread: point.spread,
612
- volume: point.volume,
613
- trade: point.trade,
614
- indexValue: point.indexValue,
615
- openingPrice: point.openingPrice,
616
- closingPrice: point.closingPrice,
617
- settlementPrice: point.settlementPrice,
618
- tradingSessionHighPrice: point.tradingSessionHighPrice,
619
- tradingSessionLowPrice: point.tradingSessionLowPrice,
620
- vwap: point.vwap,
621
- imbalance: point.imbalance,
622
- openInterest: point.openInterest,
623
- compositeUnderlyingPrice: point.compositeUnderlyingPrice,
624
- simulatedSellPrice: point.simulatedSellPrice,
625
- simulatedBuyPrice: point.simulatedBuyPrice,
626
- marginRate: point.marginRate,
627
- midPrice: point.midPrice,
628
- emptyBook: point.emptyBook,
629
- settleHighPrice: point.settleHighPrice,
630
- settleLowPrice: point.settleLowPrice,
631
- priorSettlePrice: point.priorSettlePrice,
632
- sessionHighBid: point.sessionHighBid,
633
- sessionLowOffer: point.sessionLowOffer,
634
- earlyPrices: point.earlyPrices,
635
- auctionClearingPrice: point.auctionClearingPrice,
636
- swapValueFactor: point.swapValueFactor,
637
- dailyValueAdjustmentForLongPositions: point.dailyValueAdjustmentForLongPositions,
638
- cumulativeValueAdjustmentForLongPositions: point.cumulativeValueAdjustmentForLongPositions,
639
- dailyValueAdjustmentForShortPositions: point.dailyValueAdjustmentForShortPositions,
640
- cumulativeValueAdjustmentForShortPositions: point.cumulativeValueAdjustmentForShortPositions,
641
- fixingPrice: point.fixingPrice,
642
- cashRate: point.cashRate,
643
- recoveryRate: point.recoveryRate,
644
- recoveryRateForLong: point.recoveryRateForLong,
645
- recoveryRateForShort: point.recoveryRateForShort,
646
- marketBid: point.marketBid,
647
- marketOffer: point.marketOffer,
648
- shortSaleMinPrice: point.shortSaleMinPrice,
649
- previousClosingPrice: point.previousClosingPrice,
650
- thresholdLimitPriceBanding: point.thresholdLimitPriceBanding,
651
- dailyFinancingValue: point.dailyFinancingValue,
652
- accruedFinancingValue: point.accruedFinancingValue,
653
- twap: point.twap
654
- }))
655
- },
656
- null,
657
- 2
658
- ),
659
- uri: "getStockPriceHistory"
660
- }
661
- ]
662
- };
663
- } catch (error) {
664
- return {
665
- content: [
666
- {
667
- type: "text",
668
- text: `Error: ${error instanceof Error ? error.message : "Failed to get price history"}`,
669
- uri: "getStockPriceHistory"
670
- }
671
- ],
672
- isError: true
673
- };
674
- }
675
- };
676
- };
677
-
678
- // src/tools/order.ts
679
- var import_fixparser2 = require("fixparser");
680
- var ordTypeNames = {
681
- "1": "Market",
682
- "2": "Limit",
683
- "3": "Stop",
684
- "4": "StopLimit",
685
- "5": "MarketOnClose",
686
- "6": "WithOrWithout",
687
- "7": "LimitOrBetter",
688
- "8": "LimitWithOrWithout",
689
- "9": "OnBasis",
690
- A: "OnClose",
691
- B: "LimitOnClose",
692
- C: "ForexMarket",
693
- D: "PreviouslyQuoted",
694
- E: "PreviouslyIndicated",
695
- F: "ForexLimit",
696
- G: "ForexSwap",
697
- H: "ForexPreviouslyQuoted",
698
- I: "Funari",
699
- J: "MarketIfTouched",
700
- K: "MarketWithLeftOverAsLimit",
701
- L: "PreviousFundValuationPoint",
702
- M: "NextFundValuationPoint",
703
- P: "Pegged",
704
- Q: "CounterOrderSelection",
705
- R: "StopOnBidOrOffer",
706
- S: "StopLimitOnBidOrOffer"
707
- };
708
- var sideNames = {
709
- "1": "Buy",
710
- "2": "Sell",
711
- "3": "BuyMinus",
712
- "4": "SellPlus",
713
- "5": "SellShort",
714
- "6": "SellShortExempt",
715
- "7": "Undisclosed",
716
- "8": "Cross",
717
- "9": "CrossShort",
718
- A: "CrossShortExempt",
719
- B: "AsDefined",
720
- C: "Opposite",
721
- D: "Subscribe",
722
- E: "Redeem",
723
- F: "Lend",
724
- G: "Borrow",
725
- H: "SellUndisclosed"
726
- };
727
- var timeInForceNames = {
728
- "0": "Day",
729
- "1": "GoodTillCancel",
730
- "2": "AtTheOpening",
731
- "3": "ImmediateOrCancel",
732
- "4": "FillOrKill",
733
- "5": "GoodTillCrossing",
734
- "6": "GoodTillDate",
735
- "7": "AtTheClose",
736
- "8": "GoodThroughCrossing",
737
- "9": "AtCrossing",
738
- A: "GoodForTime",
739
- B: "GoodForAuction",
740
- C: "GoodForMonth"
741
- };
742
- var handlInstNames = {
743
- "1": "AutomatedExecutionNoIntervention",
744
- "2": "AutomatedExecutionInterventionOK",
745
- "3": "ManualOrder"
746
- };
747
- var createVerifyOrderHandler = (parser, verifiedOrders) => {
748
- return async (args) => {
749
- try {
750
- verifiedOrders.set(args.clOrdID, {
751
- clOrdID: args.clOrdID,
752
- handlInst: args.handlInst,
753
- quantity: Number.parseFloat(String(args.quantity)),
754
- price: Number.parseFloat(String(args.price)),
755
- ordType: args.ordType,
756
- side: args.side,
757
- symbol: args.symbol,
758
- timeInForce: args.timeInForce
759
- });
760
- return {
761
- content: [
762
- {
763
- type: "text",
764
- text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
765
-
766
- Parameters verified:
767
- - ClOrdID: ${args.clOrdID}
768
- - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
769
- - Quantity: ${args.quantity}
770
- - Price: ${args.price}
771
- - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
772
- - Side: ${args.side} (${sideNames[args.side]})
773
- - Symbol: ${args.symbol}
774
- - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
775
-
776
- To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,
777
- uri: "verifyOrder"
778
- }
779
- ]
780
- };
781
- } catch (error) {
782
- return {
783
- content: [
784
- {
785
- type: "text",
786
- text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
787
- uri: "verifyOrder"
788
- }
789
- ],
790
- isError: true
791
- };
792
- }
793
- };
794
- };
795
- var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
796
- return async (args) => {
797
- try {
798
- const verifiedOrder = verifiedOrders.get(args.clOrdID);
799
- if (!verifiedOrder) {
800
- return {
801
- content: [
802
- {
803
- type: "text",
804
- text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
805
- uri: "executeOrder"
806
- }
807
- ],
808
- isError: true
809
- };
810
- }
811
- if (verifiedOrder.handlInst !== args.handlInst || verifiedOrder.quantity !== Number.parseFloat(String(args.quantity)) || verifiedOrder.price !== Number.parseFloat(String(args.price)) || verifiedOrder.ordType !== args.ordType || verifiedOrder.side !== args.side || verifiedOrder.symbol !== args.symbol || verifiedOrder.timeInForce !== args.timeInForce) {
812
- return {
813
- content: [
814
- {
815
- type: "text",
816
- text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
817
- uri: "executeOrder"
818
- }
819
- ],
820
- isError: true
821
- };
822
- }
823
- const response = new Promise((resolve) => {
824
- pendingRequests.set(args.clOrdID, resolve);
825
- });
826
- const order = parser.createMessage(
827
- new import_fixparser2.Field(import_fixparser2.Fields.MsgType, import_fixparser2.Messages.NewOrderSingle),
828
- new import_fixparser2.Field(import_fixparser2.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
829
- new import_fixparser2.Field(import_fixparser2.Fields.SenderCompID, parser.sender),
830
- new import_fixparser2.Field(import_fixparser2.Fields.TargetCompID, parser.target),
831
- new import_fixparser2.Field(import_fixparser2.Fields.SendingTime, parser.getTimestamp()),
832
- new import_fixparser2.Field(import_fixparser2.Fields.ClOrdID, args.clOrdID),
833
- new import_fixparser2.Field(import_fixparser2.Fields.Side, args.side),
834
- new import_fixparser2.Field(import_fixparser2.Fields.Symbol, args.symbol),
835
- new import_fixparser2.Field(import_fixparser2.Fields.OrderQty, Number.parseFloat(String(args.quantity))),
836
- new import_fixparser2.Field(import_fixparser2.Fields.Price, Number.parseFloat(String(args.price))),
837
- new import_fixparser2.Field(import_fixparser2.Fields.OrdType, args.ordType),
838
- new import_fixparser2.Field(import_fixparser2.Fields.HandlInst, args.handlInst),
839
- new import_fixparser2.Field(import_fixparser2.Fields.TimeInForce, args.timeInForce),
840
- new import_fixparser2.Field(import_fixparser2.Fields.TransactTime, parser.getTimestamp())
841
- );
842
- if (!parser.connected) {
843
- return {
844
- content: [
845
- {
846
- type: "text",
847
- text: "Error: Not connected. Ignoring message.",
848
- uri: "executeOrder"
849
- }
850
- ],
851
- isError: true
852
- };
853
- }
854
- parser.send(order);
855
- const fixData = await response;
856
- verifiedOrders.delete(args.clOrdID);
857
- return {
858
- content: [
859
- {
860
- type: "text",
861
- text: fixData.messageType === import_fixparser2.Messages.Reject ? `Reject message for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}` : `Execution Report for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`,
862
- uri: "executeOrder"
863
- }
864
- ]
865
- };
866
- } catch (error) {
867
- return {
868
- content: [
869
- {
870
- type: "text",
871
- text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
872
- uri: "executeOrder"
873
- }
874
- ],
875
- isError: true
876
- };
877
- }
878
- };
879
- };
880
-
881
- // src/tools/parse.ts
882
- var createParseHandler = (parser) => {
883
- return async (args) => {
884
- try {
885
- const parsedMessage = parser.parse(args.fixString);
886
- if (!parsedMessage || parsedMessage.length === 0) {
887
- return {
888
- content: [
889
- {
890
- type: "text",
891
- text: "Error: Failed to parse FIX string",
892
- uri: "parse"
893
- }
894
- ],
895
- isError: true
896
- };
897
- }
898
- return {
899
- content: [
900
- {
901
- type: "text",
902
- text: `${parsedMessage[0].description}
903
- ${parsedMessage[0].messageTypeDescription}`,
904
- uri: "parse"
905
- }
906
- ]
907
- };
908
- } catch (error) {
909
- return {
910
- content: [
911
- {
912
- type: "text",
913
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
914
- uri: "parse"
915
- }
916
- ],
917
- isError: true
918
- };
919
- }
920
- };
921
- };
922
-
923
- // src/tools/parseToJSON.ts
924
- var createParseToJSONHandler = (parser) => {
925
- return async (args) => {
926
- try {
927
- const parsedMessage = parser.parse(args.fixString);
928
- if (!parsedMessage || parsedMessage.length === 0) {
929
- return {
930
- content: [
931
- {
932
- type: "text",
933
- text: "Error: Failed to parse FIX string",
934
- uri: "parseToJSON"
935
- }
936
- ],
937
- isError: true
938
- };
939
- }
940
- return {
941
- content: [
942
- {
943
- type: "text",
944
- text: `${parsedMessage[0].toFIXJSON()}`,
945
- uri: "parseToJSON"
946
- }
947
- ]
948
- };
949
- } catch (error) {
950
- return {
951
- content: [
952
- {
953
- type: "text",
954
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
955
- uri: "parseToJSON"
956
- }
957
- ],
958
- isError: true
959
- };
960
- }
961
- };
962
- };
963
-
964
- // src/tools/index.ts
965
- var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
966
- parse: createParseHandler(parser),
967
- parseToJSON: createParseToJSONHandler(parser),
968
- verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
969
- executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
970
- marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
971
- getStockGraph: createGetStockGraphHandler(marketDataPrices),
972
- getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
973
- });
974
-
975
- // src/utils/messageHandler.ts
976
- var import_fixparser3 = require("fixparser");
977
- function getEnumValue(enumObj, name) {
978
- return enumObj[name] || name;
979
- }
980
- function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
981
- const msgType = message.messageType;
982
- if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh) {
983
- const symbol = message.getField(import_fixparser3.Fields.Symbol)?.value;
984
- const fixJson = message.toFIXJSON();
985
- const entries = fixJson.Body?.NoMDEntries || [];
986
- const data = {
987
- timestamp: Date.now(),
988
- bid: 0,
989
- offer: 0,
990
- spread: 0,
991
- volume: 0,
992
- trade: 0,
993
- indexValue: 0,
994
- openingPrice: 0,
995
- closingPrice: 0,
996
- settlementPrice: 0,
997
- tradingSessionHighPrice: 0,
998
- tradingSessionLowPrice: 0,
999
- vwap: 0,
1000
- imbalance: 0,
1001
- openInterest: 0,
1002
- compositeUnderlyingPrice: 0,
1003
- simulatedSellPrice: 0,
1004
- simulatedBuyPrice: 0,
1005
- marginRate: 0,
1006
- midPrice: 0,
1007
- emptyBook: 0,
1008
- settleHighPrice: 0,
1009
- settleLowPrice: 0,
1010
- priorSettlePrice: 0,
1011
- sessionHighBid: 0,
1012
- sessionLowOffer: 0,
1013
- earlyPrices: 0,
1014
- auctionClearingPrice: 0,
1015
- swapValueFactor: 0,
1016
- dailyValueAdjustmentForLongPositions: 0,
1017
- cumulativeValueAdjustmentForLongPositions: 0,
1018
- dailyValueAdjustmentForShortPositions: 0,
1019
- cumulativeValueAdjustmentForShortPositions: 0,
1020
- fixingPrice: 0,
1021
- cashRate: 0,
1022
- recoveryRate: 0,
1023
- recoveryRateForLong: 0,
1024
- recoveryRateForShort: 0,
1025
- marketBid: 0,
1026
- marketOffer: 0,
1027
- shortSaleMinPrice: 0,
1028
- previousClosingPrice: 0,
1029
- thresholdLimitPriceBanding: 0,
1030
- dailyFinancingValue: 0,
1031
- accruedFinancingValue: 0,
1032
- twap: 0
1033
- };
1034
- for (const entry of entries) {
1035
- const entryType = entry.MDEntryType;
1036
- const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
1037
- const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
1038
- const enumValue = getEnumValue(import_fixparser3.MDEntryType, entryType);
1039
- switch (enumValue) {
1040
- case import_fixparser3.MDEntryType.Bid:
1041
- data.bid = price;
1042
- break;
1043
- case import_fixparser3.MDEntryType.Offer:
1044
- data.offer = price;
1045
- break;
1046
- case import_fixparser3.MDEntryType.Trade:
1047
- data.trade = price;
1048
- break;
1049
- case import_fixparser3.MDEntryType.IndexValue:
1050
- data.indexValue = price;
1051
- break;
1052
- case import_fixparser3.MDEntryType.OpeningPrice:
1053
- data.openingPrice = price;
1054
- break;
1055
- case import_fixparser3.MDEntryType.ClosingPrice:
1056
- data.closingPrice = price;
1057
- break;
1058
- case import_fixparser3.MDEntryType.SettlementPrice:
1059
- data.settlementPrice = price;
1060
- break;
1061
- case import_fixparser3.MDEntryType.TradingSessionHighPrice:
1062
- data.tradingSessionHighPrice = price;
1063
- break;
1064
- case import_fixparser3.MDEntryType.TradingSessionLowPrice:
1065
- data.tradingSessionLowPrice = price;
1066
- break;
1067
- case import_fixparser3.MDEntryType.VWAP:
1068
- data.vwap = price;
1069
- break;
1070
- case import_fixparser3.MDEntryType.Imbalance:
1071
- data.imbalance = size;
1072
- break;
1073
- case import_fixparser3.MDEntryType.TradeVolume:
1074
- data.volume = size;
1075
- break;
1076
- case import_fixparser3.MDEntryType.OpenInterest:
1077
- data.openInterest = size;
1078
- break;
1079
- case import_fixparser3.MDEntryType.CompositeUnderlyingPrice:
1080
- data.compositeUnderlyingPrice = price;
1081
- break;
1082
- case import_fixparser3.MDEntryType.SimulatedSellPrice:
1083
- data.simulatedSellPrice = price;
1084
- break;
1085
- case import_fixparser3.MDEntryType.SimulatedBuyPrice:
1086
- data.simulatedBuyPrice = price;
1087
- break;
1088
- case import_fixparser3.MDEntryType.MarginRate:
1089
- data.marginRate = price;
1090
- break;
1091
- case import_fixparser3.MDEntryType.MidPrice:
1092
- data.midPrice = price;
1093
- break;
1094
- case import_fixparser3.MDEntryType.EmptyBook:
1095
- data.emptyBook = 1;
1096
- break;
1097
- case import_fixparser3.MDEntryType.SettleHighPrice:
1098
- data.settleHighPrice = price;
1099
- break;
1100
- case import_fixparser3.MDEntryType.SettleLowPrice:
1101
- data.settleLowPrice = price;
1102
- break;
1103
- case import_fixparser3.MDEntryType.PriorSettlePrice:
1104
- data.priorSettlePrice = price;
1105
- break;
1106
- case import_fixparser3.MDEntryType.SessionHighBid:
1107
- data.sessionHighBid = price;
1108
- break;
1109
- case import_fixparser3.MDEntryType.SessionLowOffer:
1110
- data.sessionLowOffer = price;
1111
- break;
1112
- case import_fixparser3.MDEntryType.EarlyPrices:
1113
- data.earlyPrices = price;
1114
- break;
1115
- case import_fixparser3.MDEntryType.AuctionClearingPrice:
1116
- data.auctionClearingPrice = price;
1117
- break;
1118
- case import_fixparser3.MDEntryType.SwapValueFactor:
1119
- data.swapValueFactor = price;
1120
- break;
1121
- case import_fixparser3.MDEntryType.DailyValueAdjustmentForLongPositions:
1122
- data.dailyValueAdjustmentForLongPositions = price;
1123
- break;
1124
- case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForLongPositions:
1125
- data.cumulativeValueAdjustmentForLongPositions = price;
1126
- break;
1127
- case import_fixparser3.MDEntryType.DailyValueAdjustmentForShortPositions:
1128
- data.dailyValueAdjustmentForShortPositions = price;
1129
- break;
1130
- case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForShortPositions:
1131
- data.cumulativeValueAdjustmentForShortPositions = price;
1132
- break;
1133
- case import_fixparser3.MDEntryType.FixingPrice:
1134
- data.fixingPrice = price;
1135
- break;
1136
- case import_fixparser3.MDEntryType.CashRate:
1137
- data.cashRate = price;
1138
- break;
1139
- case import_fixparser3.MDEntryType.RecoveryRate:
1140
- data.recoveryRate = price;
1141
- break;
1142
- case import_fixparser3.MDEntryType.RecoveryRateForLong:
1143
- data.recoveryRateForLong = price;
1144
- break;
1145
- case import_fixparser3.MDEntryType.RecoveryRateForShort:
1146
- data.recoveryRateForShort = price;
1147
- break;
1148
- case import_fixparser3.MDEntryType.MarketBid:
1149
- data.marketBid = price;
1150
- break;
1151
- case import_fixparser3.MDEntryType.MarketOffer:
1152
- data.marketOffer = price;
1153
- break;
1154
- case import_fixparser3.MDEntryType.ShortSaleMinPrice:
1155
- data.shortSaleMinPrice = price;
1156
- break;
1157
- case import_fixparser3.MDEntryType.PreviousClosingPrice:
1158
- data.previousClosingPrice = price;
1159
- break;
1160
- case import_fixparser3.MDEntryType.ThresholdLimitPriceBanding:
1161
- data.thresholdLimitPriceBanding = price;
1162
- break;
1163
- case import_fixparser3.MDEntryType.DailyFinancingValue:
1164
- data.dailyFinancingValue = price;
1165
- break;
1166
- case import_fixparser3.MDEntryType.AccruedFinancingValue:
1167
- data.accruedFinancingValue = price;
1168
- break;
1169
- case import_fixparser3.MDEntryType.TWAP:
1170
- data.twap = price;
1171
- break;
1172
- }
1173
- }
1174
- data.spread = data.offer - data.bid;
1175
- if (!marketDataPrices.has(symbol)) {
1176
- marketDataPrices.set(symbol, []);
1177
- }
1178
- const prices = marketDataPrices.get(symbol);
1179
- prices.push(data);
1180
- if (prices.length > maxPriceHistory) {
1181
- prices.splice(0, prices.length - maxPriceHistory);
1182
- }
1183
- onPriceUpdate?.(symbol, data);
1184
- const mdReqID = message.getField(import_fixparser3.Fields.MDReqID)?.value;
1185
- if (mdReqID) {
1186
- const callback = pendingRequests.get(mdReqID);
1187
- if (callback) {
1188
- callback(message);
1189
- pendingRequests.delete(mdReqID);
1190
- }
1191
- }
1192
- } else if (msgType === import_fixparser3.Messages.ExecutionReport) {
1193
- const reqId = message.getField(import_fixparser3.Fields.ClOrdID)?.value;
1194
- const callback = pendingRequests.get(reqId);
1195
- if (callback) {
1196
- callback(message);
1197
- pendingRequests.delete(reqId);
1198
- }
1199
- }
1200
- }
1201
-
1202
- // src/MCPRemote.ts
1203
- var transports = {};
1204
- function jsonSchemaToZod(schema) {
1205
- if (schema.type === "object") {
1206
- const shape = {};
1207
- for (const [key, prop] of Object.entries(schema.properties || {})) {
1208
- const propSchema = prop;
1209
- if (propSchema.type === "string") {
1210
- if (propSchema.enum) {
1211
- shape[key] = import_zod.z.enum(propSchema.enum);
1212
- } else {
1213
- shape[key] = import_zod.z.string();
1214
- }
1215
- } else if (propSchema.type === "number") {
1216
- shape[key] = import_zod.z.number();
1217
- } else if (propSchema.type === "boolean") {
1218
- shape[key] = import_zod.z.boolean();
1219
- } else if (propSchema.type === "array") {
1220
- if (propSchema.items.type === "string") {
1221
- shape[key] = import_zod.z.array(import_zod.z.string());
1222
- } else if (propSchema.items.type === "number") {
1223
- shape[key] = import_zod.z.array(import_zod.z.number());
1224
- } else if (propSchema.items.type === "boolean") {
1225
- shape[key] = import_zod.z.array(import_zod.z.boolean());
1226
- } else {
1227
- shape[key] = import_zod.z.array(import_zod.z.any());
1228
- }
1229
- } else {
1230
- shape[key] = import_zod.z.any();
1231
- }
1232
- }
1233
- return shape;
1234
- }
1235
- return {};
1236
- }
1237
- var MCPRemote = class extends MCPBase {
1238
- /**
1239
- * Port number the server will listen on.
1240
47
  * @private
1241
48
  */
1242
- port;
49
+ parser;
1243
50
  /**
1244
51
  * Node.js HTTP server instance created internally.
1245
52
  * @private
1246
53
  */
1247
- httpServer;
54
+ server;
1248
55
  /**
1249
56
  * MCP server instance handling MCP protocol logic.
1250
57
  * @private
@@ -1254,61 +61,89 @@ var MCPRemote = class extends MCPBase {
1254
61
  * Optional name of the plugin/server instance.
1255
62
  * @private
1256
63
  */
1257
- serverName;
64
+ name;
1258
65
  /**
1259
66
  * Optional version string of the plugin/server.
1260
67
  * @private
1261
68
  */
1262
- serverVersion;
69
+ version;
1263
70
  /**
1264
- * Map to store verified orders before execution
71
+ * Called when server is setup and listening.
1265
72
  * @private
1266
73
  */
1267
- verifiedOrders = /* @__PURE__ */ new Map();
74
+ onReady = void 0;
1268
75
  /**
1269
- * Map to store pending requests and their callbacks
76
+ * A map of pending market data requests, keyed by MDReqID.
77
+ * Each entry contains a resolver function that is called when the corresponding
78
+ * FIX Message is received.
1270
79
  * @private
80
+ * @type {Map<string, (data: Message) => void>}
1271
81
  */
1272
82
  pendingRequests = /* @__PURE__ */ new Map();
1273
- /**
1274
- * Map to store market data prices for each symbol
1275
- * @private
1276
- */
1277
- marketDataPrices = /* @__PURE__ */ new Map();
1278
- /**
1279
- * Maximum number of price history entries to keep per symbol
1280
- * @private
1281
- */
1282
- MAX_PRICE_HISTORY = 1e5;
1283
83
  constructor({ port, logger, onReady }) {
1284
- super({ logger, onReady });
1285
84
  this.port = port;
85
+ if (logger) this.logger = logger;
86
+ if (onReady) this.onReady = onReady;
1286
87
  }
1287
88
  async register(parser) {
1288
89
  this.parser = parser;
90
+ this.parser.addOnMessageCallback((message) => {
91
+ this.logger?.log({
92
+ level: "info",
93
+ message: `FIXParser (MCP): (${parser.protocol?.toUpperCase()}): << received ${message.description}`
94
+ });
95
+ const msgType = message.messageType;
96
+ if (msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser.Messages.ExecutionReport) {
97
+ const idField = msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh ? message.getField(import_fixparser.Fields.MDReqID) : message.getField(import_fixparser.Fields.ClOrdID);
98
+ if (idField) {
99
+ const id = idField.value;
100
+ if (typeof id === "string" || typeof id === "number") {
101
+ const callback = this.pendingRequests.get(String(id));
102
+ if (callback) {
103
+ callback(message);
104
+ this.pendingRequests.delete(String(id));
105
+ }
106
+ }
107
+ }
108
+ }
109
+ });
1289
110
  this.logger = parser.logger;
1290
111
  this.logger?.log({
1291
112
  level: "info",
1292
113
  message: `FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`
1293
114
  });
1294
- this.parser.addOnMessageCallback((message) => {
1295
- if (this.parser) {
1296
- handleMessage(
1297
- message,
1298
- this.parser,
1299
- this.pendingRequests,
1300
- this.marketDataPrices,
1301
- this.MAX_PRICE_HISTORY
1302
- );
1303
- }
1304
- });
1305
- this.httpServer = (0, import_node_http.createServer)(async (req, res) => {
115
+ this.server = (0, import_node_http.createServer)(async (req, res) => {
1306
116
  if (!req.url || !req.method) {
1307
117
  res.writeHead(400);
1308
118
  res.end("Bad Request");
1309
119
  return;
1310
120
  }
1311
- if (req.url === "/mcp") {
121
+ const url = new URL(req.url, `http://${req.headers.host}`);
122
+ if (url.pathname === "/.well-known/oauth-authorization-server") {
123
+ const config = {
124
+ issuer: "https://accounts.google.com",
125
+ authorization_endpoint: "https://accounts.google.com/o/oauth2/v2/auth",
126
+ token_endpoint: "https://oauth2.googleapis.com/token",
127
+ jwks_uri: "https://www.googleapis.com/oauth2/v3/certs",
128
+ response_types_supported: [
129
+ "code",
130
+ "token",
131
+ "id_token",
132
+ "code token",
133
+ "code id_token",
134
+ "token id_token",
135
+ "code token id_token"
136
+ ],
137
+ subject_types_supported: ["public"],
138
+ id_token_signing_alg_values_supported: ["RS256"],
139
+ scopes_supported: ["openid", "email", "profile"],
140
+ token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"]
141
+ };
142
+ res.writeHead(200, { "Content-Type": "application/json" });
143
+ res.end(JSON.stringify(config));
144
+ return;
145
+ }
146
+ if (url.pathname === "/") {
1312
147
  const sessionId = req.headers["mcp-session-id"];
1313
148
  if (req.method === "POST") {
1314
149
  const bodyChunks = [];
@@ -1341,10 +176,10 @@ var MCPRemote = class extends MCPBase {
1341
176
  }
1342
177
  };
1343
178
  this.mcpServer = new import_mcp.McpServer({
1344
- name: this.serverName || "FIXParser",
1345
- version: this.serverVersion || "1.0.0"
179
+ name: this.name || "FIXParser",
180
+ version: this.version || "1.0.0"
1346
181
  });
1347
- this.setupTools();
182
+ this.addWorkflows();
1348
183
  await this.mcpServer.connect(transport);
1349
184
  } else {
1350
185
  res.writeHead(400, { "Content-Type": "application/json" });
@@ -1360,15 +195,7 @@ var MCPRemote = class extends MCPBase {
1360
195
  );
1361
196
  return;
1362
197
  }
1363
- try {
1364
- await transport.handleRequest(req, res, parsed);
1365
- } catch (error) {
1366
- this.logger?.log({
1367
- level: "error",
1368
- message: `Error handling request: ${error}`
1369
- });
1370
- throw error;
1371
- }
198
+ await transport.handleRequest(req, res, parsed);
1372
199
  });
1373
200
  } else if (req.method === "GET" || req.method === "DELETE") {
1374
201
  if (!sessionId || !transports[sessionId]) {
@@ -1377,29 +204,17 @@ var MCPRemote = class extends MCPBase {
1377
204
  return;
1378
205
  }
1379
206
  const transport = transports[sessionId];
1380
- try {
1381
- await transport.handleRequest(req, res);
1382
- } catch (error) {
1383
- this.logger?.log({
1384
- level: "error",
1385
- message: `Error handling ${req.method} request: ${error}`
1386
- });
1387
- throw error;
1388
- }
207
+ await transport.handleRequest(req, res);
1389
208
  } else {
1390
- this.logger?.log({
1391
- level: "error",
1392
- message: `Method not allowed: ${req.method}`
1393
- });
1394
209
  res.writeHead(405);
1395
210
  res.end("Method Not Allowed");
1396
211
  }
1397
- } else {
1398
- res.writeHead(404);
1399
- res.end("Not Found");
212
+ return;
1400
213
  }
214
+ res.writeHead(404);
215
+ res.end("Not Found");
1401
216
  });
1402
- this.httpServer.listen(this.port, () => {
217
+ this.server.listen(this.port, () => {
1403
218
  this.logger?.log({
1404
219
  level: "info",
1405
220
  message: `FIXParser (MCP): -- Server listening on http://localhost:${this.port}...`
@@ -1409,55 +224,381 @@ var MCPRemote = class extends MCPBase {
1409
224
  this.onReady();
1410
225
  }
1411
226
  }
1412
- setupTools() {
227
+ addWorkflows() {
1413
228
  if (!this.parser) {
1414
229
  this.logger?.log({
1415
230
  level: "error",
1416
- message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of tools..."
231
+ message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of workflows..."
1417
232
  });
1418
233
  return;
1419
234
  }
1420
235
  if (!this.mcpServer) {
1421
236
  this.logger?.log({
1422
237
  level: "error",
1423
- message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of tools..."
238
+ message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of workflows..."
1424
239
  });
1425
240
  return;
1426
241
  }
1427
- const toolHandlers = createToolHandlers(
1428
- this.parser,
1429
- this.verifiedOrders,
1430
- this.pendingRequests,
1431
- this.marketDataPrices
242
+ this.mcpServer.tool(
243
+ "parse",
244
+ "Parses a FIX message and describes it in plain language",
245
+ { fixString: import_zod.z.string() },
246
+ async ({ fixString }) => {
247
+ const parsedMessage = this.parser?.parse(fixString);
248
+ if (!parsedMessage || parsedMessage.length === 0) {
249
+ this.logger?.log({
250
+ level: "error",
251
+ message: "FIXParser (MCP): -- Failed to parse FIX string"
252
+ });
253
+ return {
254
+ isError: true,
255
+ content: [
256
+ {
257
+ type: "text",
258
+ text: "Error: Failed to parse FIX string"
259
+ }
260
+ ]
261
+ };
262
+ }
263
+ return {
264
+ content: [
265
+ {
266
+ type: "text",
267
+ text: parsedMessage ? `${parsedMessage[0].description} - ${parsedMessage[0].messageTypeDescription}` : ""
268
+ }
269
+ ]
270
+ };
271
+ }
1432
272
  );
1433
- Object.entries(toolSchemas).forEach(([name, { description, schema }]) => {
1434
- this.mcpServer?.registerTool(
1435
- name,
1436
- {
1437
- description,
1438
- inputSchema: jsonSchemaToZod(schema)
1439
- },
1440
- async (args) => {
1441
- const handler = toolHandlers[name];
1442
- if (!handler) {
1443
- return {
1444
- content: [
1445
- {
1446
- type: "text",
1447
- text: `Tool not found: ${name}`
1448
- }
1449
- ],
1450
- isError: true
1451
- };
273
+ this.mcpServer.prompt(
274
+ "parse",
275
+ "Parses a FIX message and describes it in plain language",
276
+ { fixString: import_zod.z.string() },
277
+ ({ fixString }) => ({
278
+ messages: [
279
+ {
280
+ role: "user",
281
+ content: {
282
+ type: "text",
283
+ text: `Please parse and explain this FIX message: ${fixString}`
284
+ }
1452
285
  }
1453
- const result = await handler(args);
286
+ ]
287
+ })
288
+ );
289
+ this.mcpServer.tool(
290
+ "parseToJSON",
291
+ "Parses a FIX message into JSON",
292
+ { fixString: import_zod.z.string() },
293
+ async ({ fixString }) => {
294
+ const parsedMessage = this.parser?.parse(fixString);
295
+ if (!parsedMessage || parsedMessage.length === 0) {
296
+ this.logger?.log({
297
+ level: "error",
298
+ message: "FIXParser (MCP): -- Failed to parse FIX string"
299
+ });
1454
300
  return {
1455
- content: result.content,
1456
- isError: result.isError
301
+ isError: true,
302
+ content: [
303
+ {
304
+ type: "text",
305
+ text: "Error: Failed to parse FIX string"
306
+ }
307
+ ]
1457
308
  };
1458
309
  }
1459
- );
1460
- });
310
+ return {
311
+ content: [
312
+ {
313
+ type: "text",
314
+ text: parsedMessage ? JSON.stringify(parsedMessage[0].toFIXJSON()) : ""
315
+ }
316
+ ]
317
+ };
318
+ }
319
+ );
320
+ this.mcpServer.prompt(
321
+ "parseToJSON",
322
+ "Parses a FIX message into JSON",
323
+ { fixString: import_zod.z.string() },
324
+ ({ fixString }) => ({
325
+ messages: [
326
+ {
327
+ role: "user",
328
+ content: {
329
+ type: "text",
330
+ text: `Please parse the FIX message to JSON: ${fixString}`
331
+ }
332
+ }
333
+ ]
334
+ })
335
+ );
336
+ this.mcpServer.tool(
337
+ "newOrderSingle",
338
+ "Creates and sends a New Order Single",
339
+ {
340
+ clOrdID: import_zod.z.string(),
341
+ handlInst: import_zod.z.enum(["1", "2", "3"]).default(import_fixparser.HandlInst.AutomatedExecutionNoIntervention).optional(),
342
+ quantity: import_zod.z.number(),
343
+ price: import_zod.z.number(),
344
+ ordType: import_zod.z.enum([
345
+ "1",
346
+ "2",
347
+ "3",
348
+ "4",
349
+ "5",
350
+ "6",
351
+ "7",
352
+ "8",
353
+ "9",
354
+ "A",
355
+ "B",
356
+ "C",
357
+ "D",
358
+ "E",
359
+ "F",
360
+ "G",
361
+ "H",
362
+ "I",
363
+ "J",
364
+ "K",
365
+ "L",
366
+ "M",
367
+ "P",
368
+ "Q",
369
+ "R",
370
+ "S"
371
+ ]).default(import_fixparser.OrdType.Market).optional(),
372
+ side: import_zod.z.enum(["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"]),
373
+ // 1 = Buy, 2 = Sell...
374
+ symbol: import_zod.z.string(),
375
+ timeInForce: import_zod.z.enum(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"]).default(import_fixparser.TimeInForce.Day).optional()
376
+ },
377
+ async ({ clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce }) => {
378
+ const response = new Promise((resolve) => {
379
+ this.pendingRequests.set(clOrdID, resolve);
380
+ });
381
+ const order = this.parser?.createMessage(
382
+ new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.NewOrderSingle),
383
+ new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
384
+ new import_fixparser.Field(import_fixparser.Fields.SenderCompID, this.parser?.sender),
385
+ new import_fixparser.Field(import_fixparser.Fields.TargetCompID, this.parser?.target),
386
+ new import_fixparser.Field(import_fixparser.Fields.SendingTime, this.parser?.getTimestamp()),
387
+ new import_fixparser.Field(import_fixparser.Fields.ClOrdID, clOrdID),
388
+ new import_fixparser.Field(import_fixparser.Fields.Side, side),
389
+ new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol),
390
+ new import_fixparser.Field(import_fixparser.Fields.OrderQty, quantity),
391
+ new import_fixparser.Field(import_fixparser.Fields.Price, price),
392
+ new import_fixparser.Field(import_fixparser.Fields.OrdType, ordType),
393
+ new import_fixparser.Field(import_fixparser.Fields.HandlInst, handlInst),
394
+ new import_fixparser.Field(import_fixparser.Fields.TimeInForce, timeInForce),
395
+ new import_fixparser.Field(import_fixparser.Fields.TransactTime, this.parser?.getTimestamp())
396
+ );
397
+ if (!this.parser?.connected) {
398
+ this.logger?.log({
399
+ level: "error",
400
+ message: "FIXParser (MCP): -- Not connected. Ignoring message."
401
+ });
402
+ return {
403
+ isError: true,
404
+ content: [
405
+ {
406
+ type: "text",
407
+ text: "Error: Not connected. Ignoring message."
408
+ }
409
+ ]
410
+ };
411
+ }
412
+ this.parser?.send(order);
413
+ this.logger?.log({
414
+ level: "info",
415
+ message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${order?.description}`
416
+ });
417
+ const fixData = await response;
418
+ return {
419
+ content: [
420
+ {
421
+ type: "text",
422
+ text: `Execution Report for order ${clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`
423
+ }
424
+ ]
425
+ };
426
+ }
427
+ );
428
+ this.mcpServer.prompt(
429
+ "newOrderSingle",
430
+ "Creates and sends a New Order Single",
431
+ {
432
+ clOrdID: import_zod.z.string(),
433
+ handlInst: import_zod.z.string(),
434
+ quantity: import_zod.z.string(),
435
+ price: import_zod.z.string(),
436
+ ordType: import_zod.z.string(),
437
+ side: import_zod.z.string(),
438
+ symbol: import_zod.z.string(),
439
+ timeInForce: import_zod.z.string()
440
+ },
441
+ ({ clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce }) => ({
442
+ messages: [
443
+ {
444
+ role: "user",
445
+ content: {
446
+ type: "text",
447
+ text: [
448
+ "Create a New Order Single FIX message with the following parameters:",
449
+ `- ClOrdID: ${clOrdID}`,
450
+ `- HandlInst: ${handlInst ?? "default"}`,
451
+ `- Quantity: ${quantity}`,
452
+ `- Price: ${price}`,
453
+ `- OrdType: ${ordType ?? "default (Market)"}`,
454
+ `- Side: ${side}`,
455
+ `- Symbol: ${symbol}`,
456
+ `- TimeInForce: ${timeInForce ?? "default (Day)"}`,
457
+ "",
458
+ "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values."
459
+ ].join("\n")
460
+ }
461
+ }
462
+ ]
463
+ })
464
+ );
465
+ this.mcpServer.tool(
466
+ "marketDataRequest",
467
+ "Sends a request for Market Data with the given symbol",
468
+ {
469
+ mdUpdateType: import_zod.z.enum(["0", "1"]).default("0").optional(),
470
+ // MDUpdateType.FullRefresh
471
+ symbol: import_zod.z.string(),
472
+ mdReqID: import_zod.z.string(),
473
+ subscriptionRequestType: import_zod.z.enum(["0", "1", "2"]).default(import_fixparser.SubscriptionRequestType.SnapshotAndUpdates).optional(),
474
+ mdEntryType: import_zod.z.enum([
475
+ "0",
476
+ "1",
477
+ "2",
478
+ "3",
479
+ "4",
480
+ "5",
481
+ "6",
482
+ "7",
483
+ "8",
484
+ "9",
485
+ "A",
486
+ "B",
487
+ "C",
488
+ "D",
489
+ "E",
490
+ "F",
491
+ "G",
492
+ "H",
493
+ "J",
494
+ "K",
495
+ "L",
496
+ "M",
497
+ "N",
498
+ "O",
499
+ "P",
500
+ "Q",
501
+ "S",
502
+ "R",
503
+ "T",
504
+ "U",
505
+ "V",
506
+ "W",
507
+ "X",
508
+ "Y",
509
+ "Z",
510
+ "a",
511
+ "b",
512
+ "c",
513
+ "d",
514
+ "e",
515
+ "g",
516
+ "h",
517
+ "i",
518
+ "t"
519
+ ]).default(import_fixparser.MDEntryType.Bid).optional()
520
+ },
521
+ async ({ mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType }) => {
522
+ const response = new Promise((resolve) => {
523
+ this.pendingRequests.set(mdReqID, resolve);
524
+ });
525
+ const marketDataRequest = this.parser?.createMessage(
526
+ new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
527
+ new import_fixparser.Field(import_fixparser.Fields.SenderCompID, this.parser?.sender),
528
+ new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
529
+ new import_fixparser.Field(import_fixparser.Fields.TargetCompID, this.parser?.target),
530
+ new import_fixparser.Field(import_fixparser.Fields.SendingTime, this.parser?.getTimestamp()),
531
+ new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
532
+ new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, mdUpdateType),
533
+ new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, 1),
534
+ new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol),
535
+ new import_fixparser.Field(import_fixparser.Fields.MDReqID, mdReqID),
536
+ new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, subscriptionRequestType),
537
+ new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, 1),
538
+ new import_fixparser.Field(import_fixparser.Fields.MDEntryType, mdEntryType)
539
+ );
540
+ if (!this.parser?.connected) {
541
+ this.logger?.log({
542
+ level: "error",
543
+ message: "FIXParser (MCP): -- Not connected. Ignoring message."
544
+ });
545
+ return {
546
+ isError: true,
547
+ content: [
548
+ {
549
+ type: "text",
550
+ text: "Error: Not connected. Ignoring message."
551
+ }
552
+ ]
553
+ };
554
+ }
555
+ this.parser?.send(marketDataRequest);
556
+ this.logger?.log({
557
+ level: "info",
558
+ message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${marketDataRequest?.description}`
559
+ });
560
+ const fixData = await response;
561
+ return {
562
+ content: [
563
+ {
564
+ type: "text",
565
+ text: `Market data for ${symbol}: ${JSON.stringify(fixData.toFIXJSON())}`
566
+ }
567
+ ]
568
+ };
569
+ }
570
+ );
571
+ this.mcpServer.prompt(
572
+ "marketDataRequest",
573
+ "Sends a request for Market Data with the given symbol",
574
+ {
575
+ mdUpdateType: import_zod.z.string(),
576
+ symbol: import_zod.z.string(),
577
+ mdReqID: import_zod.z.string(),
578
+ subscriptionRequestType: import_zod.z.string(),
579
+ mdEntryType: import_zod.z.string()
580
+ },
581
+ ({ mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType }) => ({
582
+ messages: [
583
+ {
584
+ role: "user",
585
+ content: {
586
+ type: "text",
587
+ text: [
588
+ "Create a Market Data Request FIX message with the following parameters:",
589
+ `- MDUpdateType: ${mdUpdateType ?? "default (0 = FullRefresh)"}`,
590
+ `- Symbol: ${symbol}`,
591
+ `- MDReqID: ${mdReqID}`,
592
+ `- SubscriptionRequestType: ${subscriptionRequestType ?? "default (0 = Snapshot + Updates)"}`,
593
+ `- MDEntryType: ${mdEntryType ?? "default (0 = Bid)"}`,
594
+ "",
595
+ "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values."
596
+ ].join("\n")
597
+ }
598
+ }
599
+ ]
600
+ })
601
+ );
1461
602
  }
1462
603
  };
1463
604
  // Annotate the CommonJS export names for ESM import in node: