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