fixparser-plugin-mcp 9.1.7-bfcb9d6f → 9.1.7-c213f7c6

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,1583 @@
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. Important: The user has to explicitly confirm before executeOrder is called!`,
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
+ if (entryType === import_fixparser3.MDEntryType.Bid || entryType === import_fixparser3.MDEntryType.Offer || entryType === import_fixparser3.MDEntryType.TradeVolume) {
1020
+ parser.logger.log({
1021
+ level: "info",
1022
+ message: `Market Data Entry - Type: ${entryType}, Price: ${price}, Size: ${size}`
1023
+ });
1024
+ }
1025
+ switch (entryType) {
1026
+ case import_fixparser3.MDEntryType.Bid:
1027
+ data.bid = price;
1028
+ break;
1029
+ case import_fixparser3.MDEntryType.Offer:
1030
+ data.offer = price;
1031
+ break;
1032
+ case import_fixparser3.MDEntryType.Trade:
1033
+ data.trade = price;
1034
+ break;
1035
+ case import_fixparser3.MDEntryType.IndexValue:
1036
+ data.indexValue = price;
1037
+ break;
1038
+ case import_fixparser3.MDEntryType.OpeningPrice:
1039
+ data.openingPrice = price;
1040
+ break;
1041
+ case import_fixparser3.MDEntryType.ClosingPrice:
1042
+ data.closingPrice = price;
1043
+ break;
1044
+ case import_fixparser3.MDEntryType.SettlementPrice:
1045
+ data.settlementPrice = price;
1046
+ break;
1047
+ case import_fixparser3.MDEntryType.TradingSessionHighPrice:
1048
+ data.tradingSessionHighPrice = price;
1049
+ break;
1050
+ case import_fixparser3.MDEntryType.TradingSessionLowPrice:
1051
+ data.tradingSessionLowPrice = price;
1052
+ break;
1053
+ case import_fixparser3.MDEntryType.VWAP:
1054
+ data.vwap = price;
1055
+ break;
1056
+ case import_fixparser3.MDEntryType.Imbalance:
1057
+ data.imbalance = size;
1058
+ break;
1059
+ case import_fixparser3.MDEntryType.TradeVolume:
1060
+ data.volume = size;
1061
+ break;
1062
+ case import_fixparser3.MDEntryType.OpenInterest:
1063
+ data.openInterest = size;
1064
+ break;
1065
+ case import_fixparser3.MDEntryType.CompositeUnderlyingPrice:
1066
+ data.compositeUnderlyingPrice = price;
1067
+ break;
1068
+ case import_fixparser3.MDEntryType.SimulatedSellPrice:
1069
+ data.simulatedSellPrice = price;
1070
+ break;
1071
+ case import_fixparser3.MDEntryType.SimulatedBuyPrice:
1072
+ data.simulatedBuyPrice = price;
1073
+ break;
1074
+ case import_fixparser3.MDEntryType.MarginRate:
1075
+ data.marginRate = price;
1076
+ break;
1077
+ case import_fixparser3.MDEntryType.MidPrice:
1078
+ data.midPrice = price;
1079
+ break;
1080
+ case import_fixparser3.MDEntryType.EmptyBook:
1081
+ data.emptyBook = 1;
1082
+ break;
1083
+ case import_fixparser3.MDEntryType.SettleHighPrice:
1084
+ data.settleHighPrice = price;
1085
+ break;
1086
+ case import_fixparser3.MDEntryType.SettleLowPrice:
1087
+ data.settleLowPrice = price;
1088
+ break;
1089
+ case import_fixparser3.MDEntryType.PriorSettlePrice:
1090
+ data.priorSettlePrice = price;
1091
+ break;
1092
+ case import_fixparser3.MDEntryType.SessionHighBid:
1093
+ data.sessionHighBid = price;
1094
+ break;
1095
+ case import_fixparser3.MDEntryType.SessionLowOffer:
1096
+ data.sessionLowOffer = price;
1097
+ break;
1098
+ case import_fixparser3.MDEntryType.EarlyPrices:
1099
+ data.earlyPrices = price;
1100
+ break;
1101
+ case import_fixparser3.MDEntryType.AuctionClearingPrice:
1102
+ data.auctionClearingPrice = price;
1103
+ break;
1104
+ case import_fixparser3.MDEntryType.SwapValueFactor:
1105
+ data.swapValueFactor = price;
1106
+ break;
1107
+ case import_fixparser3.MDEntryType.DailyValueAdjustmentForLongPositions:
1108
+ data.dailyValueAdjustmentForLongPositions = price;
1109
+ break;
1110
+ case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForLongPositions:
1111
+ data.cumulativeValueAdjustmentForLongPositions = price;
1112
+ break;
1113
+ case import_fixparser3.MDEntryType.DailyValueAdjustmentForShortPositions:
1114
+ data.dailyValueAdjustmentForShortPositions = price;
1115
+ break;
1116
+ case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForShortPositions:
1117
+ data.cumulativeValueAdjustmentForShortPositions = price;
1118
+ break;
1119
+ case import_fixparser3.MDEntryType.FixingPrice:
1120
+ data.fixingPrice = price;
1121
+ break;
1122
+ case import_fixparser3.MDEntryType.CashRate:
1123
+ data.cashRate = price;
1124
+ break;
1125
+ case import_fixparser3.MDEntryType.RecoveryRate:
1126
+ data.recoveryRate = price;
1127
+ break;
1128
+ case import_fixparser3.MDEntryType.RecoveryRateForLong:
1129
+ data.recoveryRateForLong = price;
1130
+ break;
1131
+ case import_fixparser3.MDEntryType.RecoveryRateForShort:
1132
+ data.recoveryRateForShort = price;
1133
+ break;
1134
+ case import_fixparser3.MDEntryType.MarketBid:
1135
+ data.marketBid = price;
1136
+ break;
1137
+ case import_fixparser3.MDEntryType.MarketOffer:
1138
+ data.marketOffer = price;
1139
+ break;
1140
+ case import_fixparser3.MDEntryType.ShortSaleMinPrice:
1141
+ data.shortSaleMinPrice = price;
1142
+ break;
1143
+ case import_fixparser3.MDEntryType.PreviousClosingPrice:
1144
+ data.previousClosingPrice = price;
1145
+ break;
1146
+ case import_fixparser3.MDEntryType.ThresholdLimitPriceBanding:
1147
+ data.thresholdLimitPriceBanding = price;
1148
+ break;
1149
+ case import_fixparser3.MDEntryType.DailyFinancingValue:
1150
+ data.dailyFinancingValue = price;
1151
+ break;
1152
+ case import_fixparser3.MDEntryType.AccruedFinancingValue:
1153
+ data.accruedFinancingValue = price;
1154
+ break;
1155
+ case import_fixparser3.MDEntryType.TWAP:
1156
+ data.twap = price;
1157
+ break;
1158
+ }
1159
+ }
1160
+ data.spread = data.offer - data.bid;
1161
+ if (!marketDataPrices.has(symbol)) {
1162
+ marketDataPrices.set(symbol, []);
1163
+ }
1164
+ const prices = marketDataPrices.get(symbol);
1165
+ prices.push(data);
1166
+ if (prices.length > maxPriceHistory) {
1167
+ prices.splice(0, prices.length - maxPriceHistory);
1168
+ }
1169
+ onPriceUpdate?.(symbol, data);
1170
+ const mdReqID = message.getField(import_fixparser3.Fields.MDReqID)?.value;
1171
+ if (mdReqID) {
1172
+ const callback = pendingRequests.get(mdReqID);
1173
+ if (callback) {
1174
+ callback(message);
1175
+ pendingRequests.delete(mdReqID);
1176
+ }
1177
+ }
1178
+ } else if (msgType === import_fixparser3.Messages.ExecutionReport) {
1179
+ const reqId = message.getField(import_fixparser3.Fields.ClOrdID)?.value;
1180
+ const callback = pendingRequests.get(reqId);
1181
+ if (callback) {
1182
+ callback(message);
1183
+ pendingRequests.delete(reqId);
1184
+ }
1185
+ }
1186
+ }
1187
+
1188
+ // src/MCPLocal.ts
1189
+ var MCPLocal = class extends MCPBase {
1190
+ /**
1191
+ * Map to store verified orders before execution
1192
+ * @private
1193
+ */
1194
+ verifiedOrders = /* @__PURE__ */ new Map();
1195
+ /**
1196
+ * Map to store pending requests and their callbacks
1197
+ * @private
1198
+ */
1199
+ pendingRequests = /* @__PURE__ */ new Map();
1200
+ /**
1201
+ * Map to store market data prices for each symbol
1202
+ * @private
1203
+ */
1204
+ marketDataPrices = /* @__PURE__ */ new Map();
1205
+ /**
1206
+ * Maximum number of price history entries to keep per symbol
1207
+ * @private
1208
+ */
1209
+ MAX_PRICE_HISTORY = 1e5;
1210
+ server = new import_server.Server(
1211
+ {
1212
+ name: "fixparser",
1213
+ version: "1.0.0"
1214
+ },
1215
+ {
1216
+ capabilities: {
1217
+ tools: Object.entries(toolSchemas).reduce(
1218
+ (acc, [name, { description, schema }]) => {
1219
+ acc[name] = {
1220
+ description,
1221
+ parameters: schema
1222
+ };
1223
+ return acc;
1224
+ },
1225
+ {}
1226
+ )
1227
+ }
1228
+ }
1229
+ );
1230
+ transport = new import_stdio.StdioServerTransport();
1231
+ constructor({ logger, onReady }) {
1232
+ super({ logger, onReady });
1233
+ }
1234
+ async register(parser) {
1235
+ this.parser = parser;
1236
+ this.parser.addOnMessageCallback((message) => {
1237
+ handleMessage(message, this.parser, this.pendingRequests, this.marketDataPrices, this.MAX_PRICE_HISTORY);
1238
+ });
1239
+ this.addWorkflows();
1240
+ await this.server.connect(this.transport);
1241
+ if (this.onReady) {
1242
+ this.onReady();
1243
+ }
1244
+ }
1245
+ addWorkflows() {
1246
+ if (!this.parser) {
1247
+ return;
1248
+ }
1249
+ if (!this.server) {
1250
+ return;
1251
+ }
1252
+ this.server.setRequestHandler(import_zod.z.object({ method: import_zod.z.literal("tools/list") }), async () => {
1253
+ return {
1254
+ tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
1255
+ name,
1256
+ description,
1257
+ inputSchema: schema
1258
+ }))
1259
+ };
1260
+ });
1261
+ this.server.setRequestHandler(
1262
+ import_zod.z.object({
1263
+ method: import_zod.z.literal("tools/call"),
1264
+ params: import_zod.z.object({
1265
+ name: import_zod.z.string(),
1266
+ arguments: import_zod.z.any(),
1267
+ _meta: import_zod.z.object({
1268
+ progressToken: import_zod.z.number()
1269
+ }).optional()
1270
+ })
1271
+ }),
1272
+ async (request) => {
1273
+ const { name, arguments: args } = request.params;
1274
+ const toolHandlers = createToolHandlers(
1275
+ this.parser,
1276
+ this.verifiedOrders,
1277
+ this.pendingRequests,
1278
+ this.marketDataPrices
1279
+ );
1280
+ const handler = toolHandlers[name];
1281
+ if (!handler) {
1282
+ return {
1283
+ content: [
1284
+ {
1285
+ type: "text",
1286
+ text: `Tool not found: ${name}`,
1287
+ uri: name
1288
+ }
1289
+ ],
1290
+ isError: true
1291
+ };
1292
+ }
1293
+ const result = await handler(args);
1294
+ return {
1295
+ content: result.content,
1296
+ isError: result.isError
1297
+ };
1298
+ }
1299
+ );
1300
+ process.on("SIGINT", async () => {
1301
+ await this.server.close();
1302
+ process.exit(0);
1303
+ });
1304
+ }
1305
+ };
1306
+
1307
+ // src/MCPRemote.ts
1308
+ var import_node_crypto = require("node:crypto");
1309
+ var import_node_http = require("node:http");
1310
+ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
1311
+ var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
1312
+ var import_types = require("@modelcontextprotocol/sdk/types.js");
1313
+ var import_zod2 = require("zod");
1314
+ var transports = {};
1315
+ function jsonSchemaToZod(schema) {
1316
+ if (schema.type === "object") {
1317
+ const shape = {};
1318
+ for (const [key, prop] of Object.entries(schema.properties || {})) {
1319
+ const propSchema = prop;
1320
+ if (propSchema.type === "string") {
1321
+ if (propSchema.enum) {
1322
+ shape[key] = import_zod2.z.enum(propSchema.enum);
1323
+ } else {
1324
+ shape[key] = import_zod2.z.string();
1325
+ }
1326
+ } else if (propSchema.type === "number") {
1327
+ shape[key] = import_zod2.z.number();
1328
+ } else if (propSchema.type === "boolean") {
1329
+ shape[key] = import_zod2.z.boolean();
1330
+ } else if (propSchema.type === "array") {
1331
+ if (propSchema.items.type === "string") {
1332
+ shape[key] = import_zod2.z.array(import_zod2.z.string());
1333
+ } else if (propSchema.items.type === "number") {
1334
+ shape[key] = import_zod2.z.array(import_zod2.z.number());
1335
+ } else if (propSchema.items.type === "boolean") {
1336
+ shape[key] = import_zod2.z.array(import_zod2.z.boolean());
1337
+ } else {
1338
+ shape[key] = import_zod2.z.array(import_zod2.z.any());
1339
+ }
1340
+ } else {
1341
+ shape[key] = import_zod2.z.any();
1342
+ }
1343
+ }
1344
+ return shape;
1345
+ }
1346
+ return {};
1347
+ }
1348
+ var MCPRemote = class extends MCPBase {
1349
+ /**
1350
+ * Port number the server will listen on.
1351
+ * @private
1352
+ */
1353
+ port;
1354
+ /**
1355
+ * Node.js HTTP server instance created internally.
1356
+ * @private
1357
+ */
1358
+ httpServer;
1359
+ /**
1360
+ * MCP server instance handling MCP protocol logic.
1361
+ * @private
1362
+ */
1363
+ mcpServer;
1364
+ /**
1365
+ * Optional name of the plugin/server instance.
1366
+ * @private
1367
+ */
1368
+ serverName;
1369
+ /**
1370
+ * Optional version string of the plugin/server.
1371
+ * @private
1372
+ */
1373
+ serverVersion;
1374
+ /**
1375
+ * Map to store verified orders before execution
1376
+ * @private
1377
+ */
1378
+ verifiedOrders = /* @__PURE__ */ new Map();
1379
+ /**
1380
+ * Map to store pending requests and their callbacks
1381
+ * @private
1382
+ */
1383
+ pendingRequests = /* @__PURE__ */ new Map();
1384
+ /**
1385
+ * Map to store market data prices for each symbol
1386
+ * @private
1387
+ */
1388
+ marketDataPrices = /* @__PURE__ */ new Map();
1389
+ /**
1390
+ * Maximum number of price history entries to keep per symbol
1391
+ * @private
1392
+ */
1393
+ MAX_PRICE_HISTORY = 1e5;
1394
+ constructor({ port, logger, onReady }) {
1395
+ super({ logger, onReady });
1396
+ this.port = port;
1397
+ }
1398
+ async register(parser) {
1399
+ this.parser = parser;
1400
+ this.logger = parser.logger;
1401
+ this.logger?.log({
1402
+ level: "info",
1403
+ message: `FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`
1404
+ });
1405
+ this.parser.addOnMessageCallback((message) => {
1406
+ if (this.parser) {
1407
+ handleMessage(
1408
+ message,
1409
+ this.parser,
1410
+ this.pendingRequests,
1411
+ this.marketDataPrices,
1412
+ this.MAX_PRICE_HISTORY
1413
+ );
1414
+ this.logger?.log({
1415
+ level: "info",
1416
+ message: `Market Data Prices TEST: ${JSON.stringify(this.marketDataPrices)}`
1417
+ });
1418
+ }
1419
+ });
1420
+ this.httpServer = (0, import_node_http.createServer)(async (req, res) => {
1421
+ if (!req.url || !req.method) {
1422
+ res.writeHead(400);
1423
+ res.end("Bad Request");
1424
+ return;
1425
+ }
1426
+ if (req.url === "/mcp") {
1427
+ const sessionId = req.headers["mcp-session-id"];
1428
+ if (req.method === "POST") {
1429
+ const bodyChunks = [];
1430
+ req.on("data", (chunk) => {
1431
+ bodyChunks.push(chunk);
1432
+ });
1433
+ req.on("end", async () => {
1434
+ let parsed;
1435
+ const body = Buffer.concat(bodyChunks).toString();
1436
+ try {
1437
+ parsed = JSON.parse(body);
1438
+ } catch (err) {
1439
+ res.writeHead(400);
1440
+ res.end(JSON.stringify({ error: "Invalid JSON" }));
1441
+ return;
1442
+ }
1443
+ let transport;
1444
+ if (sessionId && transports[sessionId]) {
1445
+ transport = transports[sessionId];
1446
+ } else if (!sessionId && req.method === "POST" && (0, import_types.isInitializeRequest)(parsed)) {
1447
+ transport = new import_streamableHttp.StreamableHTTPServerTransport({
1448
+ sessionIdGenerator: () => (0, import_node_crypto.randomUUID)(),
1449
+ onsessioninitialized: (sessionId2) => {
1450
+ transports[sessionId2] = transport;
1451
+ }
1452
+ });
1453
+ transport.onclose = () => {
1454
+ if (transport.sessionId) {
1455
+ delete transports[transport.sessionId];
1456
+ }
1457
+ };
1458
+ this.mcpServer = new import_mcp.McpServer({
1459
+ name: this.serverName || "FIXParser",
1460
+ version: this.serverVersion || "1.0.0"
1461
+ });
1462
+ this.setupTools();
1463
+ await this.mcpServer.connect(transport);
1464
+ } else {
1465
+ res.writeHead(400, { "Content-Type": "application/json" });
1466
+ res.end(
1467
+ JSON.stringify({
1468
+ jsonrpc: "2.0",
1469
+ error: {
1470
+ code: -32e3,
1471
+ message: "Bad Request: No valid session ID provided"
1472
+ },
1473
+ id: null
1474
+ })
1475
+ );
1476
+ return;
1477
+ }
1478
+ try {
1479
+ await transport.handleRequest(req, res, parsed);
1480
+ } catch (error) {
1481
+ this.logger?.log({
1482
+ level: "error",
1483
+ message: `Error handling request: ${error}`
1484
+ });
1485
+ throw error;
1486
+ }
1487
+ });
1488
+ } else if (req.method === "GET" || req.method === "DELETE") {
1489
+ if (!sessionId || !transports[sessionId]) {
1490
+ res.writeHead(400);
1491
+ res.end("Invalid or missing session ID");
1492
+ return;
1493
+ }
1494
+ const transport = transports[sessionId];
1495
+ try {
1496
+ await transport.handleRequest(req, res);
1497
+ } catch (error) {
1498
+ this.logger?.log({
1499
+ level: "error",
1500
+ message: `Error handling ${req.method} request: ${error}`
1501
+ });
1502
+ throw error;
1503
+ }
1504
+ } else {
1505
+ this.logger?.log({
1506
+ level: "error",
1507
+ message: `Method not allowed: ${req.method}`
1508
+ });
1509
+ res.writeHead(405);
1510
+ res.end("Method Not Allowed");
1511
+ }
1512
+ } else {
1513
+ res.writeHead(404);
1514
+ res.end("Not Found");
1515
+ }
1516
+ });
1517
+ this.httpServer.listen(this.port, () => {
1518
+ this.logger?.log({
1519
+ level: "info",
1520
+ message: `FIXParser (MCP): -- Server listening on http://localhost:${this.port}...`
1521
+ });
1522
+ });
1523
+ if (this.onReady) {
1524
+ this.onReady();
1525
+ }
1526
+ }
1527
+ setupTools() {
1528
+ if (!this.parser) {
1529
+ this.logger?.log({
1530
+ level: "error",
1531
+ message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of tools..."
1532
+ });
1533
+ return;
1534
+ }
1535
+ if (!this.mcpServer) {
1536
+ this.logger?.log({
1537
+ level: "error",
1538
+ message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of tools..."
1539
+ });
1540
+ return;
1541
+ }
1542
+ const toolHandlers = createToolHandlers(
1543
+ this.parser,
1544
+ this.verifiedOrders,
1545
+ this.pendingRequests,
1546
+ this.marketDataPrices
1547
+ );
1548
+ Object.entries(toolSchemas).forEach(([name, { description, schema }]) => {
1549
+ this.mcpServer?.registerTool(
1550
+ name,
1551
+ {
1552
+ description,
1553
+ inputSchema: jsonSchemaToZod(schema)
1554
+ },
1555
+ async (args) => {
1556
+ const handler = toolHandlers[name];
1557
+ if (!handler) {
1558
+ return {
1559
+ content: [
1560
+ {
1561
+ type: "text",
1562
+ text: `Tool not found: ${name}`
1563
+ }
1564
+ ],
1565
+ isError: true
1566
+ };
1567
+ }
1568
+ const result = await handler(args);
1569
+ return {
1570
+ content: result.content,
1571
+ isError: result.isError
1572
+ };
1573
+ }
1574
+ );
1575
+ });
1576
+ }
1577
+ };
1578
+ // Annotate the CommonJS export names for ESM import in node:
1579
+ 0 && (module.exports = {
1580
+ MCPLocal,
1581
+ MCPRemote
1582
+ });
1583
+ //# sourceMappingURL=index.js.map