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