fixparser-plugin-mcp 9.1.7-edd3725d → 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.
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
+ var __create = Object.create;
2
3
  var __defProp = Object.defineProperty;
3
4
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
5
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
8
  var __export = (target, all) => {
7
9
  for (var name in all)
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
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
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/MCPLocal.ts
@@ -25,180 +35,1219 @@ __export(MCPLocal_exports, {
25
35
  module.exports = __toCommonJS(MCPLocal_exports);
26
36
  var import_server = require("@modelcontextprotocol/sdk/server/index.js");
27
37
  var import_stdio = require("@modelcontextprotocol/sdk/server/stdio.js");
28
- var import_types = require("@modelcontextprotocol/sdk/types.js");
29
- var import_fixparser = require("fixparser");
30
- var parseInputSchema = {
31
- type: "object",
32
- properties: {
33
- fixString: {
34
- type: "string",
35
- description: "FIX message string to parse"
38
+ var import_zod = require("zod");
39
+
40
+ // src/MCPBase.ts
41
+ var MCPBase = class {
42
+ /**
43
+ * Optional logger instance for diagnostics and output.
44
+ * @protected
45
+ */
46
+ logger;
47
+ /**
48
+ * FIXParser instance, set during plugin register().
49
+ * @protected
50
+ */
51
+ parser;
52
+ /**
53
+ * Called when server is setup and listening.
54
+ * @protected
55
+ */
56
+ onReady = void 0;
57
+ /**
58
+ * Map to store verified orders before execution
59
+ * @protected
60
+ */
61
+ verifiedOrders = /* @__PURE__ */ new Map();
62
+ /**
63
+ * Map to store pending market data requests
64
+ * @protected
65
+ */
66
+ pendingRequests = /* @__PURE__ */ new Map();
67
+ /**
68
+ * Map to store market data prices
69
+ * @protected
70
+ */
71
+ marketDataPrices = /* @__PURE__ */ new Map();
72
+ /**
73
+ * Maximum number of price history entries to keep per symbol
74
+ * @protected
75
+ */
76
+ MAX_PRICE_HISTORY = 1e5;
77
+ constructor({ logger, onReady }) {
78
+ this.logger = logger;
79
+ this.onReady = onReady;
80
+ }
81
+ };
82
+
83
+ // src/schemas/schemas.ts
84
+ var toolSchemas = {
85
+ parse: {
86
+ description: "Parses a FIX message and describes it in plain language",
87
+ schema: {
88
+ type: "object",
89
+ properties: {
90
+ fixString: { type: "string" }
91
+ },
92
+ required: ["fixString"]
36
93
  }
37
94
  },
38
- required: ["fixString"]
39
- };
40
- var parseToJSONInputSchema = {
41
- type: "object",
42
- properties: {
43
- fixString: {
44
- type: "string",
45
- description: "FIX message string to parse"
95
+ parseToJSON: {
96
+ description: "Parses a FIX message into JSON",
97
+ schema: {
98
+ type: "object",
99
+ properties: {
100
+ fixString: { type: "string" }
101
+ },
102
+ required: ["fixString"]
46
103
  }
47
104
  },
48
- required: ["fixString"]
49
- };
50
- var newOrderSingleInputSchema = {
51
- type: "object",
52
- properties: {
53
- clOrdID: {
54
- type: "string",
55
- description: "Client Order ID"
56
- },
57
- handlInst: {
58
- type: "string",
59
- enum: ["1", "2", "3"],
60
- default: import_fixparser.HandlInst.AutomatedExecutionNoIntervention,
61
- description: 'Handling instruction (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "1" for Manual, "2" for Automated, "3" for AutomatedNoIntervention)'
62
- },
63
- quantity: {
64
- type: "number",
65
- description: "Order quantity"
66
- },
67
- price: {
68
- type: "number",
69
- description: "Order price"
70
- },
71
- ordType: {
72
- type: "string",
73
- enum: [
74
- "1",
75
- "2",
76
- "3",
77
- "4",
78
- "5",
79
- "6",
80
- "7",
81
- "8",
82
- "9",
83
- "A",
84
- "B",
85
- "C",
86
- "D",
87
- "E",
88
- "F",
89
- "G",
90
- "H",
91
- "I",
92
- "J",
93
- "K",
94
- "L",
95
- "M",
96
- "P",
97
- "Q",
98
- "R",
99
- "S"
100
- ],
101
- default: import_fixparser.OrdType.Market,
102
- description: 'Order type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "1" for Market, "2" for Limit, "3" for Stop)'
103
- },
104
- side: {
105
- type: "string",
106
- enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
107
- description: 'Order side (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "1" for Buy, "2" for Sell, "3" for BuyMinus, "4" for SellPlus, "5" for SellShort, "6" for SellShortExempt, "7" for Undisclosed, "8" for Cross, "9" for CrossShort, "A" for CrossShortExempt, "B" for AsDefined, "C" for Opposite, "D" for Subscribe, "E" for Redeem, "F" for Lend, "G" for Borrow, "H" for SellUndisclosed)'
108
- },
109
- symbol: {
110
- type: "string",
111
- description: "Trading symbol"
112
- },
113
- timeInForce: {
114
- type: "string",
115
- enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
116
- default: import_fixparser.TimeInForce.Day,
117
- description: 'Time in force (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Day, "1" for Good Till Cancel, "2" for At Opening, "3" for Immediate or Cancel, "4" for Fill or Kill, "5" for Good Till Crossing, "6" for Good Till Date)'
105
+ verifyOrder: {
106
+ description: "Verifies order parameters before execution. verifyOrder must be called before executeOrder.",
107
+ schema: {
108
+ type: "object",
109
+ properties: {
110
+ clOrdID: { type: "string" },
111
+ handlInst: {
112
+ type: "string",
113
+ enum: ["1", "2", "3"],
114
+ description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
115
+ },
116
+ quantity: { type: "string" },
117
+ price: { type: "string" },
118
+ ordType: {
119
+ type: "string",
120
+ enum: [
121
+ "1",
122
+ "2",
123
+ "3",
124
+ "4",
125
+ "5",
126
+ "6",
127
+ "7",
128
+ "8",
129
+ "9",
130
+ "A",
131
+ "B",
132
+ "C",
133
+ "D",
134
+ "E",
135
+ "F",
136
+ "G",
137
+ "H",
138
+ "I",
139
+ "J",
140
+ "K",
141
+ "L",
142
+ "M",
143
+ "P",
144
+ "Q",
145
+ "R",
146
+ "S"
147
+ ],
148
+ 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"
149
+ },
150
+ side: {
151
+ type: "string",
152
+ enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
153
+ 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"
154
+ },
155
+ symbol: { type: "string" },
156
+ timeInForce: {
157
+ type: "string",
158
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
159
+ 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"
160
+ }
161
+ },
162
+ required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
118
163
  }
119
164
  },
120
- required: ["clOrdID", "quantity", "price", "side", "symbol"]
121
- };
122
- var marketDataRequestInputSchema = {
123
- type: "object",
124
- properties: {
125
- mdUpdateType: {
126
- type: "string",
127
- enum: ["0", "1"],
128
- default: "0",
129
- description: 'Market data update type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for FullRefresh, "1" for IncrementalRefresh)'
130
- },
131
- symbol: {
132
- type: "string",
133
- description: "Trading symbol"
134
- },
135
- mdReqID: {
136
- type: "string",
137
- description: "Market data request ID"
138
- },
139
- subscriptionRequestType: {
140
- type: "string",
141
- enum: ["0", "1", "2"],
142
- default: import_fixparser.SubscriptionRequestType.SnapshotAndUpdates,
143
- description: 'Subscription request type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Snapshot + Updates, "1" for Snapshot, "2" for Unsubscribe)'
144
- },
145
- mdEntryType: {
146
- type: "string",
147
- enum: [
148
- "0",
149
- "1",
150
- "2",
151
- "3",
152
- "4",
153
- "5",
154
- "6",
155
- "7",
156
- "8",
157
- "9",
158
- "A",
159
- "B",
160
- "C",
161
- "D",
162
- "E",
163
- "F",
164
- "G",
165
- "H",
166
- "J",
167
- "K",
168
- "L",
169
- "M",
170
- "N",
171
- "O",
172
- "P",
173
- "Q",
174
- "S",
175
- "R",
176
- "T",
177
- "U",
178
- "V",
179
- "W",
180
- "X",
181
- "Y",
182
- "Z",
183
- "a",
184
- "b",
185
- "c",
186
- "d",
187
- "e",
188
- "g",
189
- "h",
190
- "i",
191
- "t"
192
- ],
193
- default: import_fixparser.MDEntryType.Bid,
194
- description: 'Market data entry type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Bid, "1" for Offer, "2" for Trade, "3" for Index Value, "4" for Opening Price)'
165
+ executeOrder: {
166
+ description: "Executes a verified order. verifyOrder must be called before executeOrder.",
167
+ schema: {
168
+ type: "object",
169
+ properties: {
170
+ clOrdID: { type: "string" },
171
+ handlInst: {
172
+ type: "string",
173
+ enum: ["1", "2", "3"],
174
+ description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
175
+ },
176
+ quantity: { type: "string" },
177
+ price: { type: "string" },
178
+ ordType: {
179
+ type: "string",
180
+ enum: [
181
+ "1",
182
+ "2",
183
+ "3",
184
+ "4",
185
+ "5",
186
+ "6",
187
+ "7",
188
+ "8",
189
+ "9",
190
+ "A",
191
+ "B",
192
+ "C",
193
+ "D",
194
+ "E",
195
+ "F",
196
+ "G",
197
+ "H",
198
+ "I",
199
+ "J",
200
+ "K",
201
+ "L",
202
+ "M",
203
+ "P",
204
+ "Q",
205
+ "R",
206
+ "S"
207
+ ],
208
+ 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"
209
+ },
210
+ side: {
211
+ type: "string",
212
+ enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
213
+ 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"
214
+ },
215
+ symbol: { type: "string" },
216
+ timeInForce: {
217
+ type: "string",
218
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
219
+ 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"
220
+ }
221
+ },
222
+ required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
223
+ }
224
+ },
225
+ marketDataRequest: {
226
+ description: "Requests market data for specified symbols",
227
+ schema: {
228
+ type: "object",
229
+ properties: {
230
+ mdUpdateType: {
231
+ type: "string",
232
+ enum: ["0", "1"],
233
+ description: "Market Data Update Type: 0=Full Refresh, 1=Incremental Refresh"
234
+ },
235
+ symbols: { type: "array", items: { type: "string" } },
236
+ mdReqID: { type: "string" },
237
+ subscriptionRequestType: {
238
+ type: "string",
239
+ enum: ["0", "1", "2"],
240
+ description: "Subscription Request Type: 0=Snapshot, 1=Snapshot + Updates, 2=Disable Previous Snapshot + Update Request"
241
+ },
242
+ mdEntryTypes: {
243
+ type: "array",
244
+ items: {
245
+ type: "string",
246
+ enum: [
247
+ "0",
248
+ "1",
249
+ "2",
250
+ "3",
251
+ "4",
252
+ "5",
253
+ "6",
254
+ "7",
255
+ "8",
256
+ "9",
257
+ "A",
258
+ "B",
259
+ "C",
260
+ "D",
261
+ "E",
262
+ "F",
263
+ "G",
264
+ "H",
265
+ "I",
266
+ "J",
267
+ "K",
268
+ "L",
269
+ "M",
270
+ "N",
271
+ "O",
272
+ "P",
273
+ "Q",
274
+ "R",
275
+ "S",
276
+ "T",
277
+ "U",
278
+ "V",
279
+ "W",
280
+ "X",
281
+ "Y",
282
+ "Z"
283
+ ]
284
+ },
285
+ 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"
286
+ }
287
+ },
288
+ required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType"]
289
+ }
290
+ },
291
+ getStockGraph: {
292
+ description: "Generates a price chart for a given symbol",
293
+ schema: {
294
+ type: "object",
295
+ properties: {
296
+ symbol: { type: "string" }
297
+ },
298
+ required: ["symbol"]
195
299
  }
196
300
  },
197
- required: ["symbol", "mdReqID"]
301
+ getStockPriceHistory: {
302
+ description: "Returns price history for a given symbol",
303
+ schema: {
304
+ type: "object",
305
+ properties: {
306
+ symbol: { type: "string" }
307
+ },
308
+ required: ["symbol"]
309
+ }
310
+ }
198
311
  };
199
- var MCPLocal = class {
200
- logger;
201
- parser;
312
+
313
+ // src/tools/marketData.ts
314
+ var import_fixparser = require("fixparser");
315
+ var import_quickchart_js = __toESM(require("quickchart-js"), 1);
316
+ var createMarketDataRequestHandler = (parser, pendingRequests) => {
317
+ return async (args) => {
318
+ try {
319
+ parser.logger.log({
320
+ level: "info",
321
+ message: `Sending market data request for symbols: ${args.symbols.join(", ")}`
322
+ });
323
+ const response = new Promise((resolve) => {
324
+ pendingRequests.set(args.mdReqID, resolve);
325
+ parser.logger.log({
326
+ level: "info",
327
+ message: `Registered callback for market data request ID: ${args.mdReqID}`
328
+ });
329
+ });
330
+ const entryTypes = args.mdEntryTypes || [
331
+ import_fixparser.MDEntryType.Bid,
332
+ import_fixparser.MDEntryType.Offer,
333
+ import_fixparser.MDEntryType.Trade,
334
+ import_fixparser.MDEntryType.IndexValue,
335
+ import_fixparser.MDEntryType.OpeningPrice,
336
+ import_fixparser.MDEntryType.ClosingPrice,
337
+ import_fixparser.MDEntryType.SettlementPrice,
338
+ import_fixparser.MDEntryType.TradingSessionHighPrice,
339
+ import_fixparser.MDEntryType.TradingSessionLowPrice,
340
+ import_fixparser.MDEntryType.VWAP,
341
+ import_fixparser.MDEntryType.Imbalance,
342
+ import_fixparser.MDEntryType.TradeVolume,
343
+ import_fixparser.MDEntryType.OpenInterest,
344
+ import_fixparser.MDEntryType.CompositeUnderlyingPrice,
345
+ import_fixparser.MDEntryType.SimulatedSellPrice,
346
+ import_fixparser.MDEntryType.SimulatedBuyPrice,
347
+ import_fixparser.MDEntryType.MarginRate,
348
+ import_fixparser.MDEntryType.MidPrice,
349
+ import_fixparser.MDEntryType.EmptyBook,
350
+ import_fixparser.MDEntryType.SettleHighPrice,
351
+ import_fixparser.MDEntryType.SettleLowPrice,
352
+ import_fixparser.MDEntryType.PriorSettlePrice,
353
+ import_fixparser.MDEntryType.SessionHighBid,
354
+ import_fixparser.MDEntryType.SessionLowOffer,
355
+ import_fixparser.MDEntryType.EarlyPrices,
356
+ import_fixparser.MDEntryType.AuctionClearingPrice,
357
+ import_fixparser.MDEntryType.SwapValueFactor,
358
+ import_fixparser.MDEntryType.DailyValueAdjustmentForLongPositions,
359
+ import_fixparser.MDEntryType.CumulativeValueAdjustmentForLongPositions,
360
+ import_fixparser.MDEntryType.DailyValueAdjustmentForShortPositions,
361
+ import_fixparser.MDEntryType.CumulativeValueAdjustmentForShortPositions,
362
+ import_fixparser.MDEntryType.FixingPrice,
363
+ import_fixparser.MDEntryType.CashRate,
364
+ import_fixparser.MDEntryType.RecoveryRate,
365
+ import_fixparser.MDEntryType.RecoveryRateForLong,
366
+ import_fixparser.MDEntryType.RecoveryRateForShort,
367
+ import_fixparser.MDEntryType.MarketBid,
368
+ import_fixparser.MDEntryType.MarketOffer,
369
+ import_fixparser.MDEntryType.ShortSaleMinPrice,
370
+ import_fixparser.MDEntryType.PreviousClosingPrice,
371
+ import_fixparser.MDEntryType.ThresholdLimitPriceBanding,
372
+ import_fixparser.MDEntryType.DailyFinancingValue,
373
+ import_fixparser.MDEntryType.AccruedFinancingValue,
374
+ import_fixparser.MDEntryType.TWAP
375
+ ];
376
+ const messageFields = [
377
+ new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
378
+ new import_fixparser.Field(import_fixparser.Fields.SenderCompID, parser.sender),
379
+ new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
380
+ new import_fixparser.Field(import_fixparser.Fields.TargetCompID, parser.target),
381
+ new import_fixparser.Field(import_fixparser.Fields.SendingTime, parser.getTimestamp()),
382
+ new import_fixparser.Field(import_fixparser.Fields.MDReqID, args.mdReqID),
383
+ new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, args.subscriptionRequestType),
384
+ new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
385
+ new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, args.mdUpdateType)
386
+ ];
387
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, args.symbols.length));
388
+ args.symbols.forEach((symbol) => {
389
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol));
390
+ });
391
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, entryTypes.length));
392
+ entryTypes.forEach((entryType) => {
393
+ messageFields.push(new import_fixparser.Field(import_fixparser.Fields.MDEntryType, entryType));
394
+ });
395
+ const mdr = parser.createMessage(...messageFields);
396
+ if (!parser.connected) {
397
+ parser.logger.log({
398
+ level: "error",
399
+ message: "Not connected. Cannot send market data request."
400
+ });
401
+ return {
402
+ content: [
403
+ {
404
+ type: "text",
405
+ text: "Error: Not connected. Ignoring message.",
406
+ uri: "marketDataRequest"
407
+ }
408
+ ],
409
+ isError: true
410
+ };
411
+ }
412
+ parser.logger.log({
413
+ level: "info",
414
+ message: `Sending market data request message: ${JSON.stringify(mdr?.toFIXJSON())}`
415
+ });
416
+ parser.send(mdr);
417
+ const fixData = await response;
418
+ parser.logger.log({
419
+ level: "info",
420
+ message: `Received market data response for request ID: ${args.mdReqID}`
421
+ });
422
+ return {
423
+ content: [
424
+ {
425
+ type: "text",
426
+ text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
427
+ uri: "marketDataRequest"
428
+ }
429
+ ]
430
+ };
431
+ } catch (error) {
432
+ return {
433
+ content: [
434
+ {
435
+ type: "text",
436
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
437
+ uri: "marketDataRequest"
438
+ }
439
+ ],
440
+ isError: true
441
+ };
442
+ }
443
+ };
444
+ };
445
+ var createGetStockGraphHandler = (marketDataPrices) => {
446
+ return async (args) => {
447
+ try {
448
+ const symbol = args.symbol;
449
+ const priceHistory = marketDataPrices.get(symbol) || [];
450
+ if (priceHistory.length === 0) {
451
+ return {
452
+ content: [
453
+ {
454
+ type: "text",
455
+ text: `No price data available for ${symbol}`,
456
+ uri: "getStockGraph"
457
+ }
458
+ ]
459
+ };
460
+ }
461
+ const chart = new import_quickchart_js.default();
462
+ chart.setWidth(1200);
463
+ chart.setHeight(600);
464
+ chart.setBackgroundColor("transparent");
465
+ const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
466
+ const bidData = priceHistory.map((point) => point.bid);
467
+ const offerData = priceHistory.map((point) => point.offer);
468
+ const spreadData = priceHistory.map((point) => point.spread);
469
+ const volumeData = priceHistory.map((point) => point.volume);
470
+ const tradeData = priceHistory.map((point) => point.trade);
471
+ const vwapData = priceHistory.map((point) => point.vwap);
472
+ const twapData = priceHistory.map((point) => point.twap);
473
+ const config = {
474
+ type: "line",
475
+ data: {
476
+ labels,
477
+ datasets: [
478
+ {
479
+ label: "Bid",
480
+ data: bidData,
481
+ borderColor: "#28a745",
482
+ backgroundColor: "rgba(40, 167, 69, 0.1)",
483
+ fill: false,
484
+ tension: 0.4
485
+ },
486
+ {
487
+ label: "Offer",
488
+ data: offerData,
489
+ borderColor: "#dc3545",
490
+ backgroundColor: "rgba(220, 53, 69, 0.1)",
491
+ fill: false,
492
+ tension: 0.4
493
+ },
494
+ {
495
+ label: "Spread",
496
+ data: spreadData,
497
+ borderColor: "#6c757d",
498
+ backgroundColor: "rgba(108, 117, 125, 0.1)",
499
+ fill: false,
500
+ tension: 0.4
501
+ },
502
+ {
503
+ label: "Trade",
504
+ data: tradeData,
505
+ borderColor: "#ffc107",
506
+ backgroundColor: "rgba(255, 193, 7, 0.1)",
507
+ fill: false,
508
+ tension: 0.4
509
+ },
510
+ {
511
+ label: "VWAP",
512
+ data: vwapData,
513
+ borderColor: "#17a2b8",
514
+ backgroundColor: "rgba(23, 162, 184, 0.1)",
515
+ fill: false,
516
+ tension: 0.4
517
+ },
518
+ {
519
+ label: "TWAP",
520
+ data: twapData,
521
+ borderColor: "#6610f2",
522
+ backgroundColor: "rgba(102, 16, 242, 0.1)",
523
+ fill: false,
524
+ tension: 0.4
525
+ },
526
+ {
527
+ label: "Volume",
528
+ data: volumeData,
529
+ borderColor: "#007bff",
530
+ backgroundColor: "rgba(0, 123, 255, 0.1)",
531
+ fill: true,
532
+ tension: 0.4
533
+ }
534
+ ]
535
+ },
536
+ options: {
537
+ responsive: true,
538
+ plugins: {
539
+ title: {
540
+ display: true,
541
+ text: `${symbol} Market Data`
542
+ }
543
+ },
544
+ scales: {
545
+ y: {
546
+ beginAtZero: false
547
+ }
548
+ }
549
+ }
550
+ };
551
+ chart.setConfig(config);
552
+ const imageBuffer = await chart.toBinary();
553
+ const base64 = imageBuffer.toString("base64");
554
+ return {
555
+ content: [
556
+ {
557
+ type: "resource",
558
+ resource: {
559
+ uri: "resource://graph",
560
+ mimeType: "image/png",
561
+ blob: base64
562
+ }
563
+ }
564
+ ]
565
+ };
566
+ } catch (error) {
567
+ return {
568
+ content: [
569
+ {
570
+ type: "text",
571
+ text: `Error: ${error instanceof Error ? error.message : "Failed to generate graph"}`,
572
+ uri: "getStockGraph"
573
+ }
574
+ ],
575
+ isError: true
576
+ };
577
+ }
578
+ };
579
+ };
580
+ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
581
+ return async (args) => {
582
+ try {
583
+ const symbol = args.symbol;
584
+ const priceHistory = marketDataPrices.get(symbol) || [];
585
+ if (priceHistory.length === 0) {
586
+ return {
587
+ content: [
588
+ {
589
+ type: "text",
590
+ text: `No price data available for ${symbol}`,
591
+ uri: "getStockPriceHistory"
592
+ }
593
+ ]
594
+ };
595
+ }
596
+ return {
597
+ content: [
598
+ {
599
+ type: "text",
600
+ text: JSON.stringify(
601
+ {
602
+ symbol,
603
+ count: priceHistory.length,
604
+ data: priceHistory.map((point) => ({
605
+ timestamp: new Date(point.timestamp).toISOString(),
606
+ bid: point.bid,
607
+ offer: point.offer,
608
+ spread: point.spread,
609
+ volume: point.volume,
610
+ trade: point.trade,
611
+ indexValue: point.indexValue,
612
+ openingPrice: point.openingPrice,
613
+ closingPrice: point.closingPrice,
614
+ settlementPrice: point.settlementPrice,
615
+ tradingSessionHighPrice: point.tradingSessionHighPrice,
616
+ tradingSessionLowPrice: point.tradingSessionLowPrice,
617
+ vwap: point.vwap,
618
+ imbalance: point.imbalance,
619
+ openInterest: point.openInterest,
620
+ compositeUnderlyingPrice: point.compositeUnderlyingPrice,
621
+ simulatedSellPrice: point.simulatedSellPrice,
622
+ simulatedBuyPrice: point.simulatedBuyPrice,
623
+ marginRate: point.marginRate,
624
+ midPrice: point.midPrice,
625
+ emptyBook: point.emptyBook,
626
+ settleHighPrice: point.settleHighPrice,
627
+ settleLowPrice: point.settleLowPrice,
628
+ priorSettlePrice: point.priorSettlePrice,
629
+ sessionHighBid: point.sessionHighBid,
630
+ sessionLowOffer: point.sessionLowOffer,
631
+ earlyPrices: point.earlyPrices,
632
+ auctionClearingPrice: point.auctionClearingPrice,
633
+ swapValueFactor: point.swapValueFactor,
634
+ dailyValueAdjustmentForLongPositions: point.dailyValueAdjustmentForLongPositions,
635
+ cumulativeValueAdjustmentForLongPositions: point.cumulativeValueAdjustmentForLongPositions,
636
+ dailyValueAdjustmentForShortPositions: point.dailyValueAdjustmentForShortPositions,
637
+ cumulativeValueAdjustmentForShortPositions: point.cumulativeValueAdjustmentForShortPositions,
638
+ fixingPrice: point.fixingPrice,
639
+ cashRate: point.cashRate,
640
+ recoveryRate: point.recoveryRate,
641
+ recoveryRateForLong: point.recoveryRateForLong,
642
+ recoveryRateForShort: point.recoveryRateForShort,
643
+ marketBid: point.marketBid,
644
+ marketOffer: point.marketOffer,
645
+ shortSaleMinPrice: point.shortSaleMinPrice,
646
+ previousClosingPrice: point.previousClosingPrice,
647
+ thresholdLimitPriceBanding: point.thresholdLimitPriceBanding,
648
+ dailyFinancingValue: point.dailyFinancingValue,
649
+ accruedFinancingValue: point.accruedFinancingValue,
650
+ twap: point.twap
651
+ }))
652
+ },
653
+ null,
654
+ 2
655
+ ),
656
+ uri: "getStockPriceHistory"
657
+ }
658
+ ]
659
+ };
660
+ } catch (error) {
661
+ return {
662
+ content: [
663
+ {
664
+ type: "text",
665
+ text: `Error: ${error instanceof Error ? error.message : "Failed to get price history"}`,
666
+ uri: "getStockPriceHistory"
667
+ }
668
+ ],
669
+ isError: true
670
+ };
671
+ }
672
+ };
673
+ };
674
+
675
+ // src/tools/order.ts
676
+ var import_fixparser2 = require("fixparser");
677
+ var ordTypeNames = {
678
+ "1": "Market",
679
+ "2": "Limit",
680
+ "3": "Stop",
681
+ "4": "StopLimit",
682
+ "5": "MarketOnClose",
683
+ "6": "WithOrWithout",
684
+ "7": "LimitOrBetter",
685
+ "8": "LimitWithOrWithout",
686
+ "9": "OnBasis",
687
+ A: "OnClose",
688
+ B: "LimitOnClose",
689
+ C: "ForexMarket",
690
+ D: "PreviouslyQuoted",
691
+ E: "PreviouslyIndicated",
692
+ F: "ForexLimit",
693
+ G: "ForexSwap",
694
+ H: "ForexPreviouslyQuoted",
695
+ I: "Funari",
696
+ J: "MarketIfTouched",
697
+ K: "MarketWithLeftOverAsLimit",
698
+ L: "PreviousFundValuationPoint",
699
+ M: "NextFundValuationPoint",
700
+ P: "Pegged",
701
+ Q: "CounterOrderSelection",
702
+ R: "StopOnBidOrOffer",
703
+ S: "StopLimitOnBidOrOffer"
704
+ };
705
+ var sideNames = {
706
+ "1": "Buy",
707
+ "2": "Sell",
708
+ "3": "BuyMinus",
709
+ "4": "SellPlus",
710
+ "5": "SellShort",
711
+ "6": "SellShortExempt",
712
+ "7": "Undisclosed",
713
+ "8": "Cross",
714
+ "9": "CrossShort",
715
+ A: "CrossShortExempt",
716
+ B: "AsDefined",
717
+ C: "Opposite",
718
+ D: "Subscribe",
719
+ E: "Redeem",
720
+ F: "Lend",
721
+ G: "Borrow",
722
+ H: "SellUndisclosed"
723
+ };
724
+ var timeInForceNames = {
725
+ "0": "Day",
726
+ "1": "GoodTillCancel",
727
+ "2": "AtTheOpening",
728
+ "3": "ImmediateOrCancel",
729
+ "4": "FillOrKill",
730
+ "5": "GoodTillCrossing",
731
+ "6": "GoodTillDate",
732
+ "7": "AtTheClose",
733
+ "8": "GoodThroughCrossing",
734
+ "9": "AtCrossing",
735
+ A: "GoodForTime",
736
+ B: "GoodForAuction",
737
+ C: "GoodForMonth"
738
+ };
739
+ var handlInstNames = {
740
+ "1": "AutomatedExecutionNoIntervention",
741
+ "2": "AutomatedExecutionInterventionOK",
742
+ "3": "ManualOrder"
743
+ };
744
+ var createVerifyOrderHandler = (parser, verifiedOrders) => {
745
+ return async (args) => {
746
+ try {
747
+ verifiedOrders.set(args.clOrdID, {
748
+ clOrdID: args.clOrdID,
749
+ handlInst: args.handlInst,
750
+ quantity: Number.parseFloat(String(args.quantity)),
751
+ price: Number.parseFloat(String(args.price)),
752
+ ordType: args.ordType,
753
+ side: args.side,
754
+ symbol: args.symbol,
755
+ timeInForce: args.timeInForce
756
+ });
757
+ return {
758
+ content: [
759
+ {
760
+ type: "text",
761
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
762
+
763
+ Parameters verified:
764
+ - ClOrdID: ${args.clOrdID}
765
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
766
+ - Quantity: ${args.quantity}
767
+ - Price: ${args.price}
768
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
769
+ - Side: ${args.side} (${sideNames[args.side]})
770
+ - Symbol: ${args.symbol}
771
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
772
+
773
+ To execute this order, call the executeOrder tool with these exact same parameters. Important: The user has to explicitly confirm before executeOrder is called!`,
774
+ uri: "verifyOrder"
775
+ }
776
+ ]
777
+ };
778
+ } catch (error) {
779
+ return {
780
+ content: [
781
+ {
782
+ type: "text",
783
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
784
+ uri: "verifyOrder"
785
+ }
786
+ ],
787
+ isError: true
788
+ };
789
+ }
790
+ };
791
+ };
792
+ var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
793
+ return async (args) => {
794
+ try {
795
+ const verifiedOrder = verifiedOrders.get(args.clOrdID);
796
+ if (!verifiedOrder) {
797
+ return {
798
+ content: [
799
+ {
800
+ type: "text",
801
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
802
+ uri: "executeOrder"
803
+ }
804
+ ],
805
+ isError: true
806
+ };
807
+ }
808
+ 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) {
809
+ return {
810
+ content: [
811
+ {
812
+ type: "text",
813
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
814
+ uri: "executeOrder"
815
+ }
816
+ ],
817
+ isError: true
818
+ };
819
+ }
820
+ const response = new Promise((resolve) => {
821
+ pendingRequests.set(args.clOrdID, resolve);
822
+ });
823
+ const order = parser.createMessage(
824
+ new import_fixparser2.Field(import_fixparser2.Fields.MsgType, import_fixparser2.Messages.NewOrderSingle),
825
+ new import_fixparser2.Field(import_fixparser2.Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
826
+ new import_fixparser2.Field(import_fixparser2.Fields.SenderCompID, parser.sender),
827
+ new import_fixparser2.Field(import_fixparser2.Fields.TargetCompID, parser.target),
828
+ new import_fixparser2.Field(import_fixparser2.Fields.SendingTime, parser.getTimestamp()),
829
+ new import_fixparser2.Field(import_fixparser2.Fields.ClOrdID, args.clOrdID),
830
+ new import_fixparser2.Field(import_fixparser2.Fields.Side, args.side),
831
+ new import_fixparser2.Field(import_fixparser2.Fields.Symbol, args.symbol),
832
+ new import_fixparser2.Field(import_fixparser2.Fields.OrderQty, Number.parseFloat(String(args.quantity))),
833
+ new import_fixparser2.Field(import_fixparser2.Fields.Price, Number.parseFloat(String(args.price))),
834
+ new import_fixparser2.Field(import_fixparser2.Fields.OrdType, args.ordType),
835
+ new import_fixparser2.Field(import_fixparser2.Fields.HandlInst, args.handlInst),
836
+ new import_fixparser2.Field(import_fixparser2.Fields.TimeInForce, args.timeInForce),
837
+ new import_fixparser2.Field(import_fixparser2.Fields.TransactTime, parser.getTimestamp())
838
+ );
839
+ if (!parser.connected) {
840
+ return {
841
+ content: [
842
+ {
843
+ type: "text",
844
+ text: "Error: Not connected. Ignoring message.",
845
+ uri: "executeOrder"
846
+ }
847
+ ],
848
+ isError: true
849
+ };
850
+ }
851
+ parser.send(order);
852
+ const fixData = await response;
853
+ verifiedOrders.delete(args.clOrdID);
854
+ return {
855
+ content: [
856
+ {
857
+ type: "text",
858
+ 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())}`,
859
+ uri: "executeOrder"
860
+ }
861
+ ]
862
+ };
863
+ } catch (error) {
864
+ return {
865
+ content: [
866
+ {
867
+ type: "text",
868
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
869
+ uri: "executeOrder"
870
+ }
871
+ ],
872
+ isError: true
873
+ };
874
+ }
875
+ };
876
+ };
877
+
878
+ // src/tools/parse.ts
879
+ var createParseHandler = (parser) => {
880
+ return async (args) => {
881
+ try {
882
+ const parsedMessage = parser.parse(args.fixString);
883
+ if (!parsedMessage || parsedMessage.length === 0) {
884
+ return {
885
+ content: [
886
+ {
887
+ type: "text",
888
+ text: "Error: Failed to parse FIX string",
889
+ uri: "parse"
890
+ }
891
+ ],
892
+ isError: true
893
+ };
894
+ }
895
+ return {
896
+ content: [
897
+ {
898
+ type: "text",
899
+ text: `${parsedMessage[0].description}
900
+ ${parsedMessage[0].messageTypeDescription}`,
901
+ uri: "parse"
902
+ }
903
+ ]
904
+ };
905
+ } catch (error) {
906
+ return {
907
+ content: [
908
+ {
909
+ type: "text",
910
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
911
+ uri: "parse"
912
+ }
913
+ ],
914
+ isError: true
915
+ };
916
+ }
917
+ };
918
+ };
919
+
920
+ // src/tools/parseToJSON.ts
921
+ var createParseToJSONHandler = (parser) => {
922
+ return async (args) => {
923
+ try {
924
+ const parsedMessage = parser.parse(args.fixString);
925
+ if (!parsedMessage || parsedMessage.length === 0) {
926
+ return {
927
+ content: [
928
+ {
929
+ type: "text",
930
+ text: "Error: Failed to parse FIX string",
931
+ uri: "parseToJSON"
932
+ }
933
+ ],
934
+ isError: true
935
+ };
936
+ }
937
+ return {
938
+ content: [
939
+ {
940
+ type: "text",
941
+ text: `${parsedMessage[0].toFIXJSON()}`,
942
+ uri: "parseToJSON"
943
+ }
944
+ ]
945
+ };
946
+ } catch (error) {
947
+ return {
948
+ content: [
949
+ {
950
+ type: "text",
951
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
952
+ uri: "parseToJSON"
953
+ }
954
+ ],
955
+ isError: true
956
+ };
957
+ }
958
+ };
959
+ };
960
+
961
+ // src/tools/index.ts
962
+ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
963
+ parse: createParseHandler(parser),
964
+ parseToJSON: createParseToJSONHandler(parser),
965
+ verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
966
+ executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
967
+ marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
968
+ getStockGraph: createGetStockGraphHandler(marketDataPrices),
969
+ getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
970
+ });
971
+
972
+ // src/utils/messageHandler.ts
973
+ var import_fixparser3 = require("fixparser");
974
+ function handleMessage(message, parser, pendingRequests, marketDataPrices, maxPriceHistory, onPriceUpdate) {
975
+ parser.logger.log({
976
+ level: "info",
977
+ message: `MCP Server received message: ${message.messageType}: ${message.description}`
978
+ });
979
+ const msgType = message.messageType;
980
+ if (msgType === import_fixparser3.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser3.Messages.MarketDataIncrementalRefresh) {
981
+ const symbol = message.getField(import_fixparser3.Fields.Symbol)?.value;
982
+ parser.logger.log({
983
+ level: "info",
984
+ message: `Processing market data for symbol: ${symbol}`
985
+ });
986
+ const fixJson = message.toFIXJSON();
987
+ const entries = fixJson.Body?.NoMDEntries || [];
988
+ parser.logger.log({
989
+ level: "info",
990
+ message: `Found ${entries.length} market data entries`
991
+ });
992
+ const data = {
993
+ timestamp: Date.now(),
994
+ bid: 0,
995
+ offer: 0,
996
+ spread: 0,
997
+ volume: 0,
998
+ trade: 0,
999
+ indexValue: 0,
1000
+ openingPrice: 0,
1001
+ closingPrice: 0,
1002
+ settlementPrice: 0,
1003
+ tradingSessionHighPrice: 0,
1004
+ tradingSessionLowPrice: 0,
1005
+ vwap: 0,
1006
+ imbalance: 0,
1007
+ openInterest: 0,
1008
+ compositeUnderlyingPrice: 0,
1009
+ simulatedSellPrice: 0,
1010
+ simulatedBuyPrice: 0,
1011
+ marginRate: 0,
1012
+ midPrice: 0,
1013
+ emptyBook: 0,
1014
+ settleHighPrice: 0,
1015
+ settleLowPrice: 0,
1016
+ priorSettlePrice: 0,
1017
+ sessionHighBid: 0,
1018
+ sessionLowOffer: 0,
1019
+ earlyPrices: 0,
1020
+ auctionClearingPrice: 0,
1021
+ swapValueFactor: 0,
1022
+ dailyValueAdjustmentForLongPositions: 0,
1023
+ cumulativeValueAdjustmentForLongPositions: 0,
1024
+ dailyValueAdjustmentForShortPositions: 0,
1025
+ cumulativeValueAdjustmentForShortPositions: 0,
1026
+ fixingPrice: 0,
1027
+ cashRate: 0,
1028
+ recoveryRate: 0,
1029
+ recoveryRateForLong: 0,
1030
+ recoveryRateForShort: 0,
1031
+ marketBid: 0,
1032
+ marketOffer: 0,
1033
+ shortSaleMinPrice: 0,
1034
+ previousClosingPrice: 0,
1035
+ thresholdLimitPriceBanding: 0,
1036
+ dailyFinancingValue: 0,
1037
+ accruedFinancingValue: 0,
1038
+ twap: 0
1039
+ };
1040
+ for (const entry of entries) {
1041
+ const entryType = entry.MDEntryType;
1042
+ const price = entry.MDEntryPx ? Number.parseFloat(entry.MDEntryPx) : 0;
1043
+ const size = entry.MDEntrySize ? Number.parseFloat(entry.MDEntrySize) : 0;
1044
+ if (entryType === import_fixparser3.MDEntryType.Bid || entryType === import_fixparser3.MDEntryType.Offer || entryType === import_fixparser3.MDEntryType.TradeVolume) {
1045
+ parser.logger.log({
1046
+ level: "info",
1047
+ message: `Market Data Entry - Type: ${entryType}, Price: ${price}, Size: ${size}`
1048
+ });
1049
+ }
1050
+ switch (entryType) {
1051
+ case import_fixparser3.MDEntryType.Bid:
1052
+ data.bid = price;
1053
+ break;
1054
+ case import_fixparser3.MDEntryType.Offer:
1055
+ data.offer = price;
1056
+ break;
1057
+ case import_fixparser3.MDEntryType.Trade:
1058
+ data.trade = price;
1059
+ break;
1060
+ case import_fixparser3.MDEntryType.IndexValue:
1061
+ data.indexValue = price;
1062
+ break;
1063
+ case import_fixparser3.MDEntryType.OpeningPrice:
1064
+ data.openingPrice = price;
1065
+ break;
1066
+ case import_fixparser3.MDEntryType.ClosingPrice:
1067
+ data.closingPrice = price;
1068
+ break;
1069
+ case import_fixparser3.MDEntryType.SettlementPrice:
1070
+ data.settlementPrice = price;
1071
+ break;
1072
+ case import_fixparser3.MDEntryType.TradingSessionHighPrice:
1073
+ data.tradingSessionHighPrice = price;
1074
+ break;
1075
+ case import_fixparser3.MDEntryType.TradingSessionLowPrice:
1076
+ data.tradingSessionLowPrice = price;
1077
+ break;
1078
+ case import_fixparser3.MDEntryType.VWAP:
1079
+ data.vwap = price;
1080
+ break;
1081
+ case import_fixparser3.MDEntryType.Imbalance:
1082
+ data.imbalance = size;
1083
+ break;
1084
+ case import_fixparser3.MDEntryType.TradeVolume:
1085
+ data.volume = size;
1086
+ break;
1087
+ case import_fixparser3.MDEntryType.OpenInterest:
1088
+ data.openInterest = size;
1089
+ break;
1090
+ case import_fixparser3.MDEntryType.CompositeUnderlyingPrice:
1091
+ data.compositeUnderlyingPrice = price;
1092
+ break;
1093
+ case import_fixparser3.MDEntryType.SimulatedSellPrice:
1094
+ data.simulatedSellPrice = price;
1095
+ break;
1096
+ case import_fixparser3.MDEntryType.SimulatedBuyPrice:
1097
+ data.simulatedBuyPrice = price;
1098
+ break;
1099
+ case import_fixparser3.MDEntryType.MarginRate:
1100
+ data.marginRate = price;
1101
+ break;
1102
+ case import_fixparser3.MDEntryType.MidPrice:
1103
+ data.midPrice = price;
1104
+ break;
1105
+ case import_fixparser3.MDEntryType.EmptyBook:
1106
+ data.emptyBook = 1;
1107
+ break;
1108
+ case import_fixparser3.MDEntryType.SettleHighPrice:
1109
+ data.settleHighPrice = price;
1110
+ break;
1111
+ case import_fixparser3.MDEntryType.SettleLowPrice:
1112
+ data.settleLowPrice = price;
1113
+ break;
1114
+ case import_fixparser3.MDEntryType.PriorSettlePrice:
1115
+ data.priorSettlePrice = price;
1116
+ break;
1117
+ case import_fixparser3.MDEntryType.SessionHighBid:
1118
+ data.sessionHighBid = price;
1119
+ break;
1120
+ case import_fixparser3.MDEntryType.SessionLowOffer:
1121
+ data.sessionLowOffer = price;
1122
+ break;
1123
+ case import_fixparser3.MDEntryType.EarlyPrices:
1124
+ data.earlyPrices = price;
1125
+ break;
1126
+ case import_fixparser3.MDEntryType.AuctionClearingPrice:
1127
+ data.auctionClearingPrice = price;
1128
+ break;
1129
+ case import_fixparser3.MDEntryType.SwapValueFactor:
1130
+ data.swapValueFactor = price;
1131
+ break;
1132
+ case import_fixparser3.MDEntryType.DailyValueAdjustmentForLongPositions:
1133
+ data.dailyValueAdjustmentForLongPositions = price;
1134
+ break;
1135
+ case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForLongPositions:
1136
+ data.cumulativeValueAdjustmentForLongPositions = price;
1137
+ break;
1138
+ case import_fixparser3.MDEntryType.DailyValueAdjustmentForShortPositions:
1139
+ data.dailyValueAdjustmentForShortPositions = price;
1140
+ break;
1141
+ case import_fixparser3.MDEntryType.CumulativeValueAdjustmentForShortPositions:
1142
+ data.cumulativeValueAdjustmentForShortPositions = price;
1143
+ break;
1144
+ case import_fixparser3.MDEntryType.FixingPrice:
1145
+ data.fixingPrice = price;
1146
+ break;
1147
+ case import_fixparser3.MDEntryType.CashRate:
1148
+ data.cashRate = price;
1149
+ break;
1150
+ case import_fixparser3.MDEntryType.RecoveryRate:
1151
+ data.recoveryRate = price;
1152
+ break;
1153
+ case import_fixparser3.MDEntryType.RecoveryRateForLong:
1154
+ data.recoveryRateForLong = price;
1155
+ break;
1156
+ case import_fixparser3.MDEntryType.RecoveryRateForShort:
1157
+ data.recoveryRateForShort = price;
1158
+ break;
1159
+ case import_fixparser3.MDEntryType.MarketBid:
1160
+ data.marketBid = price;
1161
+ break;
1162
+ case import_fixparser3.MDEntryType.MarketOffer:
1163
+ data.marketOffer = price;
1164
+ break;
1165
+ case import_fixparser3.MDEntryType.ShortSaleMinPrice:
1166
+ data.shortSaleMinPrice = price;
1167
+ break;
1168
+ case import_fixparser3.MDEntryType.PreviousClosingPrice:
1169
+ data.previousClosingPrice = price;
1170
+ break;
1171
+ case import_fixparser3.MDEntryType.ThresholdLimitPriceBanding:
1172
+ data.thresholdLimitPriceBanding = price;
1173
+ break;
1174
+ case import_fixparser3.MDEntryType.DailyFinancingValue:
1175
+ data.dailyFinancingValue = price;
1176
+ break;
1177
+ case import_fixparser3.MDEntryType.AccruedFinancingValue:
1178
+ data.accruedFinancingValue = price;
1179
+ break;
1180
+ case import_fixparser3.MDEntryType.TWAP:
1181
+ data.twap = price;
1182
+ break;
1183
+ }
1184
+ }
1185
+ data.spread = data.offer - data.bid;
1186
+ if (!marketDataPrices.has(symbol)) {
1187
+ parser.logger.log({
1188
+ level: "info",
1189
+ message: `Creating new price history array for symbol: ${symbol}`
1190
+ });
1191
+ marketDataPrices.set(symbol, []);
1192
+ }
1193
+ const prices = marketDataPrices.get(symbol);
1194
+ prices.push(data);
1195
+ parser.logger.log({
1196
+ level: "info",
1197
+ message: `Updated price history for ${symbol}. Current size: ${prices.length}`
1198
+ });
1199
+ if (prices.length > maxPriceHistory) {
1200
+ prices.splice(0, prices.length - maxPriceHistory);
1201
+ parser.logger.log({
1202
+ level: "info",
1203
+ message: `Trimmed price history for ${symbol} to ${maxPriceHistory} entries`
1204
+ });
1205
+ }
1206
+ onPriceUpdate?.(symbol, data);
1207
+ const mdReqID = message.getField(import_fixparser3.Fields.MDReqID)?.value;
1208
+ if (mdReqID) {
1209
+ const callback = pendingRequests.get(mdReqID);
1210
+ if (callback) {
1211
+ callback(message);
1212
+ pendingRequests.delete(mdReqID);
1213
+ parser.logger.log({
1214
+ level: "info",
1215
+ message: `Resolved market data request for ID: ${mdReqID}`
1216
+ });
1217
+ }
1218
+ }
1219
+ } else if (msgType === import_fixparser3.Messages.ExecutionReport) {
1220
+ const reqId = message.getField(import_fixparser3.Fields.ClOrdID)?.value;
1221
+ const callback = pendingRequests.get(reqId);
1222
+ if (callback) {
1223
+ callback(message);
1224
+ pendingRequests.delete(reqId);
1225
+ }
1226
+ }
1227
+ }
1228
+
1229
+ // src/MCPLocal.ts
1230
+ var MCPLocal = class extends MCPBase {
1231
+ /**
1232
+ * Map to store verified orders before execution
1233
+ * @private
1234
+ */
1235
+ verifiedOrders = /* @__PURE__ */ new Map();
1236
+ /**
1237
+ * Map to store pending requests and their callbacks
1238
+ * @private
1239
+ */
1240
+ pendingRequests = /* @__PURE__ */ new Map();
1241
+ /**
1242
+ * Map to store market data prices for each symbol
1243
+ * @private
1244
+ */
1245
+ marketDataPrices = /* @__PURE__ */ new Map();
1246
+ /**
1247
+ * Maximum number of price history entries to keep per symbol
1248
+ * @private
1249
+ */
1250
+ MAX_PRICE_HISTORY = 1e5;
202
1251
  server = new import_server.Server(
203
1252
  {
204
1253
  name: "fixparser",
@@ -206,41 +1255,27 @@ var MCPLocal = class {
206
1255
  },
207
1256
  {
208
1257
  capabilities: {
209
- tools: {},
210
- prompts: {},
211
- resources: {}
1258
+ tools: Object.entries(toolSchemas).reduce(
1259
+ (acc, [name, { description, schema }]) => {
1260
+ acc[name] = {
1261
+ description,
1262
+ parameters: schema
1263
+ };
1264
+ return acc;
1265
+ },
1266
+ {}
1267
+ )
212
1268
  }
213
1269
  }
214
1270
  );
215
1271
  transport = new import_stdio.StdioServerTransport();
216
- onReady = void 0;
217
- pendingRequests = /* @__PURE__ */ new Map();
218
1272
  constructor({ logger, onReady }) {
219
- if (logger && !logger.silent) {
220
- this.logger = logger;
221
- }
222
- if (onReady) this.onReady = onReady;
1273
+ super({ logger, onReady });
223
1274
  }
224
1275
  async register(parser) {
225
1276
  this.parser = parser;
226
- if (parser.logger && !parser.logger.silent) {
227
- this.logger = parser.logger;
228
- }
229
1277
  this.parser.addOnMessageCallback((message) => {
230
- const msgType = message.messageType;
231
- if (msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh || msgType === import_fixparser.Messages.ExecutionReport) {
232
- const idField = msgType === import_fixparser.Messages.MarketDataSnapshotFullRefresh ? message.getField(import_fixparser.Fields.MDReqID) : message.getField(import_fixparser.Fields.ClOrdID);
233
- if (idField) {
234
- const id = idField.value;
235
- if (typeof id === "string" || typeof id === "number") {
236
- const callback = this.pendingRequests.get(String(id));
237
- if (callback) {
238
- callback(message);
239
- this.pendingRequests.delete(String(id));
240
- }
241
- }
242
- }
243
- }
1278
+ handleMessage(message, this.parser, this.pendingRequests, this.marketDataPrices, this.MAX_PRICE_HISTORY);
244
1279
  });
245
1280
  this.addWorkflows();
246
1281
  await this.server.connect(this.transport);
@@ -250,460 +1285,59 @@ var MCPLocal = class {
250
1285
  }
251
1286
  addWorkflows() {
252
1287
  if (!this.parser) {
253
- this.logger?.log({
254
- level: "error",
255
- message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of workflows..."
256
- });
257
1288
  return;
258
1289
  }
259
1290
  if (!this.server) {
260
- this.logger?.log({
261
- level: "error",
262
- message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of workflows..."
263
- });
264
1291
  return;
265
1292
  }
266
- const validateArgs = (args, schema) => {
267
- const result = {};
268
- for (const [key, propSchema] of Object.entries(schema.properties || {})) {
269
- const prop = propSchema;
270
- const value = args?.[key];
271
- if (prop.required && (value === void 0 || value === null)) {
272
- throw new Error(`Required property '${key}' is missing`);
273
- }
274
- if (value !== void 0) {
275
- result[key] = value;
276
- } else if (prop.default !== void 0) {
277
- result[key] = prop.default;
278
- }
279
- }
280
- return result;
281
- };
282
- this.server.setRequestHandler(import_types.ListResourcesRequestSchema, async () => {
1293
+ this.server.setRequestHandler(import_zod.z.object({ method: import_zod.z.literal("tools/list") }), async () => {
283
1294
  return {
284
- resources: []
1295
+ tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
1296
+ name,
1297
+ description,
1298
+ inputSchema: schema
1299
+ }))
285
1300
  };
286
1301
  });
287
- this.server.setRequestHandler(import_types.ListToolsRequestSchema, async () => {
288
- return {
289
- tools: [
290
- {
291
- name: "parse",
292
- description: "Parses a FIX message and describes it in plain language",
293
- inputSchema: parseInputSchema
294
- },
295
- {
296
- name: "parseToJSON",
297
- description: "Parses a FIX message into JSON",
298
- inputSchema: parseToJSONInputSchema
299
- },
300
- {
301
- name: "newOrderSingle",
302
- description: "Creates and sends a New Order Single",
303
- inputSchema: newOrderSingleInputSchema
304
- },
305
- {
306
- name: "marketDataRequest",
307
- description: "Sends a request for Market Data with the given symbol",
308
- inputSchema: marketDataRequestInputSchema
309
- }
310
- ]
311
- };
312
- });
313
- this.server.setRequestHandler(import_types.CallToolRequestSchema, async (request) => {
314
- const { name, arguments: args } = request.params;
315
- switch (name) {
316
- case "parse": {
317
- try {
318
- const { fixString } = validateArgs(args, parseInputSchema);
319
- const parsedMessage = this.parser?.parse(fixString);
320
- if (!parsedMessage || parsedMessage.length === 0) {
321
- return {
322
- isError: true,
323
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
324
- };
325
- }
326
- return {
327
- content: [
328
- {
329
- type: "text",
330
- text: `${parsedMessage[0].description}
331
- ${parsedMessage[0].messageTypeDescription}`
332
- }
333
- ]
334
- };
335
- } catch (error) {
336
- return {
337
- isError: true,
338
- content: [
339
- {
340
- type: "text",
341
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
342
- }
343
- ]
344
- };
345
- }
346
- }
347
- case "parseToJSON": {
348
- try {
349
- const { fixString } = validateArgs(args, parseToJSONInputSchema);
350
- const parsedMessage = this.parser?.parse(fixString);
351
- if (!parsedMessage || parsedMessage.length === 0) {
352
- return {
353
- isError: true,
354
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
355
- };
356
- }
357
- return {
358
- content: [
359
- {
360
- type: "text",
361
- text: `${parsedMessage[0].toFIXJSON()}`
362
- }
363
- ]
364
- };
365
- } catch (error) {
366
- return {
367
- isError: true,
368
- content: [
369
- {
370
- type: "text",
371
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
372
- }
373
- ]
374
- };
375
- }
376
- }
377
- case "newOrderSingle": {
378
- try {
379
- const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = validateArgs(args, newOrderSingleInputSchema);
380
- const response = new Promise((resolve) => {
381
- this.pendingRequests.set(clOrdID, resolve);
382
- });
383
- const order = this.parser?.createMessage(
384
- new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.NewOrderSingle),
385
- new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
386
- new import_fixparser.Field(import_fixparser.Fields.SenderCompID, this.parser?.sender),
387
- new import_fixparser.Field(import_fixparser.Fields.TargetCompID, this.parser?.target),
388
- new import_fixparser.Field(import_fixparser.Fields.SendingTime, this.parser?.getTimestamp()),
389
- new import_fixparser.Field(import_fixparser.Fields.ClOrdID, clOrdID),
390
- new import_fixparser.Field(import_fixparser.Fields.Side, side),
391
- new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol),
392
- new import_fixparser.Field(import_fixparser.Fields.OrderQty, quantity),
393
- new import_fixparser.Field(import_fixparser.Fields.Price, price),
394
- new import_fixparser.Field(import_fixparser.Fields.OrdType, ordType),
395
- new import_fixparser.Field(import_fixparser.Fields.HandlInst, handlInst),
396
- new import_fixparser.Field(import_fixparser.Fields.TimeInForce, timeInForce),
397
- new import_fixparser.Field(import_fixparser.Fields.TransactTime, this.parser?.getTimestamp())
398
- );
399
- if (!this.parser?.connected) {
400
- this.logger?.log({
401
- level: "error",
402
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
403
- });
404
- return {
405
- isError: true,
406
- content: [
407
- {
408
- type: "text",
409
- text: "Error: Not connected. Ignoring message."
410
- }
411
- ]
412
- };
413
- }
414
- this.parser?.send(order);
415
- this.logger?.log({
416
- level: "info",
417
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${order?.description}`
418
- });
419
- const fixData = await response;
420
- return {
421
- content: [
422
- {
423
- type: "text",
424
- text: `Execution Report for order ${clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`
425
- }
426
- ]
427
- };
428
- } catch (error) {
429
- return {
430
- isError: true,
431
- content: [
432
- {
433
- type: "text",
434
- text: `Error: ${error instanceof Error ? error.message : "Failed to create order"}`
435
- }
436
- ]
437
- };
438
- }
439
- }
440
- case "marketDataRequest": {
441
- try {
442
- const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = validateArgs(
443
- args,
444
- marketDataRequestInputSchema
445
- );
446
- const response = new Promise((resolve) => {
447
- this.pendingRequests.set(mdReqID, resolve);
448
- });
449
- const marketDataRequest = this.parser?.createMessage(
450
- new import_fixparser.Field(import_fixparser.Fields.MsgType, import_fixparser.Messages.MarketDataRequest),
451
- new import_fixparser.Field(import_fixparser.Fields.SenderCompID, this.parser?.sender),
452
- new import_fixparser.Field(import_fixparser.Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
453
- new import_fixparser.Field(import_fixparser.Fields.TargetCompID, this.parser?.target),
454
- new import_fixparser.Field(import_fixparser.Fields.SendingTime, this.parser?.getTimestamp()),
455
- new import_fixparser.Field(import_fixparser.Fields.MarketDepth, 0),
456
- new import_fixparser.Field(import_fixparser.Fields.MDUpdateType, mdUpdateType),
457
- new import_fixparser.Field(import_fixparser.Fields.NoRelatedSym, 1),
458
- new import_fixparser.Field(import_fixparser.Fields.Symbol, symbol),
459
- new import_fixparser.Field(import_fixparser.Fields.MDReqID, mdReqID),
460
- new import_fixparser.Field(import_fixparser.Fields.SubscriptionRequestType, subscriptionRequestType),
461
- new import_fixparser.Field(import_fixparser.Fields.NoMDEntryTypes, 1),
462
- new import_fixparser.Field(import_fixparser.Fields.MDEntryType, mdEntryType)
463
- );
464
- if (!this.parser?.connected) {
465
- this.logger?.log({
466
- level: "error",
467
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
468
- });
469
- return {
470
- isError: true,
471
- content: [
472
- {
473
- type: "text",
474
- text: "Error: Not connected. Ignoring message."
475
- }
476
- ]
477
- };
478
- }
479
- this.parser?.send(marketDataRequest);
480
- this.logger?.log({
481
- level: "info",
482
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${marketDataRequest?.description}`
483
- });
484
- const fixData = await response;
485
- return {
486
- content: [
487
- {
488
- type: "text",
489
- text: `Market data for ${symbol}: ${JSON.stringify(fixData.toFIXJSON())}`
490
- }
491
- ]
492
- };
493
- } catch (error) {
494
- return {
495
- isError: true,
496
- content: [
497
- {
498
- type: "text",
499
- text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`
500
- }
501
- ]
502
- };
503
- }
504
- }
505
- default:
506
- throw new Error(`Unknown tool: ${name}`);
507
- }
508
- });
509
- this.server.setRequestHandler(import_types.ListPromptsRequestSchema, async () => {
510
- return {
511
- prompts: [
512
- {
513
- name: "parse",
514
- description: "Parses a FIX message and describes it in plain language",
515
- arguments: [
516
- {
517
- name: "fixString",
518
- description: "FIX message string to parse",
519
- required: true
520
- }
521
- ]
522
- },
523
- {
524
- name: "parseToJSON",
525
- description: "Parses a FIX message into JSON",
526
- arguments: [
527
- {
528
- name: "fixString",
529
- description: "FIX message string to parse",
530
- required: true
531
- }
532
- ]
533
- },
534
- {
535
- name: "newOrderSingle",
536
- description: "Creates and sends a New Order Single",
537
- arguments: [
538
- {
539
- name: "clOrdID",
540
- description: "Client Order ID",
541
- required: true
542
- },
543
- {
544
- name: "handlInst",
545
- description: "Handling instruction",
546
- required: false
547
- },
548
- {
549
- name: "quantity",
550
- description: "Order quantity",
551
- required: true
552
- },
553
- {
554
- name: "price",
555
- description: "Order price",
556
- required: true
557
- },
558
- {
559
- name: "ordType",
560
- description: "Order type",
561
- required: false
562
- },
563
- {
564
- name: "side",
565
- description: "Order 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)",
566
- required: true
567
- },
568
- {
569
- name: "symbol",
570
- description: "Trading symbol",
571
- required: true
572
- },
573
- {
574
- name: "timeInForce",
575
- description: "Time in force",
576
- required: false
577
- }
578
- ]
579
- },
580
- {
581
- name: "marketDataRequest",
582
- description: "Sends a request for Market Data with the given symbol",
583
- arguments: [
584
- {
585
- name: "mdUpdateType",
586
- description: "Market data update type",
587
- required: false
588
- },
589
- {
590
- name: "symbol",
591
- description: "Trading symbol",
592
- required: true
593
- },
594
- {
595
- name: "mdReqID",
596
- description: "Market data request ID",
597
- required: true
598
- },
599
- {
600
- name: "subscriptionRequestType",
601
- description: "Subscription request type",
602
- required: false
603
- },
604
- {
605
- name: "mdEntryType",
606
- description: "Market data entry type",
607
- required: false
608
- }
609
- ]
610
- }
611
- ]
612
- };
613
- });
614
- this.server.setRequestHandler(import_types.GetPromptRequestSchema, async (request) => {
615
- const { name, arguments: args } = request.params;
616
- switch (name) {
617
- case "parse": {
618
- const fixString = args?.fixString || "";
619
- return {
620
- messages: [
621
- {
622
- role: "user",
623
- content: {
624
- type: "text",
625
- text: `Please parse and explain this FIX message: ${fixString}`
626
- }
627
- }
628
- ]
629
- };
630
- }
631
- case "parseToJSON": {
632
- const fixString = args?.fixString || "";
633
- return {
634
- messages: [
635
- {
636
- role: "user",
637
- content: {
638
- type: "text",
639
- text: `Please parse the FIX message to JSON: ${fixString}`
640
- }
641
- }
642
- ]
643
- };
644
- }
645
- case "newOrderSingle": {
646
- const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = args || {};
1302
+ this.server.setRequestHandler(
1303
+ import_zod.z.object({
1304
+ method: import_zod.z.literal("tools/call"),
1305
+ params: import_zod.z.object({
1306
+ name: import_zod.z.string(),
1307
+ arguments: import_zod.z.any(),
1308
+ _meta: import_zod.z.object({
1309
+ progressToken: import_zod.z.number()
1310
+ }).optional()
1311
+ })
1312
+ }),
1313
+ async (request) => {
1314
+ const { name, arguments: args } = request.params;
1315
+ const toolHandlers = createToolHandlers(
1316
+ this.parser,
1317
+ this.verifiedOrders,
1318
+ this.pendingRequests,
1319
+ this.marketDataPrices
1320
+ );
1321
+ const handler = toolHandlers[name];
1322
+ if (!handler) {
647
1323
  return {
648
- messages: [
1324
+ content: [
649
1325
  {
650
- role: "user",
651
- content: {
652
- type: "text",
653
- text: [
654
- "Create a New Order Single FIX message with the following parameters:",
655
- `- ClOrdID: ${clOrdID}`,
656
- `- HandlInst: ${handlInst ?? "3"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '1' for Manual, '2' for Automated, '3' for AutomatedNoIntervention)`,
657
- `- Quantity: ${quantity}`,
658
- `- Price: ${price}`,
659
- `- OrdType: ${ordType ?? "1"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '1' for Market, '2' for Limit, '3' for Stop)`,
660
- `- Side: ${side} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '1' for Buy, '2' for Sell)`,
661
- `- Symbol: ${symbol}`,
662
- `- TimeInForce: ${timeInForce ?? "0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for Day, '1' for Good Till Cancel, '2' for At Opening, '3' for Immediate or Cancel, '4' for Fill or Kill, '5' for Good Till Crossing, '6' for Good Till Date)`,
663
- "",
664
- "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values.",
665
- "",
666
- 'Note: For the Side parameter, always use the numeric/alphabetic value (e.g., "1" for Buy, "2" for Sell) as defined in the FIX protocol, not the descriptive name.',
667
- 'Note: For the HandlInst parameter, always use the numeric/alphabetic value (e.g., "1" for Manual, "2" for Automated, "3" for AutomatedNoIntervention) as defined in the FIX protocol, not the descriptive name.',
668
- 'Note: For the OrdType parameter, always use the numeric/alphabetic value (e.g., "1" for Market, "2" for Limit, "3" for Stop) as defined in the FIX protocol, not the descriptive name.',
669
- 'Note: For the TimeInForce parameter, always use the numeric/alphabetic value (e.g., "0" for Day, "1" for Good Till Cancel, "2" for At Opening) as defined in the FIX protocol, not the descriptive name.'
670
- ].join("\n")
671
- }
1326
+ type: "text",
1327
+ text: `Tool not found: ${name}`,
1328
+ uri: name
672
1329
  }
673
- ]
1330
+ ],
1331
+ isError: true
674
1332
  };
675
1333
  }
676
- case "marketDataRequest": {
677
- const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = args || {};
678
- return {
679
- messages: [
680
- {
681
- role: "user",
682
- content: {
683
- type: "text",
684
- text: [
685
- "Create a Market Data Request FIX message with the following parameters:",
686
- `- MDUpdateType: ${mdUpdateType ?? "0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for FullRefresh, '1' for IncrementalRefresh)`,
687
- `- Symbol: ${symbol}`,
688
- `- MDReqID: ${mdReqID}`,
689
- `- SubscriptionRequestType: ${subscriptionRequestType ?? "0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for Snapshot + Updates, '1' for Snapshot, '2' for Unsubscribe)`,
690
- `- MDEntryType: ${mdEntryType ?? "0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for Bid, '1' for Offer, '2' for Trade, '3' for Index Value, '4' for Opening Price)`,
691
- "",
692
- "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values.",
693
- "",
694
- 'Note: For the MDUpdateType parameter, always use the numeric/alphabetic value (e.g., "0" for FullRefresh, "1" for IncrementalRefresh) as defined in the FIX protocol, not the descriptive name.',
695
- 'Note: For the SubscriptionRequestType parameter, always use the numeric/alphabetic value (e.g., "0" for Snapshot + Updates, "1" for Snapshot, "2" for Unsubscribe) as defined in the FIX protocol, not the descriptive name.',
696
- 'Note: For the MDEntryType parameter, always use the numeric/alphabetic value (e.g., "0" for Bid, "1" for Offer, "2" for Trade, "3" for Index Value, "4" for Opening Price) as defined in the FIX protocol, not the descriptive name.'
697
- ].join("\n")
698
- }
699
- }
700
- ]
701
- };
702
- }
703
- default:
704
- throw new Error(`Unknown prompt: ${name}`);
1334
+ const result = await handler(args);
1335
+ return {
1336
+ content: result.content,
1337
+ isError: result.isError
1338
+ };
705
1339
  }
706
- });
1340
+ );
707
1341
  process.on("SIGINT", async () => {
708
1342
  await this.server.close();
709
1343
  process.exit(0);