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

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