fixparser-plugin-mcp 9.1.7-edd3725d → 9.1.7-eea80766

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,194 +1,773 @@
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 {
5
- CallToolRequestSchema,
6
- GetPromptRequestSchema,
7
- ListPromptsRequestSchema,
8
- ListResourcesRequestSchema,
9
- ListToolsRequestSchema
10
- } from "@modelcontextprotocol/sdk/types.js";
11
- import {
12
- Field,
13
- Fields,
14
- HandlInst,
15
- MDEntryType,
16
- Messages,
17
- OrdType,
18
- SubscriptionRequestType,
19
- TimeInForce
20
- } from "fixparser";
21
- var parseInputSchema = {
22
- type: "object",
23
- properties: {
24
- fixString: {
25
- type: "string",
26
- description: "FIX message string to parse"
4
+ import { Fields as Fields3, MDEntryType as MDEntryType2, Messages as Messages3 } from "fixparser";
5
+ import { z } from "zod";
6
+
7
+ // src/schemas/schemas.ts
8
+ var toolSchemas = {
9
+ parse: {
10
+ description: "Parses a FIX message and describes it in plain language",
11
+ schema: {
12
+ type: "object",
13
+ properties: {
14
+ fixString: { type: "string" }
15
+ },
16
+ required: ["fixString"]
27
17
  }
28
18
  },
29
- required: ["fixString"]
30
- };
31
- var parseToJSONInputSchema = {
32
- type: "object",
33
- properties: {
34
- fixString: {
35
- type: "string",
36
- description: "FIX message string to parse"
19
+ parseToJSON: {
20
+ description: "Parses a FIX message into JSON",
21
+ schema: {
22
+ type: "object",
23
+ properties: {
24
+ fixString: { type: "string" }
25
+ },
26
+ required: ["fixString"]
37
27
  }
38
28
  },
39
- required: ["fixString"]
40
- };
41
- var newOrderSingleInputSchema = {
42
- type: "object",
43
- properties: {
44
- clOrdID: {
45
- type: "string",
46
- description: "Client Order ID"
47
- },
48
- handlInst: {
49
- type: "string",
50
- enum: ["1", "2", "3"],
51
- default: HandlInst.AutomatedExecutionNoIntervention,
52
- description: 'Handling instruction (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "1" for Manual, "2" for Automated, "3" for AutomatedNoIntervention)'
53
- },
54
- quantity: {
55
- type: "number",
56
- description: "Order quantity"
57
- },
58
- price: {
59
- type: "number",
60
- description: "Order price"
61
- },
62
- ordType: {
63
- type: "string",
64
- enum: [
65
- "1",
66
- "2",
67
- "3",
68
- "4",
69
- "5",
70
- "6",
71
- "7",
72
- "8",
73
- "9",
74
- "A",
75
- "B",
76
- "C",
77
- "D",
78
- "E",
79
- "F",
80
- "G",
81
- "H",
82
- "I",
83
- "J",
84
- "K",
85
- "L",
86
- "M",
87
- "P",
88
- "Q",
89
- "R",
90
- "S"
91
- ],
92
- default: OrdType.Market,
93
- description: 'Order type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "1" for Market, "2" for Limit, "3" for Stop)'
94
- },
95
- side: {
96
- type: "string",
97
- enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
98
- description: 'Order side (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "1" for Buy, "2" for Sell, "3" for BuyMinus, "4" for SellPlus, "5" for SellShort, "6" for SellShortExempt, "7" for Undisclosed, "8" for Cross, "9" for CrossShort, "A" for CrossShortExempt, "B" for AsDefined, "C" for Opposite, "D" for Subscribe, "E" for Redeem, "F" for Lend, "G" for Borrow, "H" for SellUndisclosed)'
99
- },
100
- symbol: {
101
- type: "string",
102
- description: "Trading symbol"
103
- },
104
- timeInForce: {
105
- type: "string",
106
- enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
107
- default: TimeInForce.Day,
108
- description: 'Time in force (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Day, "1" for Good Till Cancel, "2" for At Opening, "3" for Immediate or Cancel, "4" for Fill or Kill, "5" for Good Till Crossing, "6" for Good Till Date)'
29
+ verifyOrder: {
30
+ description: "Verifies order parameters before execution. verifyOrder must be called before executeOrder.",
31
+ schema: {
32
+ type: "object",
33
+ properties: {
34
+ clOrdID: { type: "string" },
35
+ handlInst: {
36
+ type: "string",
37
+ enum: ["1", "2", "3"],
38
+ description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
39
+ },
40
+ quantity: { type: "string" },
41
+ price: { type: "string" },
42
+ ordType: {
43
+ type: "string",
44
+ enum: [
45
+ "1",
46
+ "2",
47
+ "3",
48
+ "4",
49
+ "5",
50
+ "6",
51
+ "7",
52
+ "8",
53
+ "9",
54
+ "A",
55
+ "B",
56
+ "C",
57
+ "D",
58
+ "E",
59
+ "F",
60
+ "G",
61
+ "H",
62
+ "I",
63
+ "J",
64
+ "K",
65
+ "L",
66
+ "M",
67
+ "P",
68
+ "Q",
69
+ "R",
70
+ "S"
71
+ ],
72
+ 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"
73
+ },
74
+ side: {
75
+ type: "string",
76
+ enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
77
+ 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"
78
+ },
79
+ symbol: { type: "string" },
80
+ timeInForce: {
81
+ type: "string",
82
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
83
+ 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"
84
+ }
85
+ },
86
+ required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
109
87
  }
110
88
  },
111
- required: ["clOrdID", "quantity", "price", "side", "symbol"]
112
- };
113
- var marketDataRequestInputSchema = {
114
- type: "object",
115
- properties: {
116
- mdUpdateType: {
117
- type: "string",
118
- enum: ["0", "1"],
119
- default: "0",
120
- description: 'Market data update type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for FullRefresh, "1" for IncrementalRefresh)'
121
- },
122
- symbol: {
123
- type: "string",
124
- description: "Trading symbol"
125
- },
126
- mdReqID: {
127
- type: "string",
128
- description: "Market data request ID"
129
- },
130
- subscriptionRequestType: {
131
- type: "string",
132
- enum: ["0", "1", "2"],
133
- default: SubscriptionRequestType.SnapshotAndUpdates,
134
- description: 'Subscription request type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Snapshot + Updates, "1" for Snapshot, "2" for Unsubscribe)'
135
- },
136
- mdEntryType: {
137
- type: "string",
138
- enum: [
139
- "0",
140
- "1",
141
- "2",
142
- "3",
143
- "4",
144
- "5",
145
- "6",
146
- "7",
147
- "8",
148
- "9",
149
- "A",
150
- "B",
151
- "C",
152
- "D",
153
- "E",
154
- "F",
155
- "G",
156
- "H",
157
- "J",
158
- "K",
159
- "L",
160
- "M",
161
- "N",
162
- "O",
163
- "P",
164
- "Q",
165
- "S",
166
- "R",
167
- "T",
168
- "U",
169
- "V",
170
- "W",
171
- "X",
172
- "Y",
173
- "Z",
174
- "a",
175
- "b",
176
- "c",
177
- "d",
178
- "e",
179
- "g",
180
- "h",
181
- "i",
182
- "t"
183
- ],
184
- default: MDEntryType.Bid,
185
- description: 'Market data entry type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Bid, "1" for Offer, "2" for Trade, "3" for Index Value, "4" for Opening Price)'
89
+ executeOrder: {
90
+ description: "Executes a verified order. verifyOrder must be called before executeOrder. user has to explicitly allow executeOrder.",
91
+ schema: {
92
+ type: "object",
93
+ properties: {
94
+ clOrdID: { type: "string" },
95
+ handlInst: {
96
+ type: "string",
97
+ enum: ["1", "2", "3"],
98
+ description: "Handling Instructions: 1=Automated Execution No Intervention, 2=Automated Execution Intervention OK, 3=Manual Order"
99
+ },
100
+ quantity: { type: "string" },
101
+ price: { type: "string" },
102
+ ordType: {
103
+ type: "string",
104
+ enum: [
105
+ "1",
106
+ "2",
107
+ "3",
108
+ "4",
109
+ "5",
110
+ "6",
111
+ "7",
112
+ "8",
113
+ "9",
114
+ "A",
115
+ "B",
116
+ "C",
117
+ "D",
118
+ "E",
119
+ "F",
120
+ "G",
121
+ "H",
122
+ "I",
123
+ "J",
124
+ "K",
125
+ "L",
126
+ "M",
127
+ "P",
128
+ "Q",
129
+ "R",
130
+ "S"
131
+ ],
132
+ 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"
133
+ },
134
+ side: {
135
+ type: "string",
136
+ enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
137
+ 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"
138
+ },
139
+ symbol: { type: "string" },
140
+ timeInForce: {
141
+ type: "string",
142
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
143
+ 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"
144
+ }
145
+ },
146
+ required: ["clOrdID", "handlInst", "quantity", "price", "ordType", "side", "symbol", "timeInForce"]
186
147
  }
187
148
  },
188
- required: ["symbol", "mdReqID"]
149
+ marketDataRequest: {
150
+ description: "Requests market data for specified symbols",
151
+ schema: {
152
+ type: "object",
153
+ properties: {
154
+ mdUpdateType: {
155
+ type: "string",
156
+ enum: ["0", "1"],
157
+ description: "Market Data Update Type: 0=Full Refresh, 1=Incremental Refresh"
158
+ },
159
+ symbols: { type: "array", items: { type: "string" } },
160
+ mdReqID: { type: "string" },
161
+ subscriptionRequestType: {
162
+ type: "string",
163
+ enum: ["0", "1", "2"],
164
+ description: "Subscription Request Type: 0=Snapshot, 1=Snapshot + Updates, 2=Disable Previous Snapshot + Update Request"
165
+ },
166
+ mdEntryTypes: {
167
+ type: "array",
168
+ items: {
169
+ type: "string",
170
+ enum: [
171
+ "0",
172
+ "1",
173
+ "2",
174
+ "3",
175
+ "4",
176
+ "5",
177
+ "6",
178
+ "7",
179
+ "8",
180
+ "9",
181
+ "A",
182
+ "B",
183
+ "C",
184
+ "D",
185
+ "E",
186
+ "F",
187
+ "G",
188
+ "H",
189
+ "I",
190
+ "J",
191
+ "K",
192
+ "L",
193
+ "M",
194
+ "N",
195
+ "O",
196
+ "P",
197
+ "Q",
198
+ "R",
199
+ "S",
200
+ "T",
201
+ "U",
202
+ "V",
203
+ "W",
204
+ "X",
205
+ "Y",
206
+ "Z"
207
+ ]
208
+ },
209
+ 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"
210
+ }
211
+ },
212
+ required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType"]
213
+ }
214
+ },
215
+ getStockGraph: {
216
+ description: "Generates a price chart for a given symbol",
217
+ schema: {
218
+ type: "object",
219
+ properties: {
220
+ symbol: { type: "string" }
221
+ },
222
+ required: ["symbol"]
223
+ }
224
+ },
225
+ getStockPriceHistory: {
226
+ description: "Returns price history for a given symbol",
227
+ schema: {
228
+ type: "object",
229
+ properties: {
230
+ symbol: { type: "string" }
231
+ },
232
+ required: ["symbol"]
233
+ }
234
+ }
235
+ };
236
+
237
+ // src/tools/marketData.ts
238
+ import { Field, Fields, MDEntryType, Messages } from "fixparser";
239
+ import QuickChart from "quickchart-js";
240
+ var createMarketDataRequestHandler = (parser, pendingRequests) => {
241
+ return async (args) => {
242
+ try {
243
+ const response = new Promise((resolve) => {
244
+ pendingRequests.set(args.mdReqID, resolve);
245
+ });
246
+ const entryTypes = args.mdEntryTypes || [MDEntryType.Bid, MDEntryType.Offer, MDEntryType.TradeVolume];
247
+ const messageFields = [
248
+ new Field(Fields.MsgType, Messages.MarketDataRequest),
249
+ new Field(Fields.SenderCompID, parser.sender),
250
+ new Field(Fields.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
251
+ new Field(Fields.TargetCompID, parser.target),
252
+ new Field(Fields.SendingTime, parser.getTimestamp()),
253
+ new Field(Fields.MDReqID, args.mdReqID),
254
+ new Field(Fields.SubscriptionRequestType, args.subscriptionRequestType),
255
+ new Field(Fields.MarketDepth, 0),
256
+ new Field(Fields.MDUpdateType, args.mdUpdateType)
257
+ ];
258
+ messageFields.push(new Field(Fields.NoRelatedSym, args.symbols.length));
259
+ args.symbols.forEach((symbol) => {
260
+ messageFields.push(new Field(Fields.Symbol, symbol));
261
+ });
262
+ messageFields.push(new Field(Fields.NoMDEntryTypes, entryTypes.length));
263
+ entryTypes.forEach((entryType) => {
264
+ messageFields.push(new Field(Fields.MDEntryType, entryType));
265
+ });
266
+ const mdr = parser.createMessage(...messageFields);
267
+ if (!parser.connected) {
268
+ return {
269
+ content: [
270
+ {
271
+ type: "text",
272
+ text: "Error: Not connected. Ignoring message.",
273
+ uri: "marketDataRequest"
274
+ }
275
+ ],
276
+ isError: true
277
+ };
278
+ }
279
+ parser.send(mdr);
280
+ const fixData = await response;
281
+ return {
282
+ content: [
283
+ {
284
+ type: "text",
285
+ text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
286
+ uri: "marketDataRequest"
287
+ }
288
+ ]
289
+ };
290
+ } catch (error) {
291
+ return {
292
+ content: [
293
+ {
294
+ type: "text",
295
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
296
+ uri: "marketDataRequest"
297
+ }
298
+ ],
299
+ isError: true
300
+ };
301
+ }
302
+ };
303
+ };
304
+ var createGetStockGraphHandler = (marketDataPrices) => {
305
+ return async (args) => {
306
+ try {
307
+ const symbol = args.symbol;
308
+ const priceHistory = marketDataPrices.get(symbol) || [];
309
+ if (priceHistory.length === 0) {
310
+ return {
311
+ content: [
312
+ {
313
+ type: "text",
314
+ text: `No price data available for ${symbol}`,
315
+ uri: "getStockGraph"
316
+ }
317
+ ]
318
+ };
319
+ }
320
+ const chart = new QuickChart();
321
+ chart.setWidth(600);
322
+ chart.setHeight(300);
323
+ const labels = priceHistory.map((point) => new Date(point.timestamp).toLocaleTimeString());
324
+ const bidData = priceHistory.map((point) => point.bid);
325
+ const offerData = priceHistory.map((point) => point.offer);
326
+ const spreadData = priceHistory.map((point) => point.spread);
327
+ const volumeData = priceHistory.map((point) => point.volume);
328
+ const config = {
329
+ type: "line",
330
+ data: {
331
+ labels,
332
+ datasets: [
333
+ {
334
+ label: "Bid",
335
+ data: bidData,
336
+ borderColor: "#28a745",
337
+ backgroundColor: "rgba(40, 167, 69, 0.1)",
338
+ fill: false,
339
+ tension: 0.4
340
+ },
341
+ {
342
+ label: "Offer",
343
+ data: offerData,
344
+ borderColor: "#dc3545",
345
+ backgroundColor: "rgba(220, 53, 69, 0.1)",
346
+ fill: false,
347
+ tension: 0.4
348
+ },
349
+ {
350
+ label: "Spread",
351
+ data: spreadData,
352
+ borderColor: "#6c757d",
353
+ backgroundColor: "rgba(108, 117, 125, 0.1)",
354
+ fill: false,
355
+ tension: 0.4
356
+ },
357
+ {
358
+ label: "Volume",
359
+ data: volumeData,
360
+ borderColor: "#007bff",
361
+ backgroundColor: "rgba(0, 123, 255, 0.1)",
362
+ fill: true,
363
+ tension: 0.4
364
+ }
365
+ ]
366
+ },
367
+ options: {
368
+ responsive: true,
369
+ plugins: {
370
+ title: {
371
+ display: true,
372
+ text: `${symbol} Market Data`
373
+ }
374
+ },
375
+ scales: {
376
+ y: {
377
+ beginAtZero: false
378
+ }
379
+ }
380
+ }
381
+ };
382
+ chart.setConfig(config);
383
+ const imageBuffer = await chart.toBinary();
384
+ const base64Image = imageBuffer.toString("base64");
385
+ return {
386
+ content: [
387
+ {
388
+ type: "image",
389
+ data: base64Image,
390
+ mimeType: "image/png"
391
+ }
392
+ // {
393
+ // type: 'image',
394
+ // image: {
395
+ // source: {
396
+ // filename: 'graph.png',
397
+ // data: `data:image/png;base64,${base64Image}`,
398
+ // },
399
+ // },
400
+ // mimeType: 'image/png',
401
+ // },
402
+ ]
403
+ };
404
+ } catch (error) {
405
+ return {
406
+ content: [
407
+ {
408
+ type: "text",
409
+ text: `Error: ${error instanceof Error ? error.message : "Failed to generate chart"}`,
410
+ uri: "getStockGraph"
411
+ }
412
+ ],
413
+ isError: true
414
+ };
415
+ }
416
+ };
417
+ };
418
+ var createGetStockPriceHistoryHandler = (marketDataPrices) => {
419
+ return async (args) => {
420
+ try {
421
+ const symbol = args.symbol;
422
+ const priceHistory = marketDataPrices.get(symbol) || [];
423
+ if (priceHistory.length === 0) {
424
+ return {
425
+ content: [
426
+ {
427
+ type: "text",
428
+ text: `No price data available for ${symbol}`,
429
+ uri: "getStockPriceHistory"
430
+ }
431
+ ]
432
+ };
433
+ }
434
+ return {
435
+ content: [
436
+ {
437
+ type: "text",
438
+ text: JSON.stringify(
439
+ {
440
+ symbol,
441
+ count: priceHistory.length,
442
+ data: priceHistory.map((point) => ({
443
+ timestamp: new Date(point.timestamp).toISOString(),
444
+ bid: point.bid,
445
+ offer: point.offer,
446
+ spread: point.spread,
447
+ volume: point.volume
448
+ }))
449
+ },
450
+ null,
451
+ 2
452
+ ),
453
+ uri: "getStockPriceHistory"
454
+ }
455
+ ]
456
+ };
457
+ } catch (error) {
458
+ return {
459
+ content: [
460
+ {
461
+ type: "text",
462
+ text: `Error: ${error instanceof Error ? error.message : "Failed to get stock price history"}`,
463
+ uri: "getStockPriceHistory"
464
+ }
465
+ ],
466
+ isError: true
467
+ };
468
+ }
469
+ };
470
+ };
471
+
472
+ // src/tools/order.ts
473
+ import { Field as Field2, Fields as Fields2, Messages as Messages2 } from "fixparser";
474
+ var ordTypeNames = {
475
+ "1": "Market",
476
+ "2": "Limit",
477
+ "3": "Stop",
478
+ "4": "StopLimit",
479
+ "5": "MarketOnClose",
480
+ "6": "WithOrWithout",
481
+ "7": "LimitOrBetter",
482
+ "8": "LimitWithOrWithout",
483
+ "9": "OnBasis",
484
+ A: "OnClose",
485
+ B: "LimitOnClose",
486
+ C: "ForexMarket",
487
+ D: "PreviouslyQuoted",
488
+ E: "PreviouslyIndicated",
489
+ F: "ForexLimit",
490
+ G: "ForexSwap",
491
+ H: "ForexPreviouslyQuoted",
492
+ I: "Funari",
493
+ J: "MarketIfTouched",
494
+ K: "MarketWithLeftOverAsLimit",
495
+ L: "PreviousFundValuationPoint",
496
+ M: "NextFundValuationPoint",
497
+ P: "Pegged",
498
+ Q: "CounterOrderSelection",
499
+ R: "StopOnBidOrOffer",
500
+ S: "StopLimitOnBidOrOffer"
501
+ };
502
+ var sideNames = {
503
+ "1": "Buy",
504
+ "2": "Sell",
505
+ "3": "BuyMinus",
506
+ "4": "SellPlus",
507
+ "5": "SellShort",
508
+ "6": "SellShortExempt",
509
+ "7": "Undisclosed",
510
+ "8": "Cross",
511
+ "9": "CrossShort",
512
+ A: "CrossShortExempt",
513
+ B: "AsDefined",
514
+ C: "Opposite",
515
+ D: "Subscribe",
516
+ E: "Redeem",
517
+ F: "Lend",
518
+ G: "Borrow",
519
+ H: "SellUndisclosed"
520
+ };
521
+ var timeInForceNames = {
522
+ "0": "Day",
523
+ "1": "GoodTillCancel",
524
+ "2": "AtTheOpening",
525
+ "3": "ImmediateOrCancel",
526
+ "4": "FillOrKill",
527
+ "5": "GoodTillCrossing",
528
+ "6": "GoodTillDate",
529
+ "7": "AtTheClose",
530
+ "8": "GoodThroughCrossing",
531
+ "9": "AtCrossing",
532
+ A: "GoodForTime",
533
+ B: "GoodForAuction",
534
+ C: "GoodForMonth"
535
+ };
536
+ var handlInstNames = {
537
+ "1": "AutomatedExecutionNoIntervention",
538
+ "2": "AutomatedExecutionInterventionOK",
539
+ "3": "ManualOrder"
540
+ };
541
+ var createVerifyOrderHandler = (parser, verifiedOrders) => {
542
+ return async (args) => {
543
+ try {
544
+ verifiedOrders.set(args.clOrdID, {
545
+ clOrdID: args.clOrdID,
546
+ handlInst: args.handlInst,
547
+ quantity: Number.parseFloat(String(args.quantity)),
548
+ price: Number.parseFloat(String(args.price)),
549
+ ordType: args.ordType,
550
+ side: args.side,
551
+ symbol: args.symbol,
552
+ timeInForce: args.timeInForce
553
+ });
554
+ return {
555
+ content: [
556
+ {
557
+ type: "text",
558
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
559
+
560
+ Parameters verified:
561
+ - ClOrdID: ${args.clOrdID}
562
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
563
+ - Quantity: ${args.quantity}
564
+ - Price: ${args.price}
565
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
566
+ - Side: ${args.side} (${sideNames[args.side]})
567
+ - Symbol: ${args.symbol}
568
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
569
+
570
+ To execute this order, call the executeOrder tool with these exact same parameters.`,
571
+ uri: "verifyOrder"
572
+ }
573
+ ]
574
+ };
575
+ } catch (error) {
576
+ return {
577
+ content: [
578
+ {
579
+ type: "text",
580
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
581
+ uri: "verifyOrder"
582
+ }
583
+ ],
584
+ isError: true
585
+ };
586
+ }
587
+ };
588
+ };
589
+ var createExecuteOrderHandler = (parser, verifiedOrders, pendingRequests) => {
590
+ return async (args) => {
591
+ try {
592
+ const verifiedOrder = verifiedOrders.get(args.clOrdID);
593
+ if (!verifiedOrder) {
594
+ return {
595
+ content: [
596
+ {
597
+ type: "text",
598
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
599
+ uri: "executeOrder"
600
+ }
601
+ ],
602
+ isError: true
603
+ };
604
+ }
605
+ 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) {
606
+ return {
607
+ content: [
608
+ {
609
+ type: "text",
610
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
611
+ uri: "executeOrder"
612
+ }
613
+ ],
614
+ isError: true
615
+ };
616
+ }
617
+ const response = new Promise((resolve) => {
618
+ pendingRequests.set(args.clOrdID, resolve);
619
+ });
620
+ const order = parser.createMessage(
621
+ new Field2(Fields2.MsgType, Messages2.NewOrderSingle),
622
+ new Field2(Fields2.MsgSeqNum, parser.getNextTargetMsgSeqNum()),
623
+ new Field2(Fields2.SenderCompID, parser.sender),
624
+ new Field2(Fields2.TargetCompID, parser.target),
625
+ new Field2(Fields2.SendingTime, parser.getTimestamp()),
626
+ new Field2(Fields2.ClOrdID, args.clOrdID),
627
+ new Field2(Fields2.Side, args.side),
628
+ new Field2(Fields2.Symbol, args.symbol),
629
+ new Field2(Fields2.OrderQty, Number.parseFloat(String(args.quantity))),
630
+ new Field2(Fields2.Price, Number.parseFloat(String(args.price))),
631
+ new Field2(Fields2.OrdType, args.ordType),
632
+ new Field2(Fields2.HandlInst, args.handlInst),
633
+ new Field2(Fields2.TimeInForce, args.timeInForce),
634
+ new Field2(Fields2.TransactTime, parser.getTimestamp())
635
+ );
636
+ if (!parser.connected) {
637
+ return {
638
+ content: [
639
+ {
640
+ type: "text",
641
+ text: "Error: Not connected. Ignoring message.",
642
+ uri: "executeOrder"
643
+ }
644
+ ],
645
+ isError: true
646
+ };
647
+ }
648
+ parser.send(order);
649
+ const fixData = await response;
650
+ verifiedOrders.delete(args.clOrdID);
651
+ return {
652
+ content: [
653
+ {
654
+ type: "text",
655
+ 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())}`,
656
+ uri: "executeOrder"
657
+ }
658
+ ]
659
+ };
660
+ } catch (error) {
661
+ return {
662
+ content: [
663
+ {
664
+ type: "text",
665
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
666
+ uri: "executeOrder"
667
+ }
668
+ ],
669
+ isError: true
670
+ };
671
+ }
672
+ };
673
+ };
674
+
675
+ // src/tools/parse.ts
676
+ var createParseHandler = (parser) => {
677
+ return async (args) => {
678
+ try {
679
+ const parsedMessage = parser.parse(args.fixString);
680
+ if (!parsedMessage || parsedMessage.length === 0) {
681
+ return {
682
+ content: [
683
+ {
684
+ type: "text",
685
+ text: "Error: Failed to parse FIX string",
686
+ uri: "parse"
687
+ }
688
+ ],
689
+ isError: true
690
+ };
691
+ }
692
+ return {
693
+ content: [
694
+ {
695
+ type: "text",
696
+ text: `${parsedMessage[0].description}
697
+ ${parsedMessage[0].messageTypeDescription}`,
698
+ uri: "parse"
699
+ }
700
+ ]
701
+ };
702
+ } catch (error) {
703
+ return {
704
+ content: [
705
+ {
706
+ type: "text",
707
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
708
+ uri: "parse"
709
+ }
710
+ ],
711
+ isError: true
712
+ };
713
+ }
714
+ };
715
+ };
716
+
717
+ // src/tools/parseToJSON.ts
718
+ var createParseToJSONHandler = (parser) => {
719
+ return async (args) => {
720
+ try {
721
+ const parsedMessage = parser.parse(args.fixString);
722
+ if (!parsedMessage || parsedMessage.length === 0) {
723
+ return {
724
+ content: [
725
+ {
726
+ type: "text",
727
+ text: "Error: Failed to parse FIX string",
728
+ uri: "parseToJSON"
729
+ }
730
+ ],
731
+ isError: true
732
+ };
733
+ }
734
+ return {
735
+ content: [
736
+ {
737
+ type: "text",
738
+ text: `${parsedMessage[0].toFIXJSON()}`,
739
+ uri: "parseToJSON"
740
+ }
741
+ ]
742
+ };
743
+ } catch (error) {
744
+ return {
745
+ content: [
746
+ {
747
+ type: "text",
748
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
749
+ uri: "parseToJSON"
750
+ }
751
+ ],
752
+ isError: true
753
+ };
754
+ }
755
+ };
189
756
  };
757
+
758
+ // src/tools/index.ts
759
+ var createToolHandlers = (parser, verifiedOrders, pendingRequests, marketDataPrices) => ({
760
+ parse: createParseHandler(parser),
761
+ parseToJSON: createParseToJSONHandler(parser),
762
+ verifyOrder: createVerifyOrderHandler(parser, verifiedOrders),
763
+ executeOrder: createExecuteOrderHandler(parser, verifiedOrders, pendingRequests),
764
+ marketDataRequest: createMarketDataRequestHandler(parser, pendingRequests),
765
+ getStockGraph: createGetStockGraphHandler(marketDataPrices),
766
+ getStockPriceHistory: createGetStockPriceHistoryHandler(marketDataPrices)
767
+ });
768
+
769
+ // src/MCPLocal.ts
190
770
  var MCPLocal = class {
191
- logger;
192
771
  parser;
193
772
  server = new Server(
194
773
  {
@@ -197,38 +776,101 @@ var MCPLocal = class {
197
776
  },
198
777
  {
199
778
  capabilities: {
200
- tools: {},
201
- prompts: {},
202
- resources: {}
779
+ tools: Object.entries(toolSchemas).reduce(
780
+ (acc, [name, { description, schema }]) => {
781
+ acc[name] = {
782
+ description,
783
+ parameters: schema
784
+ };
785
+ return acc;
786
+ },
787
+ {}
788
+ )
203
789
  }
204
790
  }
205
791
  );
206
792
  transport = new StdioServerTransport();
207
793
  onReady = void 0;
208
794
  pendingRequests = /* @__PURE__ */ new Map();
795
+ verifiedOrders = /* @__PURE__ */ new Map();
796
+ marketDataPrices = /* @__PURE__ */ new Map();
797
+ MAX_PRICE_HISTORY = 1e5;
798
+ // Maximum number of price points to store per symbol
209
799
  constructor({ logger, onReady }) {
210
- if (logger && !logger.silent) {
211
- this.logger = logger;
212
- }
213
800
  if (onReady) this.onReady = onReady;
214
801
  }
215
802
  async register(parser) {
216
803
  this.parser = parser;
217
- if (parser.logger && !parser.logger.silent) {
218
- this.logger = parser.logger;
219
- }
220
804
  this.parser.addOnMessageCallback((message) => {
805
+ this.parser?.logger.log({
806
+ level: "info",
807
+ message: `MCP Server received message: ${message.messageType}: ${message.description}`
808
+ });
221
809
  const msgType = message.messageType;
222
- if (msgType === Messages.MarketDataSnapshotFullRefresh || msgType === Messages.ExecutionReport) {
223
- const idField = msgType === Messages.MarketDataSnapshotFullRefresh ? message.getField(Fields.MDReqID) : message.getField(Fields.ClOrdID);
224
- if (idField) {
225
- const id = idField.value;
226
- if (typeof id === "string" || typeof id === "number") {
227
- const callback = this.pendingRequests.get(String(id));
228
- if (callback) {
229
- callback(message);
230
- this.pendingRequests.delete(String(id));
810
+ if (msgType === Messages3.MarketDataSnapshotFullRefresh || msgType === Messages3.ExecutionReport || msgType === Messages3.Reject || msgType === Messages3.MarketDataIncrementalRefresh) {
811
+ this.parser?.logger.log({
812
+ level: "info",
813
+ message: `MCP Server handling message type: ${msgType}`
814
+ });
815
+ let id;
816
+ if (msgType === Messages3.MarketDataIncrementalRefresh || msgType === Messages3.MarketDataSnapshotFullRefresh) {
817
+ const symbol = message.getField(Fields3.Symbol);
818
+ const entryType = message.getField(Fields3.MDEntryType);
819
+ const price = message.getField(Fields3.MDEntryPx);
820
+ const size = message.getField(Fields3.MDEntrySize);
821
+ const timestamp = message.getField(Fields3.MDEntryTime)?.value || Date.now();
822
+ if (symbol?.value && price?.value) {
823
+ const symbolStr = String(symbol.value);
824
+ const priceNum = Number(price.value);
825
+ const sizeNum = size?.value ? Number(size.value) : 0;
826
+ const priceHistory = this.marketDataPrices.get(symbolStr) || [];
827
+ const lastEntry = priceHistory[priceHistory.length - 1] || {
828
+ timestamp: 0,
829
+ bid: 0,
830
+ offer: 0,
831
+ spread: 0,
832
+ volume: 0
833
+ };
834
+ const newEntry = {
835
+ timestamp: Number(timestamp),
836
+ bid: entryType?.value === MDEntryType2.Bid ? priceNum : lastEntry.bid,
837
+ offer: entryType?.value === MDEntryType2.Offer ? priceNum : lastEntry.offer,
838
+ spread: entryType?.value === MDEntryType2.Offer ? priceNum - lastEntry.bid : entryType?.value === MDEntryType2.Bid ? lastEntry.offer - priceNum : lastEntry.spread,
839
+ volume: entryType?.value === MDEntryType2.TradeVolume ? sizeNum : lastEntry.volume
840
+ };
841
+ priceHistory.push(newEntry);
842
+ if (priceHistory.length > this.MAX_PRICE_HISTORY) {
843
+ priceHistory.shift();
231
844
  }
845
+ this.marketDataPrices.set(symbolStr, priceHistory);
846
+ this.parser?.logger.log({
847
+ level: "info",
848
+ message: `MCP Server added ${symbol}: ${JSON.stringify(newEntry)}`
849
+ });
850
+ this.server.notification({
851
+ method: "priceUpdate",
852
+ params: {
853
+ symbol: symbolStr,
854
+ ...newEntry
855
+ }
856
+ });
857
+ }
858
+ }
859
+ if (msgType === Messages3.MarketDataSnapshotFullRefresh) {
860
+ const mdReqID = message.getField(Fields3.MDReqID);
861
+ if (mdReqID) id = String(mdReqID.value);
862
+ } else if (msgType === Messages3.ExecutionReport) {
863
+ const clOrdID = message.getField(Fields3.ClOrdID);
864
+ if (clOrdID) id = String(clOrdID.value);
865
+ } else if (msgType === Messages3.Reject) {
866
+ const refSeqNum = message.getField(Fields3.RefSeqNum);
867
+ if (refSeqNum) id = String(refSeqNum.value);
868
+ }
869
+ if (id) {
870
+ const callback = this.pendingRequests.get(id);
871
+ if (callback) {
872
+ callback(message);
873
+ this.pendingRequests.delete(id);
232
874
  }
233
875
  }
234
876
  }
@@ -241,460 +883,62 @@ var MCPLocal = class {
241
883
  }
242
884
  addWorkflows() {
243
885
  if (!this.parser) {
244
- this.logger?.log({
245
- level: "error",
246
- message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of workflows..."
247
- });
248
886
  return;
249
887
  }
250
888
  if (!this.server) {
251
- this.logger?.log({
252
- level: "error",
253
- message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of workflows..."
254
- });
255
889
  return;
256
890
  }
257
- const validateArgs = (args, schema) => {
258
- const result = {};
259
- for (const [key, propSchema] of Object.entries(schema.properties || {})) {
260
- const prop = propSchema;
261
- const value = args?.[key];
262
- if (prop.required && (value === void 0 || value === null)) {
263
- throw new Error(`Required property '${key}' is missing`);
264
- }
265
- if (value !== void 0) {
266
- result[key] = value;
267
- } else if (prop.default !== void 0) {
268
- result[key] = prop.default;
269
- }
270
- }
271
- return result;
272
- };
273
- this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
274
- return {
275
- resources: []
276
- };
277
- });
278
- this.server.setRequestHandler(ListToolsRequestSchema, async () => {
279
- return {
280
- tools: [
281
- {
282
- name: "parse",
283
- description: "Parses a FIX message and describes it in plain language",
284
- inputSchema: parseInputSchema
285
- },
286
- {
287
- name: "parseToJSON",
288
- description: "Parses a FIX message into JSON",
289
- inputSchema: parseToJSONInputSchema
290
- },
291
- {
292
- name: "newOrderSingle",
293
- description: "Creates and sends a New Order Single",
294
- inputSchema: newOrderSingleInputSchema
295
- },
296
- {
297
- name: "marketDataRequest",
298
- description: "Sends a request for Market Data with the given symbol",
299
- inputSchema: marketDataRequestInputSchema
300
- }
301
- ]
302
- };
303
- });
304
- this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
305
- const { name, arguments: args } = request.params;
306
- switch (name) {
307
- case "parse": {
308
- try {
309
- const { fixString } = validateArgs(args, parseInputSchema);
310
- const parsedMessage = this.parser?.parse(fixString);
311
- if (!parsedMessage || parsedMessage.length === 0) {
312
- return {
313
- isError: true,
314
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
315
- };
316
- }
317
- return {
318
- content: [
319
- {
320
- type: "text",
321
- text: `${parsedMessage[0].description}
322
- ${parsedMessage[0].messageTypeDescription}`
323
- }
324
- ]
325
- };
326
- } catch (error) {
327
- return {
328
- isError: true,
329
- content: [
330
- {
331
- type: "text",
332
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
333
- }
334
- ]
335
- };
336
- }
337
- }
338
- case "parseToJSON": {
339
- try {
340
- const { fixString } = validateArgs(args, parseToJSONInputSchema);
341
- const parsedMessage = this.parser?.parse(fixString);
342
- if (!parsedMessage || parsedMessage.length === 0) {
343
- return {
344
- isError: true,
345
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
346
- };
347
- }
348
- return {
349
- content: [
350
- {
351
- type: "text",
352
- text: `${parsedMessage[0].toFIXJSON()}`
353
- }
354
- ]
355
- };
356
- } catch (error) {
357
- return {
358
- isError: true,
359
- content: [
360
- {
361
- type: "text",
362
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
363
- }
364
- ]
365
- };
366
- }
367
- }
368
- case "newOrderSingle": {
369
- try {
370
- const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = validateArgs(args, newOrderSingleInputSchema);
371
- const response = new Promise((resolve) => {
372
- this.pendingRequests.set(clOrdID, resolve);
373
- });
374
- const order = this.parser?.createMessage(
375
- new Field(Fields.MsgType, Messages.NewOrderSingle),
376
- new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
377
- new Field(Fields.SenderCompID, this.parser?.sender),
378
- new Field(Fields.TargetCompID, this.parser?.target),
379
- new Field(Fields.SendingTime, this.parser?.getTimestamp()),
380
- new Field(Fields.ClOrdID, clOrdID),
381
- new Field(Fields.Side, side),
382
- new Field(Fields.Symbol, symbol),
383
- new Field(Fields.OrderQty, quantity),
384
- new Field(Fields.Price, price),
385
- new Field(Fields.OrdType, ordType),
386
- new Field(Fields.HandlInst, handlInst),
387
- new Field(Fields.TimeInForce, timeInForce),
388
- new Field(Fields.TransactTime, this.parser?.getTimestamp())
389
- );
390
- if (!this.parser?.connected) {
391
- this.logger?.log({
392
- level: "error",
393
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
394
- });
395
- return {
396
- isError: true,
397
- content: [
398
- {
399
- type: "text",
400
- text: "Error: Not connected. Ignoring message."
401
- }
402
- ]
403
- };
404
- }
405
- this.parser?.send(order);
406
- this.logger?.log({
407
- level: "info",
408
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${order?.description}`
409
- });
410
- const fixData = await response;
411
- return {
412
- content: [
413
- {
414
- type: "text",
415
- text: `Execution Report for order ${clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`
416
- }
417
- ]
418
- };
419
- } catch (error) {
420
- return {
421
- isError: true,
422
- content: [
423
- {
424
- type: "text",
425
- text: `Error: ${error instanceof Error ? error.message : "Failed to create order"}`
426
- }
427
- ]
428
- };
429
- }
430
- }
431
- case "marketDataRequest": {
432
- try {
433
- const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = validateArgs(
434
- args,
435
- marketDataRequestInputSchema
436
- );
437
- const response = new Promise((resolve) => {
438
- this.pendingRequests.set(mdReqID, resolve);
439
- });
440
- const marketDataRequest = this.parser?.createMessage(
441
- new Field(Fields.MsgType, Messages.MarketDataRequest),
442
- new Field(Fields.SenderCompID, this.parser?.sender),
443
- new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
444
- new Field(Fields.TargetCompID, this.parser?.target),
445
- new Field(Fields.SendingTime, this.parser?.getTimestamp()),
446
- new Field(Fields.MarketDepth, 0),
447
- new Field(Fields.MDUpdateType, mdUpdateType),
448
- new Field(Fields.NoRelatedSym, 1),
449
- new Field(Fields.Symbol, symbol),
450
- new Field(Fields.MDReqID, mdReqID),
451
- new Field(Fields.SubscriptionRequestType, subscriptionRequestType),
452
- new Field(Fields.NoMDEntryTypes, 1),
453
- new Field(Fields.MDEntryType, mdEntryType)
454
- );
455
- if (!this.parser?.connected) {
456
- this.logger?.log({
457
- level: "error",
458
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
459
- });
460
- return {
461
- isError: true,
462
- content: [
463
- {
464
- type: "text",
465
- text: "Error: Not connected. Ignoring message."
466
- }
467
- ]
468
- };
469
- }
470
- this.parser?.send(marketDataRequest);
471
- this.logger?.log({
472
- level: "info",
473
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${marketDataRequest?.description}`
474
- });
475
- const fixData = await response;
476
- return {
477
- content: [
478
- {
479
- type: "text",
480
- text: `Market data for ${symbol}: ${JSON.stringify(fixData.toFIXJSON())}`
481
- }
482
- ]
483
- };
484
- } catch (error) {
485
- return {
486
- isError: true,
487
- content: [
488
- {
489
- type: "text",
490
- text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`
491
- }
492
- ]
493
- };
494
- }
495
- }
496
- default:
497
- throw new Error(`Unknown tool: ${name}`);
891
+ this.server.setRequestHandler(
892
+ z.object({ method: z.literal("tools/list") }),
893
+ async (request, extra) => {
894
+ return {
895
+ tools: Object.entries(toolSchemas).map(([name, { description, schema }]) => ({
896
+ name,
897
+ description,
898
+ inputSchema: schema
899
+ }))
900
+ };
498
901
  }
499
- });
500
- this.server.setRequestHandler(ListPromptsRequestSchema, async () => {
501
- return {
502
- prompts: [
503
- {
504
- name: "parse",
505
- description: "Parses a FIX message and describes it in plain language",
506
- arguments: [
507
- {
508
- name: "fixString",
509
- description: "FIX message string to parse",
510
- required: true
511
- }
512
- ]
513
- },
514
- {
515
- name: "parseToJSON",
516
- description: "Parses a FIX message into JSON",
517
- arguments: [
518
- {
519
- name: "fixString",
520
- description: "FIX message string to parse",
521
- required: true
522
- }
523
- ]
524
- },
525
- {
526
- name: "newOrderSingle",
527
- description: "Creates and sends a New Order Single",
528
- arguments: [
529
- {
530
- name: "clOrdID",
531
- description: "Client Order ID",
532
- required: true
533
- },
534
- {
535
- name: "handlInst",
536
- description: "Handling instruction",
537
- required: false
538
- },
539
- {
540
- name: "quantity",
541
- description: "Order quantity",
542
- required: true
543
- },
544
- {
545
- name: "price",
546
- description: "Order price",
547
- required: true
548
- },
549
- {
550
- name: "ordType",
551
- description: "Order type",
552
- required: false
553
- },
554
- {
555
- name: "side",
556
- description: "Order side (1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed)",
557
- required: true
558
- },
559
- {
560
- name: "symbol",
561
- description: "Trading symbol",
562
- required: true
563
- },
564
- {
565
- name: "timeInForce",
566
- description: "Time in force",
567
- required: false
568
- }
569
- ]
570
- },
571
- {
572
- name: "marketDataRequest",
573
- description: "Sends a request for Market Data with the given symbol",
574
- arguments: [
575
- {
576
- name: "mdUpdateType",
577
- description: "Market data update type",
578
- required: false
579
- },
580
- {
581
- name: "symbol",
582
- description: "Trading symbol",
583
- required: true
584
- },
585
- {
586
- name: "mdReqID",
587
- description: "Market data request ID",
588
- required: true
589
- },
590
- {
591
- name: "subscriptionRequestType",
592
- description: "Subscription request type",
593
- required: false
594
- },
595
- {
596
- name: "mdEntryType",
597
- description: "Market data entry type",
598
- required: false
599
- }
600
- ]
601
- }
602
- ]
603
- };
604
- });
605
- this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
606
- const { name, arguments: args } = request.params;
607
- switch (name) {
608
- case "parse": {
609
- const fixString = args?.fixString || "";
902
+ );
903
+ this.server.setRequestHandler(
904
+ z.object({
905
+ method: z.literal("tools/call"),
906
+ params: z.object({
907
+ name: z.string(),
908
+ arguments: z.any(),
909
+ _meta: z.object({
910
+ progressToken: z.number()
911
+ }).optional()
912
+ })
913
+ }),
914
+ async (request, extra) => {
915
+ const { name, arguments: args } = request.params;
916
+ const toolHandlers = createToolHandlers(
917
+ this.parser,
918
+ this.verifiedOrders,
919
+ this.pendingRequests,
920
+ this.marketDataPrices
921
+ );
922
+ const handler = toolHandlers[name];
923
+ if (!handler) {
610
924
  return {
611
- messages: [
925
+ content: [
612
926
  {
613
- role: "user",
614
- content: {
615
- type: "text",
616
- text: `Please parse and explain this FIX message: ${fixString}`
617
- }
927
+ type: "text",
928
+ text: `Tool not found: ${name}`,
929
+ uri: name
618
930
  }
619
- ]
931
+ ],
932
+ isError: true
620
933
  };
621
934
  }
622
- case "parseToJSON": {
623
- const fixString = args?.fixString || "";
624
- return {
625
- messages: [
626
- {
627
- role: "user",
628
- content: {
629
- type: "text",
630
- text: `Please parse the FIX message to JSON: ${fixString}`
631
- }
632
- }
633
- ]
634
- };
635
- }
636
- case "newOrderSingle": {
637
- const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = args || {};
638
- return {
639
- messages: [
640
- {
641
- role: "user",
642
- content: {
643
- type: "text",
644
- text: [
645
- "Create a New Order Single FIX message with the following parameters:",
646
- `- ClOrdID: ${clOrdID}`,
647
- `- HandlInst: ${handlInst ?? "3"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '1' for Manual, '2' for Automated, '3' for AutomatedNoIntervention)`,
648
- `- Quantity: ${quantity}`,
649
- `- Price: ${price}`,
650
- `- OrdType: ${ordType ?? "1"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '1' for Market, '2' for Limit, '3' for Stop)`,
651
- `- Side: ${side} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '1' for Buy, '2' for Sell)`,
652
- `- Symbol: ${symbol}`,
653
- `- TimeInForce: ${timeInForce ?? "0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for Day, '1' for Good Till Cancel, '2' for At Opening, '3' for Immediate or Cancel, '4' for Fill or Kill, '5' for Good Till Crossing, '6' for Good Till Date)`,
654
- "",
655
- "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values.",
656
- "",
657
- 'Note: For the Side parameter, always use the numeric/alphabetic value (e.g., "1" for Buy, "2" for Sell) as defined in the FIX protocol, not the descriptive name.',
658
- 'Note: For the HandlInst parameter, always use the numeric/alphabetic value (e.g., "1" for Manual, "2" for Automated, "3" for AutomatedNoIntervention) as defined in the FIX protocol, not the descriptive name.',
659
- 'Note: For the OrdType parameter, always use the numeric/alphabetic value (e.g., "1" for Market, "2" for Limit, "3" for Stop) as defined in the FIX protocol, not the descriptive name.',
660
- 'Note: For the TimeInForce parameter, always use the numeric/alphabetic value (e.g., "0" for Day, "1" for Good Till Cancel, "2" for At Opening) as defined in the FIX protocol, not the descriptive name.'
661
- ].join("\n")
662
- }
663
- }
664
- ]
665
- };
666
- }
667
- case "marketDataRequest": {
668
- const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = args || {};
669
- return {
670
- messages: [
671
- {
672
- role: "user",
673
- content: {
674
- type: "text",
675
- text: [
676
- "Create a Market Data Request FIX message with the following parameters:",
677
- `- MDUpdateType: ${mdUpdateType ?? "0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for FullRefresh, '1' for IncrementalRefresh)`,
678
- `- Symbol: ${symbol}`,
679
- `- MDReqID: ${mdReqID}`,
680
- `- SubscriptionRequestType: ${subscriptionRequestType ?? "0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for Snapshot + Updates, '1' for Snapshot, '2' for Unsubscribe)`,
681
- `- MDEntryType: ${mdEntryType ?? "0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for Bid, '1' for Offer, '2' for Trade, '3' for Index Value, '4' for Opening Price)`,
682
- "",
683
- "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values.",
684
- "",
685
- 'Note: For the MDUpdateType parameter, always use the numeric/alphabetic value (e.g., "0" for FullRefresh, "1" for IncrementalRefresh) as defined in the FIX protocol, not the descriptive name.',
686
- 'Note: For the SubscriptionRequestType parameter, always use the numeric/alphabetic value (e.g., "0" for Snapshot + Updates, "1" for Snapshot, "2" for Unsubscribe) as defined in the FIX protocol, not the descriptive name.',
687
- 'Note: For the MDEntryType parameter, always use the numeric/alphabetic value (e.g., "0" for Bid, "1" for Offer, "2" for Trade, "3" for Index Value, "4" for Opening Price) as defined in the FIX protocol, not the descriptive name.'
688
- ].join("\n")
689
- }
690
- }
691
- ]
692
- };
693
- }
694
- default:
695
- throw new Error(`Unknown prompt: ${name}`);
935
+ const result = await handler(args);
936
+ return {
937
+ content: result.content,
938
+ isError: result.isError
939
+ };
696
940
  }
697
- });
941
+ );
698
942
  process.on("SIGINT", async () => {
699
943
  await this.server.close();
700
944
  process.exit(0);