fixparser-plugin-mcp 9.1.7-c213f7c6 → 9.1.7-c5ae06ce

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,7 @@
1
1
  "use strict";
2
- var __create = Object.create;
3
2
  var __defProp = Object.defineProperty;
4
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
6
  var __export = (target, all) => {
9
7
  for (var name in all)
@@ -17,14 +15,6 @@ var __copyProps = (to, from, except, desc) => {
17
15
  }
18
16
  return to;
19
17
  };
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
18
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
19
 
30
20
  // src/MCPRemote.ts
@@ -39,1198 +29,29 @@ var import_mcp = require("@modelcontextprotocol/sdk/server/mcp.js");
39
29
  var import_streamableHttp = require("@modelcontextprotocol/sdk/server/streamableHttp.js");
40
30
  var import_types = require("@modelcontextprotocol/sdk/types.js");
41
31
  var import_zod = require("zod");
42
-
43
- // src/MCPBase.ts
44
- var MCPBase = class {
32
+ var import_fixparser = require("fixparser");
33
+ var transports = {};
34
+ var MCPRemote = class {
35
+ /**
36
+ * Port number the server will listen on.
37
+ * @private
38
+ */
39
+ port;
45
40
  /**
46
41
  * Optional logger instance for diagnostics and output.
47
- * @protected
42
+ * @private
48
43
  */
49
44
  logger;
50
45
  /**
51
46
  * 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/MCPRemote.ts
1189
- var transports = {};
1190
- function jsonSchemaToZod(schema) {
1191
- if (schema.type === "object") {
1192
- const shape = {};
1193
- for (const [key, prop] of Object.entries(schema.properties || {})) {
1194
- const propSchema = prop;
1195
- if (propSchema.type === "string") {
1196
- if (propSchema.enum) {
1197
- shape[key] = import_zod.z.enum(propSchema.enum);
1198
- } else {
1199
- shape[key] = import_zod.z.string();
1200
- }
1201
- } else if (propSchema.type === "number") {
1202
- shape[key] = import_zod.z.number();
1203
- } else if (propSchema.type === "boolean") {
1204
- shape[key] = import_zod.z.boolean();
1205
- } else if (propSchema.type === "array") {
1206
- if (propSchema.items.type === "string") {
1207
- shape[key] = import_zod.z.array(import_zod.z.string());
1208
- } else if (propSchema.items.type === "number") {
1209
- shape[key] = import_zod.z.array(import_zod.z.number());
1210
- } else if (propSchema.items.type === "boolean") {
1211
- shape[key] = import_zod.z.array(import_zod.z.boolean());
1212
- } else {
1213
- shape[key] = import_zod.z.array(import_zod.z.any());
1214
- }
1215
- } else {
1216
- shape[key] = import_zod.z.any();
1217
- }
1218
- }
1219
- return shape;
1220
- }
1221
- return {};
1222
- }
1223
- var MCPRemote = class extends MCPBase {
1224
- /**
1225
- * Port number the server will listen on.
1226
47
  * @private
1227
48
  */
1228
- port;
49
+ parser;
1229
50
  /**
1230
51
  * Node.js HTTP server instance created internally.
1231
52
  * @private
1232
53
  */
1233
- httpServer;
54
+ server;
1234
55
  /**
1235
56
  * MCP server instance handling MCP protocol logic.
1236
57
  * @private
@@ -1240,65 +61,89 @@ var MCPRemote = class extends MCPBase {
1240
61
  * Optional name of the plugin/server instance.
1241
62
  * @private
1242
63
  */
1243
- serverName;
64
+ name;
1244
65
  /**
1245
66
  * Optional version string of the plugin/server.
1246
67
  * @private
1247
68
  */
1248
- serverVersion;
69
+ version;
1249
70
  /**
1250
- * Map to store verified orders before execution
71
+ * Called when server is setup and listening.
1251
72
  * @private
1252
73
  */
1253
- verifiedOrders = /* @__PURE__ */ new Map();
74
+ onReady = void 0;
1254
75
  /**
1255
- * Map to store pending requests and their callbacks
76
+ * A map of pending market data requests, keyed by MDReqID.
77
+ * Each entry contains a resolver function that is called when the corresponding
78
+ * FIX Message is received.
1256
79
  * @private
80
+ * @type {Map<string, (data: Message) => void>}
1257
81
  */
1258
82
  pendingRequests = /* @__PURE__ */ new Map();
1259
- /**
1260
- * Map to store market data prices for each symbol
1261
- * @private
1262
- */
1263
- marketDataPrices = /* @__PURE__ */ new Map();
1264
- /**
1265
- * Maximum number of price history entries to keep per symbol
1266
- * @private
1267
- */
1268
- MAX_PRICE_HISTORY = 1e5;
1269
83
  constructor({ port, logger, onReady }) {
1270
- super({ logger, onReady });
1271
84
  this.port = port;
85
+ if (logger) this.logger = logger;
86
+ if (onReady) this.onReady = onReady;
1272
87
  }
1273
88
  async register(parser) {
1274
89
  this.parser = parser;
90
+ this.parser.addOnMessageCallback((message) => {
91
+ this.logger?.log({
92
+ level: "info",
93
+ message: `FIXParser (MCP): (${parser.protocol?.toUpperCase()}): << received ${message.description}`
94
+ });
95
+ const msgType = message.messageType;
96
+ if (msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser.Messages.ExecutionReport) {
97
+ const idField = msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh ? message.getField(import_fixparser.Fields.MDReqID) : message.getField(import_fixparser.Fields.ClOrdID);
98
+ if (idField) {
99
+ const id = idField.value;
100
+ if (typeof id === "string" || typeof id === "number") {
101
+ const callback = this.pendingRequests.get(String(id));
102
+ if (callback) {
103
+ callback(message);
104
+ this.pendingRequests.delete(String(id));
105
+ }
106
+ }
107
+ }
108
+ }
109
+ });
1275
110
  this.logger = parser.logger;
1276
111
  this.logger?.log({
1277
112
  level: "info",
1278
113
  message: `FIXParser (MCP): -- Plugin registered. Creating MCP server on port ${this.port}...`
1279
114
  });
1280
- this.parser.addOnMessageCallback((message) => {
1281
- if (this.parser) {
1282
- handleMessage(
1283
- message,
1284
- this.parser,
1285
- this.pendingRequests,
1286
- this.marketDataPrices,
1287
- this.MAX_PRICE_HISTORY
1288
- );
1289
- this.logger?.log({
1290
- level: "info",
1291
- message: `Market Data Prices TEST: ${JSON.stringify(this.marketDataPrices)}`
1292
- });
1293
- }
1294
- });
1295
- this.httpServer = (0, import_node_http.createServer)(async (req, res) => {
115
+ this.server = (0, import_node_http.createServer)(async (req, res) => {
1296
116
  if (!req.url || !req.method) {
1297
117
  res.writeHead(400);
1298
118
  res.end("Bad Request");
1299
119
  return;
1300
120
  }
1301
- if (req.url === "/mcp") {
121
+ const url = new URL(req.url, `http://${req.headers.host}`);
122
+ if (url.pathname === "/.well-known/oauth-authorization-server") {
123
+ const config = {
124
+ issuer: "https://accounts.google.com",
125
+ authorization_endpoint: "https://accounts.google.com/o/oauth2/v2/auth",
126
+ token_endpoint: "https://oauth2.googleapis.com/token",
127
+ jwks_uri: "https://www.googleapis.com/oauth2/v3/certs",
128
+ response_types_supported: [
129
+ "code",
130
+ "token",
131
+ "id_token",
132
+ "code token",
133
+ "code id_token",
134
+ "token id_token",
135
+ "code token id_token"
136
+ ],
137
+ subject_types_supported: ["public"],
138
+ id_token_signing_alg_values_supported: ["RS256"],
139
+ scopes_supported: ["openid", "email", "profile"],
140
+ token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"]
141
+ };
142
+ res.writeHead(200, { "Content-Type": "application/json" });
143
+ res.end(JSON.stringify(config));
144
+ return;
145
+ }
146
+ if (url.pathname === "/") {
1302
147
  const sessionId = req.headers["mcp-session-id"];
1303
148
  if (req.method === "POST") {
1304
149
  const bodyChunks = [];
@@ -1331,10 +176,10 @@ var MCPRemote = class extends MCPBase {
1331
176
  }
1332
177
  };
1333
178
  this.mcpServer = new import_mcp.McpServer({
1334
- name: this.serverName || "FIXParser",
1335
- version: this.serverVersion || "1.0.0"
179
+ name: this.name || "FIXParser",
180
+ version: this.version || "1.0.0"
1336
181
  });
1337
- this.setupTools();
182
+ this.addWorkflows();
1338
183
  await this.mcpServer.connect(transport);
1339
184
  } else {
1340
185
  res.writeHead(400, { "Content-Type": "application/json" });
@@ -1350,15 +195,7 @@ var MCPRemote = class extends MCPBase {
1350
195
  );
1351
196
  return;
1352
197
  }
1353
- try {
1354
- await transport.handleRequest(req, res, parsed);
1355
- } catch (error) {
1356
- this.logger?.log({
1357
- level: "error",
1358
- message: `Error handling request: ${error}`
1359
- });
1360
- throw error;
1361
- }
198
+ await transport.handleRequest(req, res, parsed);
1362
199
  });
1363
200
  } else if (req.method === "GET" || req.method === "DELETE") {
1364
201
  if (!sessionId || !transports[sessionId]) {
@@ -1367,29 +204,17 @@ var MCPRemote = class extends MCPBase {
1367
204
  return;
1368
205
  }
1369
206
  const transport = transports[sessionId];
1370
- try {
1371
- await transport.handleRequest(req, res);
1372
- } catch (error) {
1373
- this.logger?.log({
1374
- level: "error",
1375
- message: `Error handling ${req.method} request: ${error}`
1376
- });
1377
- throw error;
1378
- }
207
+ await transport.handleRequest(req, res);
1379
208
  } else {
1380
- this.logger?.log({
1381
- level: "error",
1382
- message: `Method not allowed: ${req.method}`
1383
- });
1384
209
  res.writeHead(405);
1385
210
  res.end("Method Not Allowed");
1386
211
  }
1387
- } else {
1388
- res.writeHead(404);
1389
- res.end("Not Found");
212
+ return;
1390
213
  }
214
+ res.writeHead(404);
215
+ res.end("Not Found");
1391
216
  });
1392
- this.httpServer.listen(this.port, () => {
217
+ this.server.listen(this.port, () => {
1393
218
  this.logger?.log({
1394
219
  level: "info",
1395
220
  message: `FIXParser (MCP): -- Server listening on http://localhost:${this.port}...`
@@ -1399,55 +224,381 @@ var MCPRemote = class extends MCPBase {
1399
224
  this.onReady();
1400
225
  }
1401
226
  }
1402
- setupTools() {
227
+ addWorkflows() {
1403
228
  if (!this.parser) {
1404
229
  this.logger?.log({
1405
230
  level: "error",
1406
- message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of tools..."
231
+ message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of workflows..."
1407
232
  });
1408
233
  return;
1409
234
  }
1410
235
  if (!this.mcpServer) {
1411
236
  this.logger?.log({
1412
237
  level: "error",
1413
- message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of tools..."
238
+ message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of workflows..."
1414
239
  });
1415
240
  return;
1416
241
  }
1417
- const toolHandlers = createToolHandlers(
1418
- this.parser,
1419
- this.verifiedOrders,
1420
- this.pendingRequests,
1421
- this.marketDataPrices
242
+ this.mcpServer.tool(
243
+ "parse",
244
+ "Parses a FIX message and describes it in plain language",
245
+ { fixString: import_zod.z.string() },
246
+ async ({ fixString }) => {
247
+ const parsedMessage = this.parser?.parse(fixString);
248
+ if (!parsedMessage || parsedMessage.length === 0) {
249
+ this.logger?.log({
250
+ level: "error",
251
+ message: "FIXParser (MCP): -- Failed to parse FIX string"
252
+ });
253
+ return {
254
+ isError: true,
255
+ content: [
256
+ {
257
+ type: "text",
258
+ text: "Error: Failed to parse FIX string"
259
+ }
260
+ ]
261
+ };
262
+ }
263
+ return {
264
+ content: [
265
+ {
266
+ type: "text",
267
+ text: parsedMessage ? `${parsedMessage[0].description} - ${parsedMessage[0].messageTypeDescription}` : ""
268
+ }
269
+ ]
270
+ };
271
+ }
1422
272
  );
1423
- Object.entries(toolSchemas).forEach(([name, { description, schema }]) => {
1424
- this.mcpServer?.registerTool(
1425
- name,
1426
- {
1427
- description,
1428
- inputSchema: jsonSchemaToZod(schema)
1429
- },
1430
- async (args) => {
1431
- const handler = toolHandlers[name];
1432
- if (!handler) {
1433
- return {
1434
- content: [
1435
- {
1436
- type: "text",
1437
- text: `Tool not found: ${name}`
1438
- }
1439
- ],
1440
- isError: true
1441
- };
273
+ this.mcpServer.prompt(
274
+ "parse",
275
+ "Parses a FIX message and describes it in plain language",
276
+ { fixString: import_zod.z.string() },
277
+ ({ fixString }) => ({
278
+ messages: [
279
+ {
280
+ role: "user",
281
+ content: {
282
+ type: "text",
283
+ text: `Please parse and explain this FIX message: ${fixString}`
284
+ }
1442
285
  }
1443
- const result = await handler(args);
286
+ ]
287
+ })
288
+ );
289
+ this.mcpServer.tool(
290
+ "parseToJSON",
291
+ "Parses a FIX message into JSON",
292
+ { fixString: import_zod.z.string() },
293
+ async ({ fixString }) => {
294
+ const parsedMessage = this.parser?.parse(fixString);
295
+ if (!parsedMessage || parsedMessage.length === 0) {
296
+ this.logger?.log({
297
+ level: "error",
298
+ message: "FIXParser (MCP): -- Failed to parse FIX string"
299
+ });
1444
300
  return {
1445
- content: result.content,
1446
- isError: result.isError
301
+ isError: true,
302
+ content: [
303
+ {
304
+ type: "text",
305
+ text: "Error: Failed to parse FIX string"
306
+ }
307
+ ]
1447
308
  };
1448
309
  }
1449
- );
1450
- });
310
+ return {
311
+ content: [
312
+ {
313
+ type: "text",
314
+ text: parsedMessage ? JSON.stringify(parsedMessage[0].toFIXJSON()) : ""
315
+ }
316
+ ]
317
+ };
318
+ }
319
+ );
320
+ this.mcpServer.prompt(
321
+ "parseToJSON",
322
+ "Parses a FIX message into JSON",
323
+ { fixString: import_zod.z.string() },
324
+ ({ fixString }) => ({
325
+ messages: [
326
+ {
327
+ role: "user",
328
+ content: {
329
+ type: "text",
330
+ text: `Please parse the FIX message to JSON: ${fixString}`
331
+ }
332
+ }
333
+ ]
334
+ })
335
+ );
336
+ this.mcpServer.tool(
337
+ "newOrderSingle",
338
+ "Creates and sends a New Order Single",
339
+ {
340
+ clOrdID: import_zod.z.string(),
341
+ handlInst: import_zod.z.enum(["1", "2", "3"]).default(import_fixparser.HandlInst.AutomatedExecutionNoIntervention).optional(),
342
+ quantity: import_zod.z.number(),
343
+ price: import_zod.z.number(),
344
+ ordType: import_zod.z.enum([
345
+ "1",
346
+ "2",
347
+ "3",
348
+ "4",
349
+ "5",
350
+ "6",
351
+ "7",
352
+ "8",
353
+ "9",
354
+ "A",
355
+ "B",
356
+ "C",
357
+ "D",
358
+ "E",
359
+ "F",
360
+ "G",
361
+ "H",
362
+ "I",
363
+ "J",
364
+ "K",
365
+ "L",
366
+ "M",
367
+ "P",
368
+ "Q",
369
+ "R",
370
+ "S"
371
+ ]).default(import_fixparser.OrdType.Market).optional(),
372
+ side: import_zod.z.enum(["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"]),
373
+ // 1 = Buy, 2 = Sell...
374
+ symbol: import_zod.z.string(),
375
+ timeInForce: import_zod.z.enum(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"]).default(import_fixparser.TimeInForce.Day).optional()
376
+ },
377
+ async ({ clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce }) => {
378
+ const response = new Promise((resolve) => {
379
+ this.pendingRequests.set(clOrdID, resolve);
380
+ });
381
+ const order = this.parser?.createMessage(
382
+ new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.NewOrderSingle),
383
+ new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
384
+ new import_fixparser.Field(import_fixparser.Fields.SenderCompID, this.parser?.sender),
385
+ new import_fixparser.Field(import_fixparser.Fields.TargetCompID, this.parser?.target),
386
+ new import_fixparser.Field(import_fixparser.Fields.SendingTime, this.parser?.getTimestamp()),
387
+ new import_fixparser.Field(import_fixparser.Fields.ClOrdID, clOrdID),
388
+ new import_fixparser.Field(import_fixparser.Fields.Side, side),
389
+ new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol),
390
+ new import_fixparser.Field(import_fixparser.Fields.OrderQty, quantity),
391
+ new import_fixparser.Field(import_fixparser.Fields.Price, price),
392
+ new import_fixparser.Field(import_fixparser.Fields.OrdType, ordType),
393
+ new import_fixparser.Field(import_fixparser.Fields.HandlInst, handlInst),
394
+ new import_fixparser.Field(import_fixparser.Fields.TimeInForce, timeInForce),
395
+ new import_fixparser.Field(import_fixparser.Fields.TransactTime, this.parser?.getTimestamp())
396
+ );
397
+ if (!this.parser?.connected) {
398
+ this.logger?.log({
399
+ level: "error",
400
+ message: "FIXParser (MCP): -- Not connected. Ignoring message."
401
+ });
402
+ return {
403
+ isError: true,
404
+ content: [
405
+ {
406
+ type: "text",
407
+ text: "Error: Not connected. Ignoring message."
408
+ }
409
+ ]
410
+ };
411
+ }
412
+ this.parser?.send(order);
413
+ this.logger?.log({
414
+ level: "info",
415
+ message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${order?.description}`
416
+ });
417
+ const fixData = await response;
418
+ return {
419
+ content: [
420
+ {
421
+ type: "text",
422
+ text: `Execution Report for order ${clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`
423
+ }
424
+ ]
425
+ };
426
+ }
427
+ );
428
+ this.mcpServer.prompt(
429
+ "newOrderSingle",
430
+ "Creates and sends a New Order Single",
431
+ {
432
+ clOrdID: import_zod.z.string(),
433
+ handlInst: import_zod.z.string(),
434
+ quantity: import_zod.z.string(),
435
+ price: import_zod.z.string(),
436
+ ordType: import_zod.z.string(),
437
+ side: import_zod.z.string(),
438
+ symbol: import_zod.z.string(),
439
+ timeInForce: import_zod.z.string()
440
+ },
441
+ ({ clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce }) => ({
442
+ messages: [
443
+ {
444
+ role: "user",
445
+ content: {
446
+ type: "text",
447
+ text: [
448
+ "Create a New Order Single FIX message with the following parameters:",
449
+ `- ClOrdID: ${clOrdID}`,
450
+ `- HandlInst: ${handlInst ?? "default"}`,
451
+ `- Quantity: ${quantity}`,
452
+ `- Price: ${price}`,
453
+ `- OrdType: ${ordType ?? "default (Market)"}`,
454
+ `- Side: ${side}`,
455
+ `- Symbol: ${symbol}`,
456
+ `- TimeInForce: ${timeInForce ?? "default (Day)"}`,
457
+ "",
458
+ "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values."
459
+ ].join("\n")
460
+ }
461
+ }
462
+ ]
463
+ })
464
+ );
465
+ this.mcpServer.tool(
466
+ "marketDataRequest",
467
+ "Sends a request for Market Data with the given symbol",
468
+ {
469
+ mdUpdateType: import_zod.z.enum(["0", "1"]).default("0").optional(),
470
+ // MDUpdateType.FullRefresh
471
+ symbol: import_zod.z.string(),
472
+ mdReqID: import_zod.z.string(),
473
+ subscriptionRequestType: import_zod.z.enum(["0", "1", "2"]).default(import_fixparser.SubscriptionRequestType.SnapshotAndUpdates).optional(),
474
+ mdEntryType: import_zod.z.enum([
475
+ "0",
476
+ "1",
477
+ "2",
478
+ "3",
479
+ "4",
480
+ "5",
481
+ "6",
482
+ "7",
483
+ "8",
484
+ "9",
485
+ "A",
486
+ "B",
487
+ "C",
488
+ "D",
489
+ "E",
490
+ "F",
491
+ "G",
492
+ "H",
493
+ "J",
494
+ "K",
495
+ "L",
496
+ "M",
497
+ "N",
498
+ "O",
499
+ "P",
500
+ "Q",
501
+ "S",
502
+ "R",
503
+ "T",
504
+ "U",
505
+ "V",
506
+ "W",
507
+ "X",
508
+ "Y",
509
+ "Z",
510
+ "a",
511
+ "b",
512
+ "c",
513
+ "d",
514
+ "e",
515
+ "g",
516
+ "h",
517
+ "i",
518
+ "t"
519
+ ]).default(import_fixparser.MDEntryType.Bid).optional()
520
+ },
521
+ async ({ mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType }) => {
522
+ const response = new Promise((resolve) => {
523
+ this.pendingRequests.set(mdReqID, resolve);
524
+ });
525
+ const marketDataRequest = this.parser?.createMessage(
526
+ new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
527
+ new import_fixparser.Field(import_fixparser.Fields.SenderCompID, this.parser?.sender),
528
+ new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
529
+ new import_fixparser.Field(import_fixparser.Fields.TargetCompID, this.parser?.target),
530
+ new import_fixparser.Field(import_fixparser.Fields.SendingTime, this.parser?.getTimestamp()),
531
+ new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
532
+ new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, mdUpdateType),
533
+ new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, 1),
534
+ new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol),
535
+ new import_fixparser.Field(import_fixparser.Fields.MDReqID, mdReqID),
536
+ new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, subscriptionRequestType),
537
+ new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, 1),
538
+ new import_fixparser.Field(import_fixparser.Fields.MDEntryType, mdEntryType)
539
+ );
540
+ if (!this.parser?.connected) {
541
+ this.logger?.log({
542
+ level: "error",
543
+ message: "FIXParser (MCP): -- Not connected. Ignoring message."
544
+ });
545
+ return {
546
+ isError: true,
547
+ content: [
548
+ {
549
+ type: "text",
550
+ text: "Error: Not connected. Ignoring message."
551
+ }
552
+ ]
553
+ };
554
+ }
555
+ this.parser?.send(marketDataRequest);
556
+ this.logger?.log({
557
+ level: "info",
558
+ message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${marketDataRequest?.description}`
559
+ });
560
+ const fixData = await response;
561
+ return {
562
+ content: [
563
+ {
564
+ type: "text",
565
+ text: `Market data for ${symbol}: ${JSON.stringify(fixData.toFIXJSON())}`
566
+ }
567
+ ]
568
+ };
569
+ }
570
+ );
571
+ this.mcpServer.prompt(
572
+ "marketDataRequest",
573
+ "Sends a request for Market Data with the given symbol",
574
+ {
575
+ mdUpdateType: import_zod.z.string(),
576
+ symbol: import_zod.z.string(),
577
+ mdReqID: import_zod.z.string(),
578
+ subscriptionRequestType: import_zod.z.string(),
579
+ mdEntryType: import_zod.z.string()
580
+ },
581
+ ({ mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType }) => ({
582
+ messages: [
583
+ {
584
+ role: "user",
585
+ content: {
586
+ type: "text",
587
+ text: [
588
+ "Create a Market Data Request FIX message with the following parameters:",
589
+ `- MDUpdateType: ${mdUpdateType ?? "default (0 = FullRefresh)"}`,
590
+ `- Symbol: ${symbol}`,
591
+ `- MDReqID: ${mdReqID}`,
592
+ `- SubscriptionRequestType: ${subscriptionRequestType ?? "default (0 = Snapshot + Updates)"}`,
593
+ `- MDEntryType: ${mdEntryType ?? "default (0 = Bid)"}`,
594
+ "",
595
+ "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values."
596
+ ].join("\n")
597
+ }
598
+ }
599
+ ]
600
+ })
601
+ );
1451
602
  }
1452
603
  };
1453
604
  // Annotate the CommonJS export names for ESM import in node: