fixparser-plugin-mcp 9.1.7-525accda → 9.1.7-52ccb1d5

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