fixparser-plugin-mcp 9.1.7-400318ef → 9.1.7-46844c62

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