fixparser-plugin-mcp 9.1.7-b8fd1147 → 9.1.7-bb684c39

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,196 +1,11 @@
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 {
5
- CallToolRequestSchema,
6
- GetPromptRequestSchema,
7
- ListPromptsRequestSchema,
8
- ListResourcesRequestSchema,
9
- ListToolsRequestSchema
10
- } from "@modelcontextprotocol/sdk/types.js";
11
- import {
12
- Field,
13
- Fields,
14
- HandlInst,
15
- MDEntryType,
16
- Messages,
17
- OrdType,
18
- SubscriptionRequestType,
19
- TimeInForce
20
- } from "fixparser";
21
- var parseInputSchema = {
22
- type: "object",
23
- properties: {
24
- fixString: {
25
- type: "string",
26
- description: "FIX message string to parse"
27
- }
28
- },
29
- required: ["fixString"]
30
- };
31
- var parseToJSONInputSchema = {
32
- type: "object",
33
- properties: {
34
- fixString: {
35
- type: "string",
36
- description: "FIX message string to parse"
37
- }
38
- },
39
- required: ["fixString"]
40
- };
41
- var newOrderSingleInputSchema = {
42
- type: "object",
43
- properties: {
44
- clOrdID: {
45
- type: "string",
46
- description: "Client Order ID"
47
- },
48
- handlInst: {
49
- type: "string",
50
- enum: ["1", "2", "3"],
51
- default: HandlInst.AutomatedExecutionNoIntervention,
52
- description: 'Handling instruction (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "1" for Manual, "2" for Automated, "3" for AutomatedNoIntervention)'
53
- },
54
- quantity: {
55
- type: "number",
56
- description: "Order quantity"
57
- },
58
- price: {
59
- type: "number",
60
- description: "Order price"
61
- },
62
- ordType: {
63
- type: "string",
64
- enum: [
65
- "1",
66
- "2",
67
- "3",
68
- "4",
69
- "5",
70
- "6",
71
- "7",
72
- "8",
73
- "9",
74
- "A",
75
- "B",
76
- "C",
77
- "D",
78
- "E",
79
- "F",
80
- "G",
81
- "H",
82
- "I",
83
- "J",
84
- "K",
85
- "L",
86
- "M",
87
- "P",
88
- "Q",
89
- "R",
90
- "S"
91
- ],
92
- default: OrdType.Market,
93
- description: 'Order type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "1" for Market, "2" for Limit, "3" for Stop)'
94
- },
95
- side: {
96
- type: "string",
97
- enum: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H"],
98
- description: 'Order side (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "1" for Buy, "2" for Sell, "3" for BuyMinus, "4" for SellPlus, "5" for SellShort, "6" for SellShortExempt, "7" for Undisclosed, "8" for Cross, "9" for CrossShort, "A" for CrossShortExempt, "B" for AsDefined, "C" for Opposite, "D" for Subscribe, "E" for Redeem, "F" for Lend, "G" for Borrow, "H" for SellUndisclosed)'
99
- },
100
- symbol: {
101
- type: "string",
102
- description: "Trading symbol"
103
- },
104
- timeInForce: {
105
- type: "string",
106
- enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"],
107
- default: TimeInForce.Day,
108
- description: 'Time in force (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Day, "1" for Good Till Cancel, "2" for At Opening, "3" for Immediate or Cancel, "4" for Fill or Kill, "5" for Good Till Crossing, "6" for Good Till Date)'
109
- }
110
- },
111
- required: ["clOrdID", "quantity", "price", "side", "symbol"]
112
- };
113
- var marketDataRequestInputSchema = {
114
- type: "object",
115
- properties: {
116
- mdUpdateType: {
117
- type: "string",
118
- enum: ["0", "1"],
119
- default: "0",
120
- description: 'Market data update type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for FullRefresh, "1" for IncrementalRefresh)'
121
- },
122
- symbol: {
123
- type: "string",
124
- description: "Trading symbol"
125
- },
126
- mdReqID: {
127
- type: "string",
128
- description: "Market data request ID"
129
- },
130
- subscriptionRequestType: {
131
- type: "string",
132
- enum: ["0", "1", "2"],
133
- default: SubscriptionRequestType.SnapshotAndUpdates,
134
- description: 'Subscription request type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Snapshot + Updates, "1" for Snapshot, "2" for Unsubscribe)'
135
- },
136
- mdEntryType: {
137
- type: "string",
138
- enum: [
139
- "0",
140
- "1",
141
- "2",
142
- "3",
143
- "4",
144
- "5",
145
- "6",
146
- "7",
147
- "8",
148
- "9",
149
- "A",
150
- "B",
151
- "C",
152
- "D",
153
- "E",
154
- "F",
155
- "G",
156
- "H",
157
- "J",
158
- "K",
159
- "L",
160
- "M",
161
- "N",
162
- "O",
163
- "P",
164
- "Q",
165
- "S",
166
- "R",
167
- "T",
168
- "U",
169
- "V",
170
- "W",
171
- "X",
172
- "Y",
173
- "Z",
174
- "a",
175
- "b",
176
- "c",
177
- "d",
178
- "e",
179
- "g",
180
- "h",
181
- "i",
182
- "t"
183
- ],
184
- default: MDEntryType.Bid,
185
- description: 'Market data entry type (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use "0" for Bid, "1" for Offer, "2" for Trade, "3" for Index Value, "4" for Opening Price)'
186
- }
187
- },
188
- required: ["symbol", "mdReqID"]
189
- };
4
+ import { Field, Fields, Messages } from "fixparser";
5
+ import { z } from "zod";
190
6
  var MCPLocal = class {
191
- logger;
192
7
  parser;
193
- server = new Server(
8
+ server = new McpServer(
194
9
  {
195
10
  name: "fixparser",
196
11
  version: "1.0.0"
@@ -206,29 +21,31 @@ var MCPLocal = class {
206
21
  transport = new StdioServerTransport();
207
22
  onReady = void 0;
208
23
  pendingRequests = /* @__PURE__ */ new Map();
24
+ verifiedOrders = /* @__PURE__ */ new Map();
209
25
  constructor({ logger, onReady }) {
210
- if (logger && !logger.silent) {
211
- this.logger = logger;
212
- }
213
26
  if (onReady) this.onReady = onReady;
214
27
  }
215
28
  async register(parser) {
216
29
  this.parser = parser;
217
- if (parser.logger && !parser.logger.silent) {
218
- this.logger = parser.logger;
219
- }
220
30
  this.parser.addOnMessageCallback((message) => {
221
31
  const msgType = message.messageType;
222
- if (msgType === Messages.MarketDataSnapshotFullRefresh || msgType === Messages.ExecutionReport) {
223
- const idField = msgType === Messages.MarketDataSnapshotFullRefresh ? message.getField(Fields.MDReqID) : message.getField(Fields.ClOrdID);
224
- if (idField) {
225
- const id = idField.value;
226
- if (typeof id === "string" || typeof id === "number") {
227
- const callback = this.pendingRequests.get(String(id));
228
- if (callback) {
229
- callback(message);
230
- this.pendingRequests.delete(String(id));
231
- }
32
+ if (msgType === Messages.MarketDataSnapshotFullRefresh || msgType === Messages.ExecutionReport || msgType === Messages.Reject) {
33
+ let id;
34
+ if (msgType === Messages.MarketDataSnapshotFullRefresh) {
35
+ const mdReqID = message.getField(Fields.MDReqID);
36
+ if (mdReqID) id = String(mdReqID.value);
37
+ } else if (msgType === Messages.ExecutionReport) {
38
+ const clOrdID = message.getField(Fields.ClOrdID);
39
+ if (clOrdID) id = String(clOrdID.value);
40
+ } else if (msgType === Messages.Reject) {
41
+ const refSeqNum = message.getField(Fields.RefSeqNum);
42
+ if (refSeqNum) id = String(refSeqNum.value);
43
+ }
44
+ if (id) {
45
+ const callback = this.pendingRequests.get(id);
46
+ if (callback) {
47
+ callback(message);
48
+ this.pendingRequests.delete(id);
232
49
  }
233
50
  }
234
51
  }
@@ -241,460 +58,570 @@ var MCPLocal = class {
241
58
  }
242
59
  addWorkflows() {
243
60
  if (!this.parser) {
244
- this.logger?.log({
245
- level: "error",
246
- message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of workflows..."
247
- });
248
61
  return;
249
62
  }
250
63
  if (!this.server) {
251
- this.logger?.log({
252
- level: "error",
253
- message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of workflows..."
254
- });
255
64
  return;
256
65
  }
257
- const validateArgs = (args, schema) => {
258
- const result = {};
259
- for (const [key, propSchema] of Object.entries(schema.properties || {})) {
260
- const prop = propSchema;
261
- const value = args?.[key];
262
- if (prop.required && (value === void 0 || value === null)) {
263
- throw new Error(`Required property '${key}' is missing`);
264
- }
265
- if (value !== void 0) {
266
- result[key] = value;
267
- } else if (prop.default !== void 0) {
268
- result[key] = prop.default;
269
- }
270
- }
271
- return result;
272
- };
273
- this.server.setRequestHandler(ListResourcesRequestSchema, async () => {
274
- return {
275
- resources: []
276
- };
277
- });
278
- this.server.setRequestHandler(ListToolsRequestSchema, async () => {
279
- return {
280
- tools: [
281
- {
282
- name: "parse",
283
- description: "Parses a FIX message and describes it in plain language",
284
- inputSchema: parseInputSchema
285
- },
286
- {
287
- name: "parseToJSON",
288
- description: "Parses a FIX message into JSON",
289
- inputSchema: parseToJSONInputSchema
290
- },
291
- {
292
- name: "newOrderSingle",
293
- description: "Creates and sends a New Order Single",
294
- inputSchema: newOrderSingleInputSchema
295
- },
296
- {
297
- name: "marketDataRequest",
298
- description: "Sends a request for Market Data with the given symbol",
299
- inputSchema: marketDataRequestInputSchema
300
- }
301
- ]
302
- };
303
- });
304
- this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
305
- const { name, arguments: args } = request.params;
306
- switch (name) {
307
- case "parse": {
308
- try {
309
- const { fixString } = validateArgs(args, parseInputSchema);
310
- const parsedMessage = this.parser?.parse(fixString);
311
- if (!parsedMessage || parsedMessage.length === 0) {
312
- return {
313
- isError: true,
314
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
315
- };
316
- }
66
+ this.server.tool(
67
+ "parse",
68
+ "Parses a FIX message and describes it in plain language",
69
+ {
70
+ fixString: z.string().describe("FIX message string to parse")
71
+ },
72
+ async (args) => {
73
+ try {
74
+ const parsedMessage = this.parser?.parse(args.fixString);
75
+ if (!parsedMessage || parsedMessage.length === 0) {
317
76
  return {
318
- content: [
319
- {
320
- type: "text",
321
- text: `${parsedMessage[0].description}
322
- ${parsedMessage[0].messageTypeDescription}`
323
- }
324
- ]
325
- };
326
- } catch (error) {
327
- return {
328
- isError: true,
329
- content: [
330
- {
331
- type: "text",
332
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
333
- }
334
- ]
77
+ content: [{ type: "text", text: "Error: Failed to parse FIX string" }],
78
+ isError: true
335
79
  };
336
80
  }
81
+ return {
82
+ content: [
83
+ {
84
+ type: "text",
85
+ text: `${parsedMessage[0].description}
86
+ ${parsedMessage[0].messageTypeDescription}`
87
+ }
88
+ ]
89
+ };
90
+ } catch (error) {
91
+ return {
92
+ content: [
93
+ {
94
+ type: "text",
95
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
96
+ }
97
+ ],
98
+ isError: true
99
+ };
337
100
  }
338
- case "parseToJSON": {
339
- try {
340
- const { fixString } = validateArgs(args, parseToJSONInputSchema);
341
- const parsedMessage = this.parser?.parse(fixString);
342
- if (!parsedMessage || parsedMessage.length === 0) {
343
- return {
344
- isError: true,
345
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
346
- };
347
- }
348
- return {
349
- content: [
350
- {
351
- type: "text",
352
- text: `${parsedMessage[0].toFIXJSON()}`
353
- }
354
- ]
355
- };
356
- } catch (error) {
101
+ }
102
+ );
103
+ this.server.tool(
104
+ "parseToJSON",
105
+ "Parses a FIX message into JSON",
106
+ {
107
+ fixString: z.string().describe("FIX message string to parse")
108
+ },
109
+ async (args) => {
110
+ try {
111
+ const parsedMessage = this.parser?.parse(args.fixString);
112
+ if (!parsedMessage || parsedMessage.length === 0) {
357
113
  return {
358
- isError: true,
359
- content: [
360
- {
361
- type: "text",
362
- text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
363
- }
364
- ]
114
+ content: [{ type: "text", text: "Error: Failed to parse FIX string" }],
115
+ isError: true
365
116
  };
366
117
  }
118
+ return {
119
+ content: [
120
+ {
121
+ type: "text",
122
+ text: `${parsedMessage[0].toFIXJSON()}`
123
+ }
124
+ ]
125
+ };
126
+ } catch (error) {
127
+ return {
128
+ content: [
129
+ {
130
+ type: "text",
131
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
132
+ }
133
+ ],
134
+ isError: true
135
+ };
367
136
  }
368
- case "newOrderSingle": {
369
- try {
370
- const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = validateArgs(args, newOrderSingleInputSchema);
371
- const response = new Promise((resolve) => {
372
- this.pendingRequests.set(clOrdID, resolve);
373
- });
374
- const order = this.parser?.createMessage(
375
- new Field(Fields.MsgType, Messages.NewOrderSingle),
376
- new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
377
- new Field(Fields.SenderCompID, this.parser?.sender),
378
- new Field(Fields.TargetCompID, this.parser?.target),
379
- new Field(Fields.SendingTime, this.parser?.getTimestamp()),
380
- new Field(Fields.ClOrdID, clOrdID),
381
- new Field(Fields.Side, side),
382
- new Field(Fields.Symbol, symbol),
383
- new Field(Fields.OrderQty, quantity),
384
- new Field(Fields.Price, price),
385
- new Field(Fields.OrdType, ordType),
386
- new Field(Fields.HandlInst, handlInst),
387
- new Field(Fields.TimeInForce, timeInForce),
388
- new Field(Fields.TransactTime, this.parser?.getTimestamp())
389
- );
390
- if (!this.parser?.connected) {
391
- this.logger?.log({
392
- level: "error",
393
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
394
- });
395
- return {
396
- isError: true,
397
- content: [
398
- {
399
- type: "text",
400
- text: "Error: Not connected. Ignoring message."
401
- }
402
- ]
403
- };
404
- }
405
- this.parser?.send(order);
406
- this.logger?.log({
407
- level: "info",
408
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${order?.description}`
409
- });
410
- const fixData = await response;
411
- return {
412
- content: [
413
- {
414
- type: "text",
415
- text: `Execution Report for order ${clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`
416
- }
417
- ]
418
- };
419
- } catch (error) {
137
+ }
138
+ );
139
+ this.server.tool(
140
+ "verifyOrder",
141
+ "Verifies all parameters for a New Order Single. This is the first step - verification only, no order is sent.",
142
+ {
143
+ clOrdID: z.string().describe("Client Order ID"),
144
+ handlInst: z.enum(["1", "2", "3"]).describe("Handling instruction (1=Manual, 2=Automated, 3=AutomatedNoIntervention)"),
145
+ quantity: z.string().describe("Order quantity"),
146
+ price: z.string().describe("Order price"),
147
+ ordType: z.string().describe("Order type (1=Market, 2=Limit, 3=Stop)"),
148
+ side: z.string().describe("Order side (1=Buy, 2=Sell, etc.)"),
149
+ symbol: z.string().describe("Trading symbol"),
150
+ timeInForce: z.string().describe("Time in force (0=Day, 1=Good Till Cancel, etc.)")
151
+ },
152
+ async (args) => {
153
+ try {
154
+ this.verifiedOrders.set(args.clOrdID, {
155
+ clOrdID: args.clOrdID,
156
+ handlInst: args.handlInst,
157
+ quantity: Number.parseFloat(args.quantity),
158
+ price: Number.parseFloat(args.price),
159
+ ordType: args.ordType,
160
+ side: args.side,
161
+ symbol: args.symbol,
162
+ timeInForce: args.timeInForce
163
+ });
164
+ return {
165
+ content: [
166
+ {
167
+ type: "text",
168
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
169
+
170
+ Parameters verified:
171
+ - ClOrdID: ${args.clOrdID}
172
+ - HandlInst: ${args.handlInst}
173
+ - Quantity: ${args.quantity}
174
+ - Price: ${args.price}
175
+ - OrdType: ${args.ordType}
176
+ - Side: ${args.side}
177
+ - Symbol: ${args.symbol}
178
+ - TimeInForce: ${args.timeInForce}
179
+
180
+ To execute this order, call the executeOrder tool with these exact same parameters.`
181
+ }
182
+ ]
183
+ };
184
+ } catch (error) {
185
+ return {
186
+ content: [
187
+ {
188
+ type: "text",
189
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`
190
+ }
191
+ ],
192
+ isError: true
193
+ };
194
+ }
195
+ }
196
+ );
197
+ this.server.tool(
198
+ "executeOrder",
199
+ "Executes a New Order Single after verification. This is the second step - only call after successful verification.",
200
+ {
201
+ clOrdID: z.string().describe("Client Order ID"),
202
+ handlInst: z.enum(["1", "2", "3"]).describe("Handling instruction (1=Manual, 2=Automated, 3=AutomatedNoIntervention)"),
203
+ quantity: z.string().describe("Order quantity"),
204
+ price: z.string().describe("Order price"),
205
+ ordType: z.string().describe("Order type (1=Market, 2=Limit, 3=Stop)"),
206
+ side: z.string().describe("Order side (1=Buy, 2=Sell, etc.)"),
207
+ symbol: z.string().describe("Trading symbol"),
208
+ timeInForce: z.string().describe("Time in force (0=Day, 1=Good Till Cancel, etc.)")
209
+ },
210
+ async (args) => {
211
+ try {
212
+ const verifiedOrder = this.verifiedOrders.get(args.clOrdID);
213
+ if (!verifiedOrder) {
420
214
  return {
421
- isError: true,
422
215
  content: [
423
216
  {
424
217
  type: "text",
425
- text: `Error: ${error instanceof Error ? error.message : "Failed to create order"}`
218
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`
426
219
  }
427
- ]
220
+ ],
221
+ isError: true
428
222
  };
429
223
  }
430
- }
431
- case "marketDataRequest": {
432
- try {
433
- const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = validateArgs(
434
- args,
435
- marketDataRequestInputSchema
436
- );
437
- const response = new Promise((resolve) => {
438
- this.pendingRequests.set(mdReqID, resolve);
439
- });
440
- const marketDataRequest = this.parser?.createMessage(
441
- new Field(Fields.MsgType, Messages.MarketDataRequest),
442
- new Field(Fields.SenderCompID, this.parser?.sender),
443
- new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
444
- new Field(Fields.TargetCompID, this.parser?.target),
445
- new Field(Fields.SendingTime, this.parser?.getTimestamp()),
446
- new Field(Fields.MarketDepth, 0),
447
- new Field(Fields.MDUpdateType, mdUpdateType),
448
- new Field(Fields.NoRelatedSym, 1),
449
- new Field(Fields.Symbol, symbol),
450
- new Field(Fields.MDReqID, mdReqID),
451
- new Field(Fields.SubscriptionRequestType, subscriptionRequestType),
452
- new Field(Fields.NoMDEntryTypes, 1),
453
- new Field(Fields.MDEntryType, mdEntryType)
454
- );
455
- if (!this.parser?.connected) {
456
- this.logger?.log({
457
- level: "error",
458
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
459
- });
460
- return {
461
- isError: true,
462
- content: [
463
- {
464
- type: "text",
465
- text: "Error: Not connected. Ignoring message."
466
- }
467
- ]
468
- };
469
- }
470
- this.parser?.send(marketDataRequest);
471
- this.logger?.log({
472
- level: "info",
473
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${marketDataRequest?.description}`
474
- });
475
- const fixData = await response;
224
+ 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) {
476
225
  return {
477
226
  content: [
478
227
  {
479
228
  type: "text",
480
- text: `Market data for ${symbol}: ${JSON.stringify(fixData.toFIXJSON())}`
229
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified."
481
230
  }
482
- ]
231
+ ],
232
+ isError: true
483
233
  };
484
- } catch (error) {
234
+ }
235
+ const response = new Promise((resolve) => {
236
+ this.pendingRequests.set(args.clOrdID, resolve);
237
+ });
238
+ const order = this.parser?.createMessage(
239
+ new Field(Fields.MsgType, Messages.NewOrderSingle),
240
+ new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
241
+ new Field(Fields.SenderCompID, this.parser?.sender),
242
+ new Field(Fields.TargetCompID, this.parser?.target),
243
+ new Field(Fields.SendingTime, this.parser?.getTimestamp()),
244
+ new Field(Fields.ClOrdID, args.clOrdID),
245
+ new Field(Fields.Side, args.side),
246
+ new Field(Fields.Symbol, args.symbol),
247
+ new Field(Fields.OrderQty, Number.parseFloat(args.quantity)),
248
+ new Field(Fields.Price, Number.parseFloat(args.price)),
249
+ new Field(Fields.OrdType, args.ordType),
250
+ new Field(Fields.HandlInst, args.handlInst),
251
+ new Field(Fields.TimeInForce, args.timeInForce),
252
+ new Field(Fields.TransactTime, this.parser?.getTimestamp())
253
+ );
254
+ if (!this.parser?.connected) {
485
255
  return {
486
- isError: true,
487
256
  content: [
488
257
  {
489
258
  type: "text",
490
- text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`
259
+ text: "Error: Not connected. Ignoring message."
491
260
  }
492
- ]
261
+ ],
262
+ isError: true
493
263
  };
494
264
  }
495
- }
496
- default:
497
- throw new Error(`Unknown tool: ${name}`);
498
- }
499
- });
500
- this.server.setRequestHandler(ListPromptsRequestSchema, async () => {
501
- return {
502
- prompts: [
503
- {
504
- name: "parse",
505
- description: "Parses a FIX message and describes it in plain language",
506
- arguments: [
507
- {
508
- name: "fixString",
509
- description: "FIX message string to parse",
510
- required: true
511
- }
512
- ]
513
- },
514
- {
515
- name: "parseToJSON",
516
- description: "Parses a FIX message into JSON",
517
- arguments: [
518
- {
519
- name: "fixString",
520
- description: "FIX message string to parse",
521
- required: true
522
- }
523
- ]
524
- },
525
- {
526
- name: "newOrderSingle",
527
- description: "Creates and sends a New Order Single",
528
- arguments: [
529
- {
530
- name: "clOrdID",
531
- description: "Client Order ID",
532
- required: true
533
- },
534
- {
535
- name: "handlInst",
536
- description: "Handling instruction",
537
- required: false
538
- },
539
- {
540
- name: "quantity",
541
- description: "Order quantity",
542
- required: true
543
- },
544
- {
545
- name: "price",
546
- description: "Order price",
547
- required: true
548
- },
549
- {
550
- name: "ordType",
551
- description: "Order type",
552
- required: false
553
- },
554
- {
555
- name: "side",
556
- description: "Order side (1=Buy, 2=Sell, 3=BuyMinus, 4=SellPlus, 5=SellShort, 6=SellShortExempt, 7=Undisclosed, 8=Cross, 9=CrossShort, A=CrossShortExempt, B=AsDefined, C=Opposite, D=Subscribe, E=Redeem, F=Lend, G=Borrow, H=SellUndisclosed)",
557
- required: true
558
- },
559
- {
560
- name: "symbol",
561
- description: "Trading symbol",
562
- required: true
563
- },
564
- {
565
- name: "timeInForce",
566
- description: "Time in force",
567
- required: false
568
- }
569
- ]
570
- },
571
- {
572
- name: "marketDataRequest",
573
- description: "Sends a request for Market Data with the given symbol",
574
- arguments: [
575
- {
576
- name: "mdUpdateType",
577
- description: "Market data update type",
578
- required: false
579
- },
580
- {
581
- name: "symbol",
582
- description: "Trading symbol",
583
- required: true
584
- },
585
- {
586
- name: "mdReqID",
587
- description: "Market data request ID",
588
- required: true
589
- },
590
- {
591
- name: "subscriptionRequestType",
592
- description: "Subscription request type",
593
- required: false
594
- },
595
- {
596
- name: "mdEntryType",
597
- description: "Market data entry type",
598
- required: false
599
- }
600
- ]
601
- }
602
- ]
603
- };
604
- });
605
- this.server.setRequestHandler(GetPromptRequestSchema, async (request) => {
606
- const { name, arguments: args } = request.params;
607
- switch (name) {
608
- case "parse": {
609
- const fixString = args?.fixString || "";
265
+ this.parser?.send(order);
266
+ const fixData = await response;
267
+ this.verifiedOrders.delete(args.clOrdID);
610
268
  return {
611
- messages: [
269
+ content: [
612
270
  {
613
- role: "user",
614
- content: {
615
- type: "text",
616
- text: `Please parse and explain this FIX message: ${fixString}`
617
- }
271
+ type: "text",
272
+ 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())}`
618
273
  }
619
274
  ]
620
275
  };
621
- }
622
- case "parseToJSON": {
623
- const fixString = args?.fixString || "";
276
+ } catch (error) {
624
277
  return {
625
- messages: [
278
+ content: [
626
279
  {
627
- role: "user",
628
- content: {
629
- type: "text",
630
- text: `Please parse the FIX message to JSON: ${fixString}`
631
- }
280
+ type: "text",
281
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`
632
282
  }
633
- ]
283
+ ],
284
+ isError: true
634
285
  };
635
286
  }
636
- case "newOrderSingle": {
637
- const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = args || {};
638
- return {
639
- messages: [
640
- {
641
- role: "user",
642
- content: {
287
+ }
288
+ );
289
+ this.server.tool(
290
+ "marketDataRequest",
291
+ "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.",
292
+ {
293
+ mdUpdateType: z.enum(["0", "1"]).describe("Market data update type (0=FullRefresh, 1=IncrementalRefresh)"),
294
+ symbol: z.string().describe("Trading symbol"),
295
+ mdReqID: z.string().describe("Market data request ID"),
296
+ subscriptionRequestType: z.enum(["0", "1", "2"]).describe("Subscription request type (0=Snapshot + Updates, 1=Snapshot, 2=Unsubscribe)"),
297
+ mdEntryType: z.string().describe("Market data entry type (0=Bid, 1=Offer, 2=Trade, etc.)")
298
+ },
299
+ async (args) => {
300
+ try {
301
+ const response = new Promise((resolve) => {
302
+ this.pendingRequests.set(args.mdReqID, resolve);
303
+ });
304
+ const marketDataRequest = this.parser?.createMessage(
305
+ new Field(Fields.MsgType, Messages.MarketDataRequest),
306
+ new Field(Fields.SenderCompID, this.parser?.sender),
307
+ new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
308
+ new Field(Fields.TargetCompID, this.parser?.target),
309
+ new Field(Fields.SendingTime, this.parser?.getTimestamp()),
310
+ new Field(Fields.MarketDepth, 0),
311
+ new Field(Fields.MDUpdateType, args.mdUpdateType),
312
+ new Field(Fields.NoRelatedSym, 1),
313
+ new Field(Fields.Symbol, args.symbol),
314
+ new Field(Fields.MDReqID, args.mdReqID),
315
+ new Field(Fields.SubscriptionRequestType, args.subscriptionRequestType),
316
+ new Field(Fields.NoMDEntryTypes, 1),
317
+ new Field(Fields.MDEntryType, args.mdEntryType)
318
+ );
319
+ if (!this.parser?.connected) {
320
+ return {
321
+ content: [
322
+ {
643
323
  type: "text",
644
- text: [
645
- "Create a New Order Single FIX message with the following parameters:",
646
- `- ClOrdID: ${clOrdID}`,
647
- `- HandlInst: ${handlInst ?? "3"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '1' for Manual, '2' for Automated, '3' for AutomatedNoIntervention)`,
648
- `- Quantity: ${quantity}`,
649
- `- Price: ${price}`,
650
- `- OrdType: ${ordType ?? "1"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '1' for Market, '2' for Limit, '3' for Stop)`,
651
- `- Side: ${side} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '1' for Buy, '2' for Sell)`,
652
- `- Symbol: ${symbol}`,
653
- `- TimeInForce: ${timeInForce ?? "0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for Day, '1' for Good Till Cancel, '2' for At Opening, '3' for Immediate or Cancel, '4' for Fill or Kill, '5' for Good Till Crossing, '6' for Good Till Date)`,
654
- "",
655
- "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values.",
656
- "",
657
- 'Note: For the Side parameter, always use the numeric/alphabetic value (e.g., "1" for Buy, "2" for Sell) as defined in the FIX protocol, not the descriptive name.',
658
- 'Note: For the HandlInst parameter, always use the numeric/alphabetic value (e.g., "1" for Manual, "2" for Automated, "3" for AutomatedNoIntervention) as defined in the FIX protocol, not the descriptive name.',
659
- 'Note: For the OrdType parameter, always use the numeric/alphabetic value (e.g., "1" for Market, "2" for Limit, "3" for Stop) as defined in the FIX protocol, not the descriptive name.',
660
- 'Note: For the TimeInForce parameter, always use the numeric/alphabetic value (e.g., "0" for Day, "1" for Good Till Cancel, "2" for At Opening) as defined in the FIX protocol, not the descriptive name.'
661
- ].join("\n")
324
+ text: "Error: Not connected. Ignoring message."
662
325
  }
326
+ ],
327
+ isError: true
328
+ };
329
+ }
330
+ this.parser?.send(marketDataRequest);
331
+ const fixData = await response;
332
+ return {
333
+ content: [
334
+ {
335
+ type: "text",
336
+ text: `Market data for ${args.symbol}: ${JSON.stringify(fixData.toFIXJSON())}`
663
337
  }
664
338
  ]
665
339
  };
666
- }
667
- case "marketDataRequest": {
668
- const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = args || {};
340
+ } catch (error) {
669
341
  return {
670
- messages: [
342
+ content: [
671
343
  {
672
- role: "user",
673
- content: {
674
- type: "text",
675
- text: [
676
- "Create a Market Data Request FIX message with the following parameters:",
677
- `- MDUpdateType: ${mdUpdateType ?? "0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for FullRefresh, '1' for IncrementalRefresh)`,
678
- `- Symbol: ${symbol}`,
679
- `- MDReqID: ${mdReqID}`,
680
- `- SubscriptionRequestType: ${subscriptionRequestType ?? "0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for Snapshot + Updates, '1' for Snapshot, '2' for Unsubscribe)`,
681
- `- MDEntryType: ${mdEntryType ?? "0"} (IMPORTANT: Use the numeric/alphabetic value, not the descriptive name. For example, use '0' for Bid, '1' for Offer, '2' for Trade, '3' for Index Value, '4' for Opening Price)`,
682
- "",
683
- "Format the response as a JSON object with FIX tag numbers as keys and their corresponding values.",
684
- "",
685
- 'Note: For the MDUpdateType parameter, always use the numeric/alphabetic value (e.g., "0" for FullRefresh, "1" for IncrementalRefresh) as defined in the FIX protocol, not the descriptive name.',
686
- 'Note: For the SubscriptionRequestType parameter, always use the numeric/alphabetic value (e.g., "0" for Snapshot + Updates, "1" for Snapshot, "2" for Unsubscribe) as defined in the FIX protocol, not the descriptive name.',
687
- 'Note: For the MDEntryType parameter, always use the numeric/alphabetic value (e.g., "0" for Bid, "1" for Offer, "2" for Trade, "3" for Index Value, "4" for Opening Price) as defined in the FIX protocol, not the descriptive name.'
688
- ].join("\n")
689
- }
344
+ type: "text",
345
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`
690
346
  }
691
- ]
347
+ ],
348
+ isError: true
692
349
  };
693
350
  }
694
- default:
695
- throw new Error(`Unknown prompt: ${name}`);
696
351
  }
697
- });
352
+ );
353
+ this.server.prompt(
354
+ "parse",
355
+ "Parses a FIX message and describes it in plain language",
356
+ {
357
+ fixString: z.string().describe("FIX message string to parse")
358
+ },
359
+ async (args) => {
360
+ return {
361
+ messages: [
362
+ {
363
+ role: "user",
364
+ content: {
365
+ type: "text",
366
+ text: `Please parse and explain this FIX message: ${args.fixString}`
367
+ }
368
+ }
369
+ ]
370
+ };
371
+ }
372
+ );
373
+ this.server.prompt(
374
+ "parseToJSON",
375
+ "Parses a FIX message into JSON",
376
+ {
377
+ fixString: z.string().describe("FIX message string to parse")
378
+ },
379
+ async (args) => {
380
+ return {
381
+ messages: [
382
+ {
383
+ role: "user",
384
+ content: {
385
+ type: "text",
386
+ text: `Please parse the FIX message to JSON: ${args.fixString}`
387
+ }
388
+ }
389
+ ]
390
+ };
391
+ }
392
+ );
393
+ this.server.prompt(
394
+ "verifyOrder",
395
+ "Verifies all parameters for a New Order Single. This is the first step - verification only, no order is sent.",
396
+ {
397
+ clOrdID: z.string().describe("Client Order ID"),
398
+ handlInst: z.enum(["1", "2", "3"]).describe("Handling instruction (1=Manual, 2=Automated, 3=AutomatedNoIntervention)"),
399
+ quantity: z.string().describe("Order quantity"),
400
+ price: z.string().describe("Order price"),
401
+ ordType: z.string().describe("Order type (1=Market, 2=Limit, 3=Stop)"),
402
+ side: z.string().describe("Order side (1=Buy, 2=Sell, etc.)"),
403
+ symbol: z.string().describe("Trading symbol"),
404
+ timeInForce: z.string().describe("Time in force (0=Day, 1=Good Till Cancel, etc.)")
405
+ },
406
+ async (args) => {
407
+ return {
408
+ messages: [
409
+ {
410
+ role: "user",
411
+ content: {
412
+ type: "text",
413
+ text: [
414
+ "You are an AI assistant that helps users verify FIX New Order Single parameters.",
415
+ "This is STEP 1 of 2 - VERIFICATION ONLY. No order will be sent at this stage.",
416
+ "",
417
+ "You must verify that all required fields are provided and valid:",
418
+ "- ClOrdID (Client Order ID)",
419
+ "- HandlInst (1=Manual, 2=Automated, 3=AutomatedNoIntervention)",
420
+ "- Quantity (Order quantity)",
421
+ "- Price (Order price)",
422
+ "- OrdType (1=Market, 2=Limit, 3=Stop)",
423
+ "- 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)",
424
+ "- Symbol (Trading symbol)",
425
+ "- TimeInForce (0=Day, 1=Good Till Cancel, 2=At Opening, 3=Immediate or Cancel, 4=Fill or Kill, 5=Good Till Crossing, 6=Good Till Date)",
426
+ "",
427
+ "Current parameters to verify:",
428
+ `- ClOrdID: ${args.clOrdID}`,
429
+ `- HandlInst: ${args.handlInst}`,
430
+ `- Quantity: ${args.quantity}`,
431
+ `- Price: ${args.price}`,
432
+ `- OrdType: ${args.ordType}`,
433
+ `- Side: ${args.side}`,
434
+ `- Symbol: ${args.symbol}`,
435
+ `- TimeInForce: ${args.timeInForce}`,
436
+ "",
437
+ "If all parameters are valid, respond with:",
438
+ "`VERIFICATION: All parameters valid. Ready to proceed.`",
439
+ "",
440
+ "Otherwise, list the missing or invalid ones.",
441
+ "",
442
+ "IMPORTANT: This is only verification. To actually send the order, the user must call the executeOrder tool with the same parameters."
443
+ ].join("\n")
444
+ }
445
+ }
446
+ ]
447
+ };
448
+ }
449
+ );
450
+ this.server.prompt(
451
+ "executeOrder",
452
+ "Executes a New Order Single after verification. This is the second step - only call after successful verification.",
453
+ {
454
+ clOrdID: z.string().describe("Client Order ID"),
455
+ handlInst: z.enum(["1", "2", "3"]).describe("Handling instruction (1=Manual, 2=Automated, 3=AutomatedNoIntervention)"),
456
+ quantity: z.string().describe("Order quantity"),
457
+ price: z.string().describe("Order price"),
458
+ ordType: z.string().describe("Order type (1=Market, 2=Limit, 3=Stop)"),
459
+ side: z.string().describe("Order side (1=Buy, 2=Sell, etc.)"),
460
+ symbol: z.string().describe("Trading symbol"),
461
+ timeInForce: z.string().describe("Time in force (0=Day, 1=Good Till Cancel, etc.)")
462
+ },
463
+ async (args) => {
464
+ return {
465
+ messages: [
466
+ {
467
+ role: "user",
468
+ content: {
469
+ type: "text",
470
+ text: [
471
+ "You are an AI assistant that helps users execute FIX New Order Single messages.",
472
+ "This is STEP 2 of 2 - EXECUTION. This will send the order to the market.",
473
+ "",
474
+ "IMPORTANT: This tool should only be called after successful verification of all parameters.",
475
+ "",
476
+ "Parameters to execute:",
477
+ `- ClOrdID: ${args.clOrdID}`,
478
+ `- HandlInst: ${args.handlInst}`,
479
+ `- Quantity: ${args.quantity}`,
480
+ `- Price: ${args.price}`,
481
+ `- OrdType: ${args.ordType}`,
482
+ `- Side: ${args.side}`,
483
+ `- Symbol: ${args.symbol}`,
484
+ `- TimeInForce: ${args.timeInForce}`,
485
+ "",
486
+ "IMPORTANT: The response will be either:",
487
+ "1. An Execution Report (MsgType=8) if the order was successfully placed",
488
+ "2. A Reject message (MsgType=3) if the order failed to execute (e.g., due to missing or invalid parameters)"
489
+ ].join("\n")
490
+ }
491
+ }
492
+ ]
493
+ };
494
+ }
495
+ );
496
+ this.server.prompt(
497
+ "marketDataRequest",
498
+ "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.",
499
+ {
500
+ mdUpdateType: z.enum(["0", "1"]).describe("Market data update type (0=FullRefresh, 1=IncrementalRefresh)"),
501
+ symbol: z.string().describe("Trading symbol"),
502
+ mdReqID: z.string().describe("Market data request ID"),
503
+ subscriptionRequestType: z.enum(["0", "1", "2"]).describe("Subscription request type (0=Snapshot + Updates, 1=Snapshot, 2=Unsubscribe)"),
504
+ mdEntryType: z.string().describe("Market data entry type (0=Bid, 1=Offer, 2=Trade, etc.)")
505
+ },
506
+ async (args) => {
507
+ return {
508
+ messages: [
509
+ {
510
+ role: "user",
511
+ content: {
512
+ type: "text",
513
+ text: [
514
+ "You are an AI assistant that helps users create FIX Market Data Request messages.",
515
+ "You must **first verify** that all required fields are provided:",
516
+ "- MDUpdateType (0=FullRefresh, 1=IncrementalRefresh)",
517
+ "- Symbol (Trading symbol)",
518
+ "- MDReqID (Market data request ID)",
519
+ "- SubscriptionRequestType (0=Snapshot + Updates, 1=Snapshot, 2=Unsubscribe)",
520
+ "- MDEntryType (0=Bid, 1=Offer, 2=Trade, 3=Index Value, 4=Opening Price)",
521
+ "",
522
+ "Only when all fields are present and valid, respond with:",
523
+ "`VERIFICATION: All parameters valid. Ready to proceed.`",
524
+ "",
525
+ "Otherwise, list the missing or invalid ones.",
526
+ "",
527
+ "Do not create the FIX message until verification is complete.",
528
+ "",
529
+ "Current parameters:",
530
+ `- MDUpdateType: ${args.mdUpdateType}`,
531
+ `- Symbol: ${args.symbol}`,
532
+ `- MDReqID: ${args.mdReqID}`,
533
+ `- SubscriptionRequestType: ${args.subscriptionRequestType}`,
534
+ `- MDEntryType: ${args.mdEntryType}`
535
+ ].join("\n")
536
+ }
537
+ }
538
+ ]
539
+ };
540
+ }
541
+ );
542
+ this.server.resource(
543
+ "stockGraph",
544
+ new ResourceTemplate("stock://{symbol}", { list: void 0 }),
545
+ async (uri, variables) => {
546
+ const symbol = variables.symbol;
547
+ const data = [
548
+ { time: "09:30", price: 150 },
549
+ { time: "10:30", price: 152.5 },
550
+ { time: "11:30", price: 151.75 },
551
+ { time: "12:30", price: 153.25 },
552
+ { time: "13:30", price: 154 },
553
+ { time: "14:30", price: 153.5 },
554
+ { time: "15:30", price: 155 },
555
+ { time: "16:00", price: 154.75 }
556
+ ];
557
+ const width = 600;
558
+ const height = 300;
559
+ const padding = 40;
560
+ const xScale = (width - 2 * padding) / (data.length - 1);
561
+ const yMin = Math.min(...data.map((d) => d.price));
562
+ const yMax = Math.max(...data.map((d) => d.price));
563
+ const yScale = (height - 2 * padding) / (yMax - yMin);
564
+ const points = data.map((d, i) => {
565
+ const x = padding + i * xScale;
566
+ const y = height - padding - (d.price - yMin) * yScale;
567
+ return `${x},${y}`;
568
+ }).join(" L ");
569
+ const svg = `<?xml version="1.0" encoding="UTF-8"?>
570
+ <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
571
+ <!-- Background -->
572
+ <rect width="100%" height="100%" fill="#f8f9fa"/>
573
+
574
+ <!-- Grid lines -->
575
+ <g stroke="#e9ecef" stroke-width="1">
576
+ ${Array.from({ length: 5 }, (_, i) => {
577
+ const y = padding + (height - 2 * padding) * i / 4;
578
+ return `<line x1="${padding}" y1="${y}" x2="${width - padding}" y2="${y}"/>`;
579
+ }).join("\n")}
580
+ </g>
581
+
582
+ <!-- Price line -->
583
+ <path d="M ${points}"
584
+ fill="none"
585
+ stroke="#007bff"
586
+ stroke-width="2"/>
587
+
588
+ <!-- Data points -->
589
+ ${data.map((d, i) => {
590
+ const x = padding + i * xScale;
591
+ const y = height - padding - (d.price - yMin) * yScale;
592
+ return `<circle cx="${x}" cy="${y}" r="3" fill="#007bff"/>`;
593
+ }).join("\n")}
594
+
595
+ <!-- Labels -->
596
+ <g font-family="Arial" font-size="12" fill="#495057">
597
+ ${data.map((d, i) => {
598
+ const x = padding + i * xScale;
599
+ return `<text x="${x}" y="${height - padding + 20}" text-anchor="middle">${d.time}</text>`;
600
+ }).join("\n")}
601
+ ${Array.from({ length: 5 }, (_, i) => {
602
+ const y = padding + (height - 2 * padding) * i / 4;
603
+ const price = yMax - (yMax - yMin) * i / 4;
604
+ return `<text x="${padding - 5}" y="${y + 4}" text-anchor="end">$${price.toFixed(2)}</text>`;
605
+ }).join("\n")}
606
+ </g>
607
+
608
+ <!-- Title -->
609
+ <text x="${width / 2}" y="${padding / 2}"
610
+ font-family="Arial" font-size="16" font-weight="bold"
611
+ text-anchor="middle" fill="#212529">
612
+ ${symbol} - 1 Day Price Chart
613
+ </text>
614
+ </svg>`;
615
+ return {
616
+ contents: [
617
+ {
618
+ uri: uri.href,
619
+ text: svg
620
+ }
621
+ ]
622
+ };
623
+ }
624
+ );
698
625
  process.on("SIGINT", async () => {
699
626
  await this.server.close();
700
627
  process.exit(0);