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