fixparser-plugin-mcp 9.1.7-bfcb9d6f → 9.1.7-c415bb75

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