fixparser-plugin-mcp 9.1.7-eb1de32a → 9.1.7-edd9ee17

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