fixparser-plugin-mcp 9.1.7-c415bb75 → 9.1.7-c5ae06ce

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