fixparser-plugin-mcp 9.1.7-89ae1451 → 9.1.7-8efb79c3

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