fixparser-plugin-mcp 9.1.7-8fdb1e41 → 9.1.7-945d3edd

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