fixparser-plugin-mcp 9.1.7-89ae1451 → 9.1.7-8efb79c3

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