fixparser-plugin-mcp 9.1.7-537ecaee → 9.1.7-555b7cf3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,52 @@
1
1
  // src/MCPLocal.ts
2
2
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
3
3
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
4
- import { Field, Fields, Messages } from "fixparser";
5
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
6
50
  var toolSchemas = {
7
51
  parse: {
8
52
  description: "Parses a FIX message and describes it in plain language",
@@ -85,7 +129,7 @@ var toolSchemas = {
85
129
  }
86
130
  },
87
131
  executeOrder: {
88
- description: "Executes a verified order. verifyOrder must be called before executeOrder. user has to explicitly allow executeOrder.",
132
+ description: "Executes a verified order. verifyOrder must be called before executeOrder.",
89
133
  schema: {
90
134
  type: "object",
91
135
  properties: {
@@ -202,12 +246,12 @@ var toolSchemas = {
202
246
  "X",
203
247
  "Y",
204
248
  "Z"
205
- ],
206
- 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"
207
- }
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"
208
252
  }
209
253
  },
210
- required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType", "mdEntryTypes"]
254
+ required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType"]
211
255
  }
212
256
  },
213
257
  getStockGraph: {
@@ -231,8 +275,613 @@ var toolSchemas = {
231
275
  }
232
276
  }
233
277
  };
234
- var MCPLocal = class {
235
- parser;
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 || [MDEntryType.Bid, MDEntryType.Offer, MDEntryType.TradeVolume];
289
+ const messageFields = [
290
+ new Field(Fields.MsgType, Messages.MarketDataRequest),
291
+ new Field(Fields.SenderCompID, parser.sender),
292
+ new Field(Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
293
+ new Field(Fields.TargetCompID, parser.target),
294
+ new Field(Fields.SendingTime, parser.getTimestamp()),
295
+ new Field(Fields.MDReqID, args.mdReqID),
296
+ new Field(Fields.SubscriptionRequestType, args.subscriptionRequestType),
297
+ new Field(Fields.MarketDepth, 0),
298
+ new Field(Fields.MDUpdateType, args.mdUpdateType)
299
+ ];
300
+ messageFields.push(new Field(Fields.NoRelatedSym, args.symbols.length));
301
+ args.symbols.forEach((symbol) => {
302
+ messageFields.push(new Field(Fields.Symbol, symbol));
303
+ });
304
+ messageFields.push(new Field(Fields.NoMDEntryTypes, entryTypes.length));
305
+ entryTypes.forEach((entryType) => {
306
+ messageFields.push(new Field(Fields.MDEntryType, entryType));
307
+ });
308
+ const mdr = parser.createMessage(...messageFields);
309
+ if (!parser.connected) {
310
+ return {
311
+ content: [
312
+ {
313
+ type: "text",
314
+ text: "Error: Not connected. Ignoring message.",
315
+ uri: "marketDataRequest"
316
+ }
317
+ ],
318
+ isError: true
319
+ };
320
+ }
321
+ parser.send(mdr);
322
+ const fixData = await response;
323
+ return {
324
+ content: [
325
+ {
326
+ type: "text",
327
+ text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
328
+ uri: "marketDataRequest"
329
+ }
330
+ ]
331
+ };
332
+ } catch (error) {
333
+ return {
334
+ content: [
335
+ {
336
+ type: "text",
337
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
338
+ uri: "marketDataRequest"
339
+ }
340
+ ],
341
+ isError: true
342
+ };
343
+ }
344
+ };
345
+ };
346
+ var createGetStockGraphHandler = (marketDataPrices) => {
347
+ return async (args) => {
348
+ try {
349
+ const symbol = args.symbol;
350
+ const priceHistory = marketDataPrices.get(symbol) || [];
351
+ if (priceHistory.length === 0) {
352
+ return {
353
+ content: [
354
+ {
355
+ type: "text",
356
+ text: `No price data available for ${symbol}`,
357
+ uri: "getStockGraph"
358
+ }
359
+ ]
360
+ };
361
+ }
362
+ const chart = new QuickChart();
363
+ chart.setWidth(1200);
364
+ chart.setHeight(600);
365
+ chart.setBackgroundColor("transparent");
366
+ const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
367
+ const bidData = priceHistory.map((point) => point.bid);
368
+ const offerData = priceHistory.map((point) => point.offer);
369
+ const spreadData = priceHistory.map((point) => point.spread);
370
+ const volumeData = priceHistory.map((point) => point.volume);
371
+ const config = {
372
+ type: "line",
373
+ data: {
374
+ labels,
375
+ datasets: [
376
+ {
377
+ label: "Bid",
378
+ data: bidData,
379
+ borderColor: "#28a745",
380
+ backgroundColor: "rgba(40, 167, 69, 0.1)",
381
+ fill: false,
382
+ tension: 0.4
383
+ },
384
+ {
385
+ label: "Offer",
386
+ data: offerData,
387
+ borderColor: "#dc3545",
388
+ backgroundColor: "rgba(220, 53, 69, 0.1)",
389
+ fill: false,
390
+ tension: 0.4
391
+ },
392
+ {
393
+ label: "Spread",
394
+ data: spreadData,
395
+ borderColor: "#6c757d",
396
+ backgroundColor: "rgba(108, 117, 125, 0.1)",
397
+ fill: false,
398
+ tension: 0.4
399
+ },
400
+ {
401
+ label: "Volume",
402
+ data: volumeData,
403
+ borderColor: "#007bff",
404
+ backgroundColor: "rgba(0, 123, 255, 0.1)",
405
+ fill: true,
406
+ tension: 0.4
407
+ }
408
+ ]
409
+ },
410
+ options: {
411
+ responsive: true,
412
+ plugins: {
413
+ title: {
414
+ display: true,
415
+ text: `${symbol} Market Data`
416
+ }
417
+ },
418
+ scales: {
419
+ y: {
420
+ beginAtZero: false
421
+ }
422
+ }
423
+ }
424
+ };
425
+ chart.setConfig(config);
426
+ const imageBuffer = await chart.toBinary();
427
+ const base64 = imageBuffer.toString("base64");
428
+ return {
429
+ content: [
430
+ {
431
+ type: "resource",
432
+ resource: {
433
+ uri: "resource://graph",
434
+ mimeType: "image/png",
435
+ blob: base64
436
+ }
437
+ }
438
+ ]
439
+ };
440
+ } catch (error) {
441
+ return {
442
+ content: [
443
+ {
444
+ type: "text",
445
+ text: `Error: ${error instanceof Error ? error.message : "Failed to generate chart"}`,
446
+ uri: "getStockGraph"
447
+ }
448
+ ],
449
+ isError: true
450
+ };
451
+ }
452
+ };
453
+ };
454
+ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
455
+ return async (args) => {
456
+ try {
457
+ const symbol = args.symbol;
458
+ const priceHistory = marketDataPrices.get(symbol) || [];
459
+ if (priceHistory.length === 0) {
460
+ return {
461
+ content: [
462
+ {
463
+ type: "text",
464
+ text: `No price data available for ${symbol}`,
465
+ uri: "getStockPriceHistory"
466
+ }
467
+ ]
468
+ };
469
+ }
470
+ return {
471
+ content: [
472
+ {
473
+ type: "text",
474
+ text: JSON.stringify(
475
+ {
476
+ symbol,
477
+ count: priceHistory.length,
478
+ data: priceHistory.map((point) => ({
479
+ timestamp: new Date(point.timestamp).toISOString(),
480
+ bid: point.bid,
481
+ offer: point.offer,
482
+ spread: point.spread,
483
+ volume: point.volume
484
+ }))
485
+ },
486
+ null,
487
+ 2
488
+ ),
489
+ uri: "getStockPriceHistory"
490
+ }
491
+ ]
492
+ };
493
+ } catch (error) {
494
+ return {
495
+ content: [
496
+ {
497
+ type: "text",
498
+ text: `Error: ${error instanceof Error ? error.message : "Failed to get stock price history"}`,
499
+ uri: "getStockPriceHistory"
500
+ }
501
+ ],
502
+ isError: true
503
+ };
504
+ }
505
+ };
506
+ };
507
+
508
+ // src/tools/order.ts
509
+ import { Field as Field2, Fields as Fields2, Messages as Messages2 } from "fixparser";
510
+ var ordTypeNames = {
511
+ "1": "Market",
512
+ "2": "Limit",
513
+ "3": "Stop",
514
+ "4": "StopLimit",
515
+ "5": "MarketOnClose",
516
+ "6": "WithOrWithout",
517
+ "7": "LimitOrBetter",
518
+ "8": "LimitWithOrWithout",
519
+ "9": "OnBasis",
520
+ A: "OnClose",
521
+ B: "LimitOnClose",
522
+ C: "ForexMarket",
523
+ D: "PreviouslyQuoted",
524
+ E: "PreviouslyIndicated",
525
+ F: "ForexLimit",
526
+ G: "ForexSwap",
527
+ H: "ForexPreviouslyQuoted",
528
+ I: "Funari",
529
+ J: "MarketIfTouched",
530
+ K: "MarketWithLeftOverAsLimit",
531
+ L: "PreviousFundValuationPoint",
532
+ M: "NextFundValuationPoint",
533
+ P: "Pegged",
534
+ Q: "CounterOrderSelection",
535
+ R: "StopOnBidOrOffer",
536
+ S: "StopLimitOnBidOrOffer"
537
+ };
538
+ var sideNames = {
539
+ "1": "Buy",
540
+ "2": "Sell",
541
+ "3": "BuyMinus",
542
+ "4": "SellPlus",
543
+ "5": "SellShort",
544
+ "6": "SellShortExempt",
545
+ "7": "Undisclosed",
546
+ "8": "Cross",
547
+ "9": "CrossShort",
548
+ A: "CrossShortExempt",
549
+ B: "AsDefined",
550
+ C: "Opposite",
551
+ D: "Subscribe",
552
+ E: "Redeem",
553
+ F: "Lend",
554
+ G: "Borrow",
555
+ H: "SellUndisclosed"
556
+ };
557
+ var timeInForceNames = {
558
+ "0": "Day",
559
+ "1": "GoodTillCancel",
560
+ "2": "AtTheOpening",
561
+ "3": "ImmediateOrCancel",
562
+ "4": "FillOrKill",
563
+ "5": "GoodTillCrossing",
564
+ "6": "GoodTillDate",
565
+ "7": "AtTheClose",
566
+ "8": "GoodThroughCrossing",
567
+ "9": "AtCrossing",
568
+ A: "GoodForTime",
569
+ B: "GoodForAuction",
570
+ C: "GoodForMonth"
571
+ };
572
+ var handlInstNames = {
573
+ "1": "AutomatedExecutionNoIntervention",
574
+ "2": "AutomatedExecutionInterventionOK",
575
+ "3": "ManualOrder"
576
+ };
577
+ var createVerifyOrderHandler = (parser, verifiedOrders) => {
578
+ return async (args) => {
579
+ try {
580
+ verifiedOrders.set(args.clOrdID, {
581
+ clOrdID: args.clOrdID,
582
+ handlInst: args.handlInst,
583
+ quantity: Number.parseFloat(String(args.quantity)),
584
+ price: Number.parseFloat(String(args.price)),
585
+ ordType: args.ordType,
586
+ side: args.side,
587
+ symbol: args.symbol,
588
+ timeInForce: args.timeInForce
589
+ });
590
+ return {
591
+ content: [
592
+ {
593
+ type: "text",
594
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
595
+
596
+ Parameters verified:
597
+ - ClOrdID: ${args.clOrdID}
598
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
599
+ - Quantity: ${args.quantity}
600
+ - Price: ${args.price}
601
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
602
+ - Side: ${args.side} (${sideNames[args.side]})
603
+ - Symbol: ${args.symbol}
604
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
605
+
606
+ To execute this order, call the executeOrder tool with these exact same parameters.`,
607
+ uri: "verifyOrder"
608
+ }
609
+ ]
610
+ };
611
+ } catch (error) {
612
+ return {
613
+ content: [
614
+ {
615
+ type: "text",
616
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
617
+ uri: "verifyOrder"
618
+ }
619
+ ],
620
+ isError: true
621
+ };
622
+ }
623
+ };
624
+ };
625
+ var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
626
+ return async (args) => {
627
+ try {
628
+ const verifiedOrder = verifiedOrders.get(args.clOrdID);
629
+ if (!verifiedOrder) {
630
+ return {
631
+ content: [
632
+ {
633
+ type: "text",
634
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
635
+ uri: "executeOrder"
636
+ }
637
+ ],
638
+ isError: true
639
+ };
640
+ }
641
+ 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) {
642
+ return {
643
+ content: [
644
+ {
645
+ type: "text",
646
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
647
+ uri: "executeOrder"
648
+ }
649
+ ],
650
+ isError: true
651
+ };
652
+ }
653
+ const response = new Promise((resolve) => {
654
+ pendingRequests.set(args.clOrdID, resolve);
655
+ });
656
+ const order = parser.createMessage(
657
+ new Field2(Fields2.MsgType, Messages2.NewOrderSingle),
658
+ new Field2(Fields2.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
659
+ new Field2(Fields2.SenderCompID, parser.sender),
660
+ new Field2(Fields2.TargetCompID, parser.target),
661
+ new Field2(Fields2.SendingTime, parser.getTimestamp()),
662
+ new Field2(Fields2.ClOrdID, args.clOrdID),
663
+ new Field2(Fields2.Side, args.side),
664
+ new Field2(Fields2.Symbol, args.symbol),
665
+ new Field2(Fields2.OrderQty, Number.parseFloat(String(args.quantity))),
666
+ new Field2(Fields2.Price, Number.parseFloat(String(args.price))),
667
+ new Field2(Fields2.OrdType, args.ordType),
668
+ new Field2(Fields2.HandlInst, args.handlInst),
669
+ new Field2(Fields2.TimeInForce, args.timeInForce),
670
+ new Field2(Fields2.TransactTime, parser.getTimestamp())
671
+ );
672
+ if (!parser.connected) {
673
+ return {
674
+ content: [
675
+ {
676
+ type: "text",
677
+ text: "Error: Not connected. Ignoring message.",
678
+ uri: "executeOrder"
679
+ }
680
+ ],
681
+ isError: true
682
+ };
683
+ }
684
+ parser.send(order);
685
+ const fixData = await response;
686
+ verifiedOrders.delete(args.clOrdID);
687
+ return {
688
+ content: [
689
+ {
690
+ type: "text",
691
+ 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())}`,
692
+ uri: "executeOrder"
693
+ }
694
+ ]
695
+ };
696
+ } catch (error) {
697
+ return {
698
+ content: [
699
+ {
700
+ type: "text",
701
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
702
+ uri: "executeOrder"
703
+ }
704
+ ],
705
+ isError: true
706
+ };
707
+ }
708
+ };
709
+ };
710
+
711
+ // src/tools/parse.ts
712
+ var createParseHandler = (parser) => {
713
+ return async (args) => {
714
+ try {
715
+ const parsedMessage = parser.parse(args.fixString);
716
+ if (!parsedMessage || parsedMessage.length === 0) {
717
+ return {
718
+ content: [
719
+ {
720
+ type: "text",
721
+ text: "Error: Failed to parse FIX string",
722
+ uri: "parse"
723
+ }
724
+ ],
725
+ isError: true
726
+ };
727
+ }
728
+ return {
729
+ content: [
730
+ {
731
+ type: "text",
732
+ text: `${parsedMessage[0].description}
733
+ ${parsedMessage[0].messageTypeDescription}`,
734
+ uri: "parse"
735
+ }
736
+ ]
737
+ };
738
+ } catch (error) {
739
+ return {
740
+ content: [
741
+ {
742
+ type: "text",
743
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
744
+ uri: "parse"
745
+ }
746
+ ],
747
+ isError: true
748
+ };
749
+ }
750
+ };
751
+ };
752
+
753
+ // src/tools/parseToJSON.ts
754
+ var createParseToJSONHandler = (parser) => {
755
+ return async (args) => {
756
+ try {
757
+ const parsedMessage = parser.parse(args.fixString);
758
+ if (!parsedMessage || parsedMessage.length === 0) {
759
+ return {
760
+ content: [
761
+ {
762
+ type: "text",
763
+ text: "Error: Failed to parse FIX string",
764
+ uri: "parseToJSON"
765
+ }
766
+ ],
767
+ isError: true
768
+ };
769
+ }
770
+ return {
771
+ content: [
772
+ {
773
+ type: "text",
774
+ text: `${parsedMessage[0].toFIXJSON()}`,
775
+ uri: "parseToJSON"
776
+ }
777
+ ]
778
+ };
779
+ } catch (error) {
780
+ return {
781
+ content: [
782
+ {
783
+ type: "text",
784
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
785
+ uri: "parseToJSON"
786
+ }
787
+ ],
788
+ isError: true
789
+ };
790
+ }
791
+ };
792
+ };
793
+
794
+ // src/tools/index.ts
795
+ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
796
+ parse: createParseHandler(parser),
797
+ parseToJSON: createParseToJSONHandler(parser),
798
+ verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
799
+ executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
800
+ marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
801
+ getStockGraph: createGetStockGraphHandler(marketDataPrices),
802
+ getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
803
+ });
804
+
805
+ // src/utils/messageHandler.ts
806
+ import { Fields as Fields3, MDEntryType as MDEntryType2, Messages as Messages3 } from "fixparser";
807
+ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
808
+ parser.logger.log({
809
+ level: "info",
810
+ message: `MCP Server received message: ${message.messageType}: ${message.description}`
811
+ });
812
+ const msgType = message.messageType;
813
+ if (msgType === Messages3.MarketDataSnapshotFullRefresh || msgType === Messages3.MarketDataIncrementalRefresh) {
814
+ const symbol = message.getField(Fields3.Symbol)?.value;
815
+ const entries = message.getField(Fields3.NoMDEntries)?.value;
816
+ let bid = 0;
817
+ let offer = 0;
818
+ let volume = 0;
819
+ const entryTypes = message.getFields(Fields3.MDEntryType);
820
+ const entryPrices = message.getFields(Fields3.MDEntryPx);
821
+ const entrySizes = message.getFields(Fields3.MDEntrySize);
822
+ if (entryTypes && entryPrices && entrySizes) {
823
+ for (let i = 0; i < entries; i++) {
824
+ const entryType = entryTypes[i]?.value;
825
+ const entryPrice = Number.parseFloat(entryPrices[i]?.value);
826
+ const entrySize = Number.parseFloat(entrySizes[i]?.value);
827
+ if (entryType === MDEntryType2.Bid) {
828
+ bid = entryPrice;
829
+ } else if (entryType === MDEntryType2.Offer) {
830
+ offer = entryPrice;
831
+ }
832
+ volume += entrySize;
833
+ }
834
+ }
835
+ const spread = offer - bid;
836
+ const timestamp = Date.now();
837
+ const data = {
838
+ timestamp,
839
+ bid,
840
+ offer,
841
+ spread,
842
+ volume
843
+ };
844
+ if (!marketDataPrices.has(symbol)) {
845
+ marketDataPrices.set(symbol, []);
846
+ }
847
+ const prices = marketDataPrices.get(symbol);
848
+ prices.push(data);
849
+ if (prices.length > maxPriceHistory) {
850
+ prices.splice(0, prices.length - maxPriceHistory);
851
+ }
852
+ onPriceUpdate?.(symbol, data);
853
+ } else if (msgType === Messages3.ExecutionReport) {
854
+ const reqId = message.getField(Fields3.ClOrdID)?.value;
855
+ const callback = pendingRequests.get(reqId);
856
+ if (callback) {
857
+ callback(message);
858
+ pendingRequests.delete(reqId);
859
+ }
860
+ }
861
+ }
862
+
863
+ // src/MCPLocal.ts
864
+ var MCPLocal = class extends MCPBase {
865
+ /**
866
+ * Map to store verified orders before execution
867
+ * @private
868
+ */
869
+ verifiedOrders = /* @__PURE__ */ new Map();
870
+ /**
871
+ * Map to store pending requests and their callbacks
872
+ * @private
873
+ */
874
+ pendingRequests = /* @__PURE__ */ new Map();
875
+ /**
876
+ * Map to store market data prices for each symbol
877
+ * @private
878
+ */
879
+ marketDataPrices = /* @__PURE__ */ new Map();
880
+ /**
881
+ * Maximum number of price points to store per symbol
882
+ * @private
883
+ */
884
+ MAX_PRICE_HISTORY = 1e5;
236
885
  server = new Server(
237
886
  {
238
887
  name: "fixparser",
@@ -254,78 +903,13 @@ var MCPLocal = class {
254
903
  }
255
904
  );
256
905
  transport = new StdioServerTransport();
257
- onReady = void 0;
258
- pendingRequests = /* @__PURE__ */ new Map();
259
- verifiedOrders = /* @__PURE__ */ new Map();
260
- // Store market data prices with timestamps
261
- marketDataPrices = /* @__PURE__ */ new Map();
262
- MAX_PRICE_HISTORY = 1e5;
263
- // Maximum number of price points to store per symbol
264
906
  constructor({ logger, onReady }) {
265
- if (onReady) this.onReady = onReady;
907
+ super({ logger, onReady });
266
908
  }
267
909
  async register(parser) {
268
910
  this.parser = parser;
269
911
  this.parser.addOnMessageCallback((message) => {
270
- this.parser?.logger.log({
271
- level: "info",
272
- message: `MCP Server received message: ${message.messageType}: ${message.description}`
273
- });
274
- const msgType = message.messageType;
275
- if (msgType === Messages.MarketDataSnapshotFullRefresh || msgType === Messages.ExecutionReport || msgType === Messages.Reject || msgType === Messages.MarketDataIncrementalRefresh) {
276
- this.parser?.logger.log({
277
- level: "info",
278
- message: `MCP Server handling message type: ${msgType}`
279
- });
280
- let id;
281
- if (msgType === Messages.MarketDataIncrementalRefresh || msgType === Messages.MarketDataSnapshotFullRefresh) {
282
- const symbol = message.getField(Fields.Symbol);
283
- const price = message.getField(Fields.MDEntryPx);
284
- const timestamp = message.getField(Fields.MDEntryTime)?.value || Date.now();
285
- if (symbol?.value && price?.value) {
286
- const symbolStr = String(symbol.value);
287
- const priceNum = Number(price.value);
288
- const priceHistory = this.marketDataPrices.get(symbolStr) || [];
289
- priceHistory.push({
290
- timestamp: Number(timestamp),
291
- price: priceNum
292
- });
293
- if (priceHistory.length > this.MAX_PRICE_HISTORY) {
294
- priceHistory.shift();
295
- }
296
- this.marketDataPrices.set(symbolStr, priceHistory);
297
- this.parser?.logger.log({
298
- level: "info",
299
- message: `MCP Server added ${symbol}: ${priceNum}`
300
- });
301
- this.server.notification({
302
- method: "priceUpdate",
303
- params: {
304
- symbol: symbolStr,
305
- price: priceNum,
306
- timestamp: Number(timestamp)
307
- }
308
- });
309
- }
310
- }
311
- if (msgType === Messages.MarketDataSnapshotFullRefresh) {
312
- const mdReqID = message.getField(Fields.MDReqID);
313
- if (mdReqID) id = String(mdReqID.value);
314
- } else if (msgType === Messages.ExecutionReport) {
315
- const clOrdID = message.getField(Fields.ClOrdID);
316
- if (clOrdID) id = String(clOrdID.value);
317
- } else if (msgType === Messages.Reject) {
318
- const refSeqNum = message.getField(Fields.RefSeqNum);
319
- if (refSeqNum) id = String(refSeqNum.value);
320
- }
321
- if (id) {
322
- const callback = this.pendingRequests.get(id);
323
- if (callback) {
324
- callback(message);
325
- this.pendingRequests.delete(id);
326
- }
327
- }
328
- }
912
+ handleMessage(message, this.parser, this.pendingRequests, this.marketDataPrices, this.MAX_PRICE_HISTORY);
329
913
  });
330
914
  this.addWorkflows();
331
915
  await this.server.connect(this.transport);
@@ -340,18 +924,15 @@ var MCPLocal = class {
340
924
  if (!this.server) {
341
925
  return;
342
926
  }
343
- this.server.setRequestHandler(
344
- z.object({ method: z.literal("tools/list") }),
345
- async (request, extra) => {
346
- return {
347
- tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
348
- name,
349
- description,
350
- inputSchema: schema
351
- }))
352
- };
353
- }
354
- );
927
+ this.server.setRequestHandler(z.object({ method: z.literal("tools/list") }), async () => {
928
+ return {
929
+ tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
930
+ name,
931
+ description,
932
+ inputSchema: schema
933
+ }))
934
+ };
935
+ });
355
936
  this.server.setRequestHandler(
356
937
  z.object({
357
938
  method: z.literal("tools/call"),
@@ -363,493 +944,32 @@ var MCPLocal = class {
363
944
  }).optional()
364
945
  })
365
946
  }),
366
- async (request, extra) => {
947
+ async (request) => {
367
948
  const { name, arguments: args } = request.params;
368
- switch (name) {
369
- case "parse":
370
- try {
371
- const parsedMessage = this.parser?.parse(args.fixString);
372
- if (!parsedMessage || parsedMessage.length === 0) {
373
- return {
374
- content: [
375
- {
376
- type: "text",
377
- text: "Error: Failed to parse FIX string",
378
- uri: "parse"
379
- }
380
- ],
381
- isError: true
382
- };
383
- }
384
- return {
385
- content: [
386
- {
387
- type: "text",
388
- text: `${parsedMessage[0].description}
389
- ${parsedMessage[0].messageTypeDescription}`,
390
- uri: "parse"
391
- }
392
- ]
393
- };
394
- } catch (error) {
395
- return {
396
- content: [
397
- {
398
- type: "text",
399
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
400
- uri: "parse"
401
- }
402
- ],
403
- isError: true
404
- };
405
- }
406
- case "parseToJSON":
407
- try {
408
- const parsedMessage = this.parser?.parse(args.fixString);
409
- if (!parsedMessage || parsedMessage.length === 0) {
410
- return {
411
- content: [
412
- {
413
- type: "text",
414
- text: "Error: Failed to parse FIX string",
415
- uri: "parseToJSON"
416
- }
417
- ],
418
- isError: true
419
- };
420
- }
421
- return {
422
- content: [
423
- {
424
- type: "text",
425
- text: `${parsedMessage[0].toFIXJSON()}`,
426
- uri: "parseToJSON"
427
- }
428
- ]
429
- };
430
- } catch (error) {
431
- return {
432
- content: [
433
- {
434
- type: "text",
435
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
436
- uri: "parseToJSON"
437
- }
438
- ],
439
- isError: true
440
- };
441
- }
442
- case "verifyOrder":
443
- try {
444
- this.verifiedOrders.set(args.clOrdID, {
445
- clOrdID: args.clOrdID,
446
- handlInst: args.handlInst,
447
- quantity: Number.parseFloat(args.quantity),
448
- price: Number.parseFloat(args.price),
449
- ordType: args.ordType,
450
- side: args.side,
451
- symbol: args.symbol,
452
- timeInForce: args.timeInForce
453
- });
454
- const ordTypeNames = {
455
- "1": "Market",
456
- "2": "Limit",
457
- "3": "Stop",
458
- "4": "StopLimit",
459
- "5": "MarketOnClose",
460
- "6": "WithOrWithout",
461
- "7": "LimitOrBetter",
462
- "8": "LimitWithOrWithout",
463
- "9": "OnBasis",
464
- A: "OnClose",
465
- B: "LimitOnClose",
466
- C: "ForexMarket",
467
- D: "PreviouslyQuoted",
468
- E: "PreviouslyIndicated",
469
- F: "ForexLimit",
470
- G: "ForexSwap",
471
- H: "ForexPreviouslyQuoted",
472
- I: "Funari",
473
- J: "MarketIfTouched",
474
- K: "MarketWithLeftOverAsLimit",
475
- L: "PreviousFundValuationPoint",
476
- M: "NextFundValuationPoint",
477
- P: "Pegged",
478
- Q: "CounterOrderSelection",
479
- R: "StopOnBidOrOffer",
480
- S: "StopLimitOnBidOrOffer"
481
- };
482
- const sideNames = {
483
- "1": "Buy",
484
- "2": "Sell",
485
- "3": "BuyMinus",
486
- "4": "SellPlus",
487
- "5": "SellShort",
488
- "6": "SellShortExempt",
489
- "7": "Undisclosed",
490
- "8": "Cross",
491
- "9": "CrossShort",
492
- A: "CrossShortExempt",
493
- B: "AsDefined",
494
- C: "Opposite",
495
- D: "Subscribe",
496
- E: "Redeem",
497
- F: "Lend",
498
- G: "Borrow",
499
- H: "SellUndisclosed"
500
- };
501
- const timeInForceNames = {
502
- "0": "Day",
503
- "1": "GoodTillCancel",
504
- "2": "AtTheOpening",
505
- "3": "ImmediateOrCancel",
506
- "4": "FillOrKill",
507
- "5": "GoodTillCrossing",
508
- "6": "GoodTillDate",
509
- "7": "AtTheClose",
510
- "8": "GoodThroughCrossing",
511
- "9": "AtCrossing",
512
- A: "GoodForTime",
513
- B: "GoodForAuction",
514
- C: "GoodForMonth"
515
- };
516
- const handlInstNames = {
517
- "1": "AutomatedExecutionNoIntervention",
518
- "2": "AutomatedExecutionInterventionOK",
519
- "3": "ManualOrder"
520
- };
521
- return {
522
- content: [
523
- {
524
- type: "text",
525
- text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
526
-
527
- Parameters verified:
528
- - ClOrdID: ${args.clOrdID}
529
- - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
530
- - Quantity: ${args.quantity}
531
- - Price: ${args.price}
532
- - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
533
- - Side: ${args.side} (${sideNames[args.side]})
534
- - Symbol: ${args.symbol}
535
- - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
536
-
537
- To execute this order, call the executeOrder tool with these exact same parameters.`,
538
- uri: "verifyOrder"
539
- }
540
- ]
541
- };
542
- } catch (error) {
543
- return {
544
- content: [
545
- {
546
- type: "text",
547
- text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
548
- uri: "verifyOrder"
549
- }
550
- ],
551
- isError: true
552
- };
553
- }
554
- case "executeOrder":
555
- try {
556
- const verifiedOrder = this.verifiedOrders.get(args.clOrdID);
557
- if (!verifiedOrder) {
558
- return {
559
- content: [
560
- {
561
- type: "text",
562
- text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
563
- uri: "executeOrder"
564
- }
565
- ],
566
- isError: true
567
- };
568
- }
569
- if (verifiedOrder.handlInst !== args.handlInst || verifiedOrder.quantity !== Number.parseFloat(args.quantity) || verifiedOrder.price !== Number.parseFloat(args.price) || verifiedOrder.ordType !== args.ordType || verifiedOrder.side !== args.side || verifiedOrder.symbol !== args.symbol || verifiedOrder.timeInForce !== args.timeInForce) {
570
- return {
571
- content: [
572
- {
573
- type: "text",
574
- text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
575
- uri: "executeOrder"
576
- }
577
- ],
578
- isError: true
579
- };
580
- }
581
- const response = new Promise((resolve) => {
582
- this.pendingRequests.set(args.clOrdID, resolve);
583
- });
584
- const order = this.parser?.createMessage(
585
- new Field(Fields.MsgType, Messages.NewOrderSingle),
586
- new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
587
- new Field(Fields.SenderCompID, this.parser?.sender),
588
- new Field(Fields.TargetCompID, this.parser?.target),
589
- new Field(Fields.SendingTime, this.parser?.getTimestamp()),
590
- new Field(Fields.ClOrdID, args.clOrdID),
591
- new Field(Fields.Side, args.side),
592
- new Field(Fields.Symbol, args.symbol),
593
- new Field(Fields.OrderQty, Number.parseFloat(args.quantity)),
594
- new Field(Fields.Price, Number.parseFloat(args.price)),
595
- new Field(Fields.OrdType, args.ordType),
596
- new Field(Fields.HandlInst, args.handlInst),
597
- new Field(Fields.TimeInForce, args.timeInForce),
598
- new Field(Fields.TransactTime, this.parser?.getTimestamp())
599
- );
600
- if (!this.parser?.connected) {
601
- return {
602
- content: [
603
- {
604
- type: "text",
605
- text: "Error: Not connected. Ignoring message.",
606
- uri: "executeOrder"
607
- }
608
- ],
609
- isError: true
610
- };
949
+ const toolHandlers = createToolHandlers(
950
+ this.parser,
951
+ this.verifiedOrders,
952
+ this.pendingRequests,
953
+ this.marketDataPrices
954
+ );
955
+ const handler = toolHandlers[name];
956
+ if (!handler) {
957
+ return {
958
+ content: [
959
+ {
960
+ type: "text",
961
+ text: `Tool not found: ${name}`,
962
+ uri: name
611
963
  }
612
- this.parser?.send(order);
613
- const fixData = await response;
614
- this.verifiedOrders.delete(args.clOrdID);
615
- return {
616
- content: [
617
- {
618
- type: "text",
619
- text: fixData.messageType === Messages.Reject ? `Reject message for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}` : `Execution Report for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`,
620
- uri: "executeOrder"
621
- }
622
- ]
623
- };
624
- } catch (error) {
625
- return {
626
- content: [
627
- {
628
- type: "text",
629
- text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
630
- uri: "executeOrder"
631
- }
632
- ],
633
- isError: true
634
- };
635
- }
636
- case "marketDataRequest":
637
- try {
638
- const response = new Promise((resolve) => {
639
- this.pendingRequests.set(args.mdReqID, resolve);
640
- });
641
- const messageFields = [
642
- new Field(Fields.MsgType, Messages.MarketDataRequest),
643
- new Field(Fields.SenderCompID, this.parser?.sender),
644
- new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
645
- new Field(Fields.TargetCompID, this.parser?.target),
646
- new Field(Fields.SendingTime, this.parser?.getTimestamp()),
647
- new Field(Fields.MDReqID, args.mdReqID),
648
- new Field(Fields.SubscriptionRequestType, args.subscriptionRequestType),
649
- new Field(Fields.MarketDepth, 0),
650
- new Field(Fields.MDUpdateType, args.mdUpdateType)
651
- ];
652
- messageFields.push(new Field(Fields.NoRelatedSym, args.symbols.length));
653
- args.symbols.forEach((symbol) => {
654
- messageFields.push(new Field(Fields.Symbol, symbol));
655
- });
656
- messageFields.push(new Field(Fields.NoMDEntryTypes, args.mdEntryTypes.length));
657
- args.mdEntryTypes.forEach((entryType) => {
658
- messageFields.push(new Field(Fields.MDEntryType, entryType));
659
- });
660
- const mdr = this.parser?.createMessage(...messageFields);
661
- if (!this.parser?.connected) {
662
- return {
663
- content: [
664
- {
665
- type: "text",
666
- text: "Error: Not connected. Ignoring message.",
667
- uri: "marketDataRequest"
668
- }
669
- ],
670
- isError: true
671
- };
672
- }
673
- this.parser?.send(mdr);
674
- const fixData = await response;
675
- return {
676
- content: [
677
- {
678
- type: "text",
679
- text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
680
- uri: "marketDataRequest"
681
- }
682
- ]
683
- };
684
- } catch (error) {
685
- return {
686
- content: [
687
- {
688
- type: "text",
689
- text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
690
- uri: "marketDataRequest"
691
- }
692
- ],
693
- isError: true
694
- };
695
- }
696
- case "getStockGraph":
697
- try {
698
- const symbol = args.symbol;
699
- const priceHistory = this.marketDataPrices.get(symbol) || [];
700
- if (priceHistory.length === 0) {
701
- return {
702
- content: [
703
- {
704
- type: "text",
705
- text: `No price data available for ${symbol}`,
706
- uri: "getStockGraph"
707
- }
708
- ]
709
- };
710
- }
711
- const width = 600;
712
- const height = 300;
713
- const padding = 40;
714
- const xScale = (width - 2 * padding) / (priceHistory.length - 1);
715
- const yMin = Math.min(...priceHistory.map((d) => d.price));
716
- const yMax = Math.max(...priceHistory.map((d) => d.price));
717
- const yScale = (height - 2 * padding) / (yMax - yMin);
718
- const points = priceHistory.map((d, i) => {
719
- const x = padding + i * xScale;
720
- const y = height - padding - (d.price - yMin) * yScale;
721
- return `${x},${y}`;
722
- }).join(" L ");
723
- const svg = `<?xml version="1.0" encoding="UTF-8"?>
724
- <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
725
- <!-- Background -->
726
- <rect width="100%" height="100%" fill="#f8f9fa"/>
727
-
728
- <!-- Grid lines -->
729
- <g stroke="#e9ecef" stroke-width="1">
730
- ${Array.from({ length: 5 }, (_, i) => {
731
- const y = padding + (height - 2 * padding) * i / 4;
732
- return `<line x1="${padding}" y1="${y}" x2="${width - padding}" y2="${y}"/>`;
733
- }).join("\n")}
734
- </g>
735
-
736
- <!-- Price line -->
737
- <path d="M ${points}"
738
- fill="none"
739
- stroke="#007bff"
740
- stroke-width="2"/>
741
-
742
- <!-- Data points -->
743
- ${priceHistory.map((d, i) => {
744
- const x = padding + i * xScale;
745
- const y = height - padding - (d.price - yMin) * yScale;
746
- return `<circle cx="${x}" cy="${y}" r="3" fill="#007bff"/>`;
747
- }).join("\n")}
748
-
749
- <!-- Labels -->
750
- <g font-family="Arial" font-size="12" fill="#495057">
751
- ${Array.from({ length: 5 }, (_, i) => {
752
- const x = padding + (width - 2 * padding) * i / 4;
753
- const index = Math.floor((priceHistory.length - 1) * i / 4);
754
- const timestamp = new Date(priceHistory[index].timestamp).toLocaleTimeString();
755
- return `<text x="${x + padding}" y="${height - padding + 20}" text-anchor="middle">${timestamp}</text>`;
756
- }).join("\n")}
757
- ${Array.from({ length: 5 }, (_, i) => {
758
- const y = padding + (height - 2 * padding) * i / 4;
759
- const price = yMax - (yMax - yMin) * i / 4;
760
- return `<text x="${padding - 5}" y="${y + 4}" text-anchor="end">$${price.toFixed(2)}</text>`;
761
- }).join("\n")}
762
- </g>
763
-
764
- <!-- Title -->
765
- <text x="${width / 2}" y="${padding / 2}"
766
- font-family="Arial" font-size="16" font-weight="bold"
767
- text-anchor="middle" fill="#212529">
768
- ${symbol} - Price Chart (${priceHistory.length} points)
769
- </text>
770
- </svg>`;
771
- const base64Svg = Buffer.from(svg).toString("base64");
772
- return {
773
- content: [
774
- {
775
- type: "image",
776
- text: base64Svg,
777
- uri: "getStockGraph",
778
- mimeType: "image/svg+xml"
779
- }
780
- ]
781
- };
782
- } catch (error) {
783
- return {
784
- content: [
785
- {
786
- type: "text",
787
- text: `Error: ${error instanceof Error ? error.message : "Failed to generate stock graph"}`,
788
- uri: "getStockGraph"
789
- }
790
- ],
791
- isError: true
792
- };
793
- }
794
- case "getStockPriceHistory":
795
- try {
796
- const symbol = args.symbol;
797
- const priceHistory = this.marketDataPrices.get(symbol) || [];
798
- if (priceHistory.length === 0) {
799
- return {
800
- content: [
801
- {
802
- type: "text",
803
- text: `No price data available for ${symbol}`,
804
- uri: "getStockPriceHistory"
805
- }
806
- ]
807
- };
808
- }
809
- return {
810
- content: [
811
- {
812
- type: "text",
813
- text: JSON.stringify(
814
- {
815
- symbol,
816
- count: priceHistory.length,
817
- prices: priceHistory.map((point) => ({
818
- timestamp: new Date(point.timestamp).toISOString(),
819
- price: point.price
820
- }))
821
- },
822
- null,
823
- 2
824
- ),
825
- uri: "getStockPriceHistory"
826
- }
827
- ]
828
- };
829
- } catch (error) {
830
- return {
831
- content: [
832
- {
833
- type: "text",
834
- text: `Error: ${error instanceof Error ? error.message : "Failed to get stock price history"}`,
835
- uri: "getStockPriceHistory"
836
- }
837
- ],
838
- isError: true
839
- };
840
- }
841
- default:
842
- return {
843
- content: [
844
- {
845
- type: "text",
846
- text: `Tool not found: ${name}`,
847
- uri: name
848
- }
849
- ],
850
- isError: true
851
- };
964
+ ],
965
+ isError: true
966
+ };
852
967
  }
968
+ const result = await handler(args);
969
+ return {
970
+ content: result.content,
971
+ isError: result.isError
972
+ };
853
973
  }
854
974
  );
855
975
  process.on("SIGINT", async () => {