fixparser-plugin-mcp 9.1.7-bfcb9d6f → 9.1.7-c415bb75

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