fixparser-plugin-mcp 9.1.7-3c6fd297 → 9.1.7-3f807208

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