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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1281 +1,9 @@
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 {
5
- CallToolRequestSchema,
6
- ListToolsRequestSchema
7
- } from "@modelcontextprotocol/sdk/types.js";
4
+ import { Field, Fields, Messages } from "fixparser";
8
5
  import { z } from "zod";
9
-
10
- // ../../node_modules/zod-to-json-schema/dist/esm/Options.js
11
- var ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use");
12
- var defaultOptions = {
13
- name: void 0,
14
- $refStrategy: "root",
15
- basePath: ["#"],
16
- effectStrategy: "input",
17
- pipeStrategy: "all",
18
- dateStrategy: "format:date-time",
19
- mapStrategy: "entries",
20
- removeAdditionalStrategy: "passthrough",
21
- allowedAdditionalProperties: true,
22
- rejectedAdditionalProperties: false,
23
- definitionPath: "definitions",
24
- target: "jsonSchema7",
25
- strictUnions: false,
26
- definitions: {},
27
- errorMessages: false,
28
- markdownDescription: false,
29
- patternStrategy: "escape",
30
- applyRegexFlags: false,
31
- emailStrategy: "format:email",
32
- base64Strategy: "contentEncoding:base64",
33
- nameStrategy: "ref"
34
- };
35
- var getDefaultOptions = (options) => typeof options === "string" ? {
36
- ...defaultOptions,
37
- name: options
38
- } : {
39
- ...defaultOptions,
40
- ...options
41
- };
42
-
43
- // ../../node_modules/zod-to-json-schema/dist/esm/Refs.js
44
- var getRefs = (options) => {
45
- const _options = getDefaultOptions(options);
46
- const currentPath = _options.name !== void 0 ? [..._options.basePath, _options.definitionPath, _options.name] : _options.basePath;
47
- return {
48
- ..._options,
49
- currentPath,
50
- propertyPath: void 0,
51
- seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [
52
- def._def,
53
- {
54
- def: def._def,
55
- path: [..._options.basePath, _options.definitionPath, name],
56
- // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
57
- jsonSchema: void 0
58
- }
59
- ]))
60
- };
61
- };
62
-
63
- // ../../node_modules/zod-to-json-schema/dist/esm/errorMessages.js
64
- function addErrorMessage(res, key, errorMessage, refs) {
65
- if (!refs?.errorMessages)
66
- return;
67
- if (errorMessage) {
68
- res.errorMessage = {
69
- ...res.errorMessage,
70
- [key]: errorMessage
71
- };
72
- }
73
- }
74
- function setResponseValueAndErrors(res, key, value, errorMessage, refs) {
75
- res[key] = value;
76
- addErrorMessage(res, key, errorMessage, refs);
77
- }
78
-
79
- // ../../node_modules/zod-to-json-schema/dist/esm/selectParser.js
80
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind3 } from "zod";
81
-
82
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/any.js
83
- function parseAnyDef() {
84
- return {};
85
- }
86
-
87
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/array.js
88
- import { ZodFirstPartyTypeKind } from "zod";
89
- function parseArrayDef(def, refs) {
90
- const res = {
91
- type: "array"
92
- };
93
- if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) {
94
- res.items = parseDef(def.type._def, {
95
- ...refs,
96
- currentPath: [...refs.currentPath, "items"]
97
- });
98
- }
99
- if (def.minLength) {
100
- setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs);
101
- }
102
- if (def.maxLength) {
103
- setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs);
104
- }
105
- if (def.exactLength) {
106
- setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs);
107
- setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs);
108
- }
109
- return res;
110
- }
111
-
112
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/bigint.js
113
- function parseBigintDef(def, refs) {
114
- const res = {
115
- type: "integer",
116
- format: "int64"
117
- };
118
- if (!def.checks)
119
- return res;
120
- for (const check of def.checks) {
121
- switch (check.kind) {
122
- case "min":
123
- if (refs.target === "jsonSchema7") {
124
- if (check.inclusive) {
125
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
126
- } else {
127
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
128
- }
129
- } else {
130
- if (!check.inclusive) {
131
- res.exclusiveMinimum = true;
132
- }
133
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
134
- }
135
- break;
136
- case "max":
137
- if (refs.target === "jsonSchema7") {
138
- if (check.inclusive) {
139
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
140
- } else {
141
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
142
- }
143
- } else {
144
- if (!check.inclusive) {
145
- res.exclusiveMaximum = true;
146
- }
147
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
148
- }
149
- break;
150
- case "multipleOf":
151
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
152
- break;
153
- }
154
- }
155
- return res;
156
- }
157
-
158
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/boolean.js
159
- function parseBooleanDef() {
160
- return {
161
- type: "boolean"
162
- };
163
- }
164
-
165
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/branded.js
166
- function parseBrandedDef(_def, refs) {
167
- return parseDef(_def.type._def, refs);
168
- }
169
-
170
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/catch.js
171
- var parseCatchDef = (def, refs) => {
172
- return parseDef(def.innerType._def, refs);
173
- };
174
-
175
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/date.js
176
- function parseDateDef(def, refs, overrideDateStrategy) {
177
- const strategy = overrideDateStrategy ?? refs.dateStrategy;
178
- if (Array.isArray(strategy)) {
179
- return {
180
- anyOf: strategy.map((item, i) => parseDateDef(def, refs, item))
181
- };
182
- }
183
- switch (strategy) {
184
- case "string":
185
- case "format:date-time":
186
- return {
187
- type: "string",
188
- format: "date-time"
189
- };
190
- case "format:date":
191
- return {
192
- type: "string",
193
- format: "date"
194
- };
195
- case "integer":
196
- return integerDateParser(def, refs);
197
- }
198
- }
199
- var integerDateParser = (def, refs) => {
200
- const res = {
201
- type: "integer",
202
- format: "unix-time"
203
- };
204
- if (refs.target === "openApi3") {
205
- return res;
206
- }
207
- for (const check of def.checks) {
208
- switch (check.kind) {
209
- case "min":
210
- setResponseValueAndErrors(
211
- res,
212
- "minimum",
213
- check.value,
214
- // This is in milliseconds
215
- check.message,
216
- refs
217
- );
218
- break;
219
- case "max":
220
- setResponseValueAndErrors(
221
- res,
222
- "maximum",
223
- check.value,
224
- // This is in milliseconds
225
- check.message,
226
- refs
227
- );
228
- break;
229
- }
230
- }
231
- return res;
232
- };
233
-
234
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/default.js
235
- function parseDefaultDef(_def, refs) {
236
- return {
237
- ...parseDef(_def.innerType._def, refs),
238
- default: _def.defaultValue()
239
- };
240
- }
241
-
242
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/effects.js
243
- function parseEffectsDef(_def, refs) {
244
- return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : {};
245
- }
246
-
247
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/enum.js
248
- function parseEnumDef(def) {
249
- return {
250
- type: "string",
251
- enum: Array.from(def.values)
252
- };
253
- }
254
-
255
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/intersection.js
256
- var isJsonSchema7AllOfType = (type) => {
257
- if ("type" in type && type.type === "string")
258
- return false;
259
- return "allOf" in type;
260
- };
261
- function parseIntersectionDef(def, refs) {
262
- const allOf = [
263
- parseDef(def.left._def, {
264
- ...refs,
265
- currentPath: [...refs.currentPath, "allOf", "0"]
266
- }),
267
- parseDef(def.right._def, {
268
- ...refs,
269
- currentPath: [...refs.currentPath, "allOf", "1"]
270
- })
271
- ].filter((x) => !!x);
272
- let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0;
273
- const mergedAllOf = [];
274
- allOf.forEach((schema) => {
275
- if (isJsonSchema7AllOfType(schema)) {
276
- mergedAllOf.push(...schema.allOf);
277
- if (schema.unevaluatedProperties === void 0) {
278
- unevaluatedProperties = void 0;
279
- }
280
- } else {
281
- let nestedSchema = schema;
282
- if ("additionalProperties" in schema && schema.additionalProperties === false) {
283
- const { additionalProperties, ...rest } = schema;
284
- nestedSchema = rest;
285
- } else {
286
- unevaluatedProperties = void 0;
287
- }
288
- mergedAllOf.push(nestedSchema);
289
- }
290
- });
291
- return mergedAllOf.length ? {
292
- allOf: mergedAllOf,
293
- ...unevaluatedProperties
294
- } : void 0;
295
- }
296
-
297
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/literal.js
298
- function parseLiteralDef(def, refs) {
299
- const parsedType = typeof def.value;
300
- if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") {
301
- return {
302
- type: Array.isArray(def.value) ? "array" : "object"
303
- };
304
- }
305
- if (refs.target === "openApi3") {
306
- return {
307
- type: parsedType === "bigint" ? "integer" : parsedType,
308
- enum: [def.value]
309
- };
310
- }
311
- return {
312
- type: parsedType === "bigint" ? "integer" : parsedType,
313
- const: def.value
314
- };
315
- }
316
-
317
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/record.js
318
- import { ZodFirstPartyTypeKind as ZodFirstPartyTypeKind2 } from "zod";
319
-
320
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/string.js
321
- var emojiRegex = void 0;
322
- var zodPatterns = {
323
- /**
324
- * `c` was changed to `[cC]` to replicate /i flag
325
- */
326
- cuid: /^[cC][^\s-]{8,}$/,
327
- cuid2: /^[0-9a-z]+$/,
328
- ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
329
- /**
330
- * `a-z` was added to replicate /i flag
331
- */
332
- email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
333
- /**
334
- * Constructed a valid Unicode RegExp
335
- *
336
- * Lazily instantiate since this type of regex isn't supported
337
- * in all envs (e.g. React Native).
338
- *
339
- * See:
340
- * https://github.com/colinhacks/zod/issues/2433
341
- * Fix in Zod:
342
- * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
343
- */
344
- emoji: () => {
345
- if (emojiRegex === void 0) {
346
- emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
347
- }
348
- return emojiRegex;
349
- },
350
- /**
351
- * Unused
352
- */
353
- uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
354
- /**
355
- * Unused
356
- */
357
- ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
358
- ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
359
- /**
360
- * Unused
361
- */
362
- ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
363
- ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
364
- base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
365
- base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
366
- nanoid: /^[a-zA-Z0-9_-]{21}$/,
367
- jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
368
- };
369
- function parseStringDef(def, refs) {
370
- const res = {
371
- type: "string"
372
- };
373
- if (def.checks) {
374
- for (const check of def.checks) {
375
- switch (check.kind) {
376
- case "min":
377
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
378
- break;
379
- case "max":
380
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
381
- break;
382
- case "email":
383
- switch (refs.emailStrategy) {
384
- case "format:email":
385
- addFormat(res, "email", check.message, refs);
386
- break;
387
- case "format:idn-email":
388
- addFormat(res, "idn-email", check.message, refs);
389
- break;
390
- case "pattern:zod":
391
- addPattern(res, zodPatterns.email, check.message, refs);
392
- break;
393
- }
394
- break;
395
- case "url":
396
- addFormat(res, "uri", check.message, refs);
397
- break;
398
- case "uuid":
399
- addFormat(res, "uuid", check.message, refs);
400
- break;
401
- case "regex":
402
- addPattern(res, check.regex, check.message, refs);
403
- break;
404
- case "cuid":
405
- addPattern(res, zodPatterns.cuid, check.message, refs);
406
- break;
407
- case "cuid2":
408
- addPattern(res, zodPatterns.cuid2, check.message, refs);
409
- break;
410
- case "startsWith":
411
- addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs);
412
- break;
413
- case "endsWith":
414
- addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs);
415
- break;
416
- case "datetime":
417
- addFormat(res, "date-time", check.message, refs);
418
- break;
419
- case "date":
420
- addFormat(res, "date", check.message, refs);
421
- break;
422
- case "time":
423
- addFormat(res, "time", check.message, refs);
424
- break;
425
- case "duration":
426
- addFormat(res, "duration", check.message, refs);
427
- break;
428
- case "length":
429
- setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs);
430
- setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs);
431
- break;
432
- case "includes": {
433
- addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs);
434
- break;
435
- }
436
- case "ip": {
437
- if (check.version !== "v6") {
438
- addFormat(res, "ipv4", check.message, refs);
439
- }
440
- if (check.version !== "v4") {
441
- addFormat(res, "ipv6", check.message, refs);
442
- }
443
- break;
444
- }
445
- case "base64url":
446
- addPattern(res, zodPatterns.base64url, check.message, refs);
447
- break;
448
- case "jwt":
449
- addPattern(res, zodPatterns.jwt, check.message, refs);
450
- break;
451
- case "cidr": {
452
- if (check.version !== "v6") {
453
- addPattern(res, zodPatterns.ipv4Cidr, check.message, refs);
454
- }
455
- if (check.version !== "v4") {
456
- addPattern(res, zodPatterns.ipv6Cidr, check.message, refs);
457
- }
458
- break;
459
- }
460
- case "emoji":
461
- addPattern(res, zodPatterns.emoji(), check.message, refs);
462
- break;
463
- case "ulid": {
464
- addPattern(res, zodPatterns.ulid, check.message, refs);
465
- break;
466
- }
467
- case "base64": {
468
- switch (refs.base64Strategy) {
469
- case "format:binary": {
470
- addFormat(res, "binary", check.message, refs);
471
- break;
472
- }
473
- case "contentEncoding:base64": {
474
- setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs);
475
- break;
476
- }
477
- case "pattern:zod": {
478
- addPattern(res, zodPatterns.base64, check.message, refs);
479
- break;
480
- }
481
- }
482
- break;
483
- }
484
- case "nanoid": {
485
- addPattern(res, zodPatterns.nanoid, check.message, refs);
486
- }
487
- case "toLowerCase":
488
- case "toUpperCase":
489
- case "trim":
490
- break;
491
- default:
492
- /* @__PURE__ */ ((_) => {
493
- })(check);
494
- }
495
- }
496
- }
497
- return res;
498
- }
499
- function escapeLiteralCheckValue(literal, refs) {
500
- return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal;
501
- }
502
- var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
503
- function escapeNonAlphaNumeric(source) {
504
- let result = "";
505
- for (let i = 0; i < source.length; i++) {
506
- if (!ALPHA_NUMERIC.has(source[i])) {
507
- result += "\\";
508
- }
509
- result += source[i];
510
- }
511
- return result;
512
- }
513
- function addFormat(schema, value, message, refs) {
514
- if (schema.format || schema.anyOf?.some((x) => x.format)) {
515
- if (!schema.anyOf) {
516
- schema.anyOf = [];
517
- }
518
- if (schema.format) {
519
- schema.anyOf.push({
520
- format: schema.format,
521
- ...schema.errorMessage && refs.errorMessages && {
522
- errorMessage: { format: schema.errorMessage.format }
523
- }
524
- });
525
- delete schema.format;
526
- if (schema.errorMessage) {
527
- delete schema.errorMessage.format;
528
- if (Object.keys(schema.errorMessage).length === 0) {
529
- delete schema.errorMessage;
530
- }
531
- }
532
- }
533
- schema.anyOf.push({
534
- format: value,
535
- ...message && refs.errorMessages && { errorMessage: { format: message } }
536
- });
537
- } else {
538
- setResponseValueAndErrors(schema, "format", value, message, refs);
539
- }
540
- }
541
- function addPattern(schema, regex, message, refs) {
542
- if (schema.pattern || schema.allOf?.some((x) => x.pattern)) {
543
- if (!schema.allOf) {
544
- schema.allOf = [];
545
- }
546
- if (schema.pattern) {
547
- schema.allOf.push({
548
- pattern: schema.pattern,
549
- ...schema.errorMessage && refs.errorMessages && {
550
- errorMessage: { pattern: schema.errorMessage.pattern }
551
- }
552
- });
553
- delete schema.pattern;
554
- if (schema.errorMessage) {
555
- delete schema.errorMessage.pattern;
556
- if (Object.keys(schema.errorMessage).length === 0) {
557
- delete schema.errorMessage;
558
- }
559
- }
560
- }
561
- schema.allOf.push({
562
- pattern: stringifyRegExpWithFlags(regex, refs),
563
- ...message && refs.errorMessages && { errorMessage: { pattern: message } }
564
- });
565
- } else {
566
- setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs);
567
- }
568
- }
569
- function stringifyRegExpWithFlags(regex, refs) {
570
- if (!refs.applyRegexFlags || !regex.flags) {
571
- return regex.source;
572
- }
573
- const flags = {
574
- i: regex.flags.includes("i"),
575
- m: regex.flags.includes("m"),
576
- s: regex.flags.includes("s")
577
- // `.` matches newlines
578
- };
579
- const source = flags.i ? regex.source.toLowerCase() : regex.source;
580
- let pattern = "";
581
- let isEscaped = false;
582
- let inCharGroup = false;
583
- let inCharRange = false;
584
- for (let i = 0; i < source.length; i++) {
585
- if (isEscaped) {
586
- pattern += source[i];
587
- isEscaped = false;
588
- continue;
589
- }
590
- if (flags.i) {
591
- if (inCharGroup) {
592
- if (source[i].match(/[a-z]/)) {
593
- if (inCharRange) {
594
- pattern += source[i];
595
- pattern += `${source[i - 2]}-${source[i]}`.toUpperCase();
596
- inCharRange = false;
597
- } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) {
598
- pattern += source[i];
599
- inCharRange = true;
600
- } else {
601
- pattern += `${source[i]}${source[i].toUpperCase()}`;
602
- }
603
- continue;
604
- }
605
- } else if (source[i].match(/[a-z]/)) {
606
- pattern += `[${source[i]}${source[i].toUpperCase()}]`;
607
- continue;
608
- }
609
- }
610
- if (flags.m) {
611
- if (source[i] === "^") {
612
- pattern += `(^|(?<=[\r
613
- ]))`;
614
- continue;
615
- } else if (source[i] === "$") {
616
- pattern += `($|(?=[\r
617
- ]))`;
618
- continue;
619
- }
620
- }
621
- if (flags.s && source[i] === ".") {
622
- pattern += inCharGroup ? `${source[i]}\r
623
- ` : `[${source[i]}\r
624
- ]`;
625
- continue;
626
- }
627
- pattern += source[i];
628
- if (source[i] === "\\") {
629
- isEscaped = true;
630
- } else if (inCharGroup && source[i] === "]") {
631
- inCharGroup = false;
632
- } else if (!inCharGroup && source[i] === "[") {
633
- inCharGroup = true;
634
- }
635
- }
636
- try {
637
- new RegExp(pattern);
638
- } catch {
639
- console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`);
640
- return regex.source;
641
- }
642
- return pattern;
643
- }
644
-
645
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/record.js
646
- function parseRecordDef(def, refs) {
647
- if (refs.target === "openAi") {
648
- console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");
649
- }
650
- if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) {
651
- return {
652
- type: "object",
653
- required: def.keyType._def.values,
654
- properties: def.keyType._def.values.reduce((acc, key) => ({
655
- ...acc,
656
- [key]: parseDef(def.valueType._def, {
657
- ...refs,
658
- currentPath: [...refs.currentPath, "properties", key]
659
- }) ?? {}
660
- }), {}),
661
- additionalProperties: refs.rejectedAdditionalProperties
662
- };
663
- }
664
- const schema = {
665
- type: "object",
666
- additionalProperties: parseDef(def.valueType._def, {
667
- ...refs,
668
- currentPath: [...refs.currentPath, "additionalProperties"]
669
- }) ?? refs.allowedAdditionalProperties
670
- };
671
- if (refs.target === "openApi3") {
672
- return schema;
673
- }
674
- if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.checks?.length) {
675
- const { type, ...keyType } = parseStringDef(def.keyType._def, refs);
676
- return {
677
- ...schema,
678
- propertyNames: keyType
679
- };
680
- } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodEnum) {
681
- return {
682
- ...schema,
683
- propertyNames: {
684
- enum: def.keyType._def.values
685
- }
686
- };
687
- } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind2.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind2.ZodString && def.keyType._def.type._def.checks?.length) {
688
- const { type, ...keyType } = parseBrandedDef(def.keyType._def, refs);
689
- return {
690
- ...schema,
691
- propertyNames: keyType
692
- };
693
- }
694
- return schema;
695
- }
696
-
697
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/map.js
698
- function parseMapDef(def, refs) {
699
- if (refs.mapStrategy === "record") {
700
- return parseRecordDef(def, refs);
701
- }
702
- const keys = parseDef(def.keyType._def, {
703
- ...refs,
704
- currentPath: [...refs.currentPath, "items", "items", "0"]
705
- }) || {};
706
- const values = parseDef(def.valueType._def, {
707
- ...refs,
708
- currentPath: [...refs.currentPath, "items", "items", "1"]
709
- }) || {};
710
- return {
711
- type: "array",
712
- maxItems: 125,
713
- items: {
714
- type: "array",
715
- items: [keys, values],
716
- minItems: 2,
717
- maxItems: 2
718
- }
719
- };
720
- }
721
-
722
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/nativeEnum.js
723
- function parseNativeEnumDef(def) {
724
- const object = def.values;
725
- const actualKeys = Object.keys(def.values).filter((key) => {
726
- return typeof object[object[key]] !== "number";
727
- });
728
- const actualValues = actualKeys.map((key) => object[key]);
729
- const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values)));
730
- return {
731
- type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"],
732
- enum: actualValues
733
- };
734
- }
735
-
736
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/never.js
737
- function parseNeverDef() {
738
- return {
739
- not: {}
740
- };
741
- }
742
-
743
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/null.js
744
- function parseNullDef(refs) {
745
- return refs.target === "openApi3" ? {
746
- enum: ["null"],
747
- nullable: true
748
- } : {
749
- type: "null"
750
- };
751
- }
752
-
753
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/union.js
754
- var primitiveMappings = {
755
- ZodString: "string",
756
- ZodNumber: "number",
757
- ZodBigInt: "integer",
758
- ZodBoolean: "boolean",
759
- ZodNull: "null"
760
- };
761
- function parseUnionDef(def, refs) {
762
- if (refs.target === "openApi3")
763
- return asAnyOf(def, refs);
764
- const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options;
765
- if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) {
766
- const types = options.reduce((types2, x) => {
767
- const type = primitiveMappings[x._def.typeName];
768
- return type && !types2.includes(type) ? [...types2, type] : types2;
769
- }, []);
770
- return {
771
- type: types.length > 1 ? types : types[0]
772
- };
773
- } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) {
774
- const types = options.reduce((acc, x) => {
775
- const type = typeof x._def.value;
776
- switch (type) {
777
- case "string":
778
- case "number":
779
- case "boolean":
780
- return [...acc, type];
781
- case "bigint":
782
- return [...acc, "integer"];
783
- case "object":
784
- if (x._def.value === null)
785
- return [...acc, "null"];
786
- case "symbol":
787
- case "undefined":
788
- case "function":
789
- default:
790
- return acc;
791
- }
792
- }, []);
793
- if (types.length === options.length) {
794
- const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i);
795
- return {
796
- type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0],
797
- enum: options.reduce((acc, x) => {
798
- return acc.includes(x._def.value) ? acc : [...acc, x._def.value];
799
- }, [])
800
- };
801
- }
802
- } else if (options.every((x) => x._def.typeName === "ZodEnum")) {
803
- return {
804
- type: "string",
805
- enum: options.reduce((acc, x) => [
806
- ...acc,
807
- ...x._def.values.filter((x2) => !acc.includes(x2))
808
- ], [])
809
- };
810
- }
811
- return asAnyOf(def, refs);
812
- }
813
- var asAnyOf = (def, refs) => {
814
- const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, {
815
- ...refs,
816
- currentPath: [...refs.currentPath, "anyOf", `${i}`]
817
- })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0));
818
- return anyOf.length ? { anyOf } : void 0;
819
- };
820
-
821
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/nullable.js
822
- function parseNullableDef(def, refs) {
823
- if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) {
824
- if (refs.target === "openApi3") {
825
- return {
826
- type: primitiveMappings[def.innerType._def.typeName],
827
- nullable: true
828
- };
829
- }
830
- return {
831
- type: [
832
- primitiveMappings[def.innerType._def.typeName],
833
- "null"
834
- ]
835
- };
836
- }
837
- if (refs.target === "openApi3") {
838
- const base2 = parseDef(def.innerType._def, {
839
- ...refs,
840
- currentPath: [...refs.currentPath]
841
- });
842
- if (base2 && "$ref" in base2)
843
- return { allOf: [base2], nullable: true };
844
- return base2 && { ...base2, nullable: true };
845
- }
846
- const base = parseDef(def.innerType._def, {
847
- ...refs,
848
- currentPath: [...refs.currentPath, "anyOf", "0"]
849
- });
850
- return base && { anyOf: [base, { type: "null" }] };
851
- }
852
-
853
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/number.js
854
- function parseNumberDef(def, refs) {
855
- const res = {
856
- type: "number"
857
- };
858
- if (!def.checks)
859
- return res;
860
- for (const check of def.checks) {
861
- switch (check.kind) {
862
- case "int":
863
- res.type = "integer";
864
- addErrorMessage(res, "type", check.message, refs);
865
- break;
866
- case "min":
867
- if (refs.target === "jsonSchema7") {
868
- if (check.inclusive) {
869
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
870
- } else {
871
- setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs);
872
- }
873
- } else {
874
- if (!check.inclusive) {
875
- res.exclusiveMinimum = true;
876
- }
877
- setResponseValueAndErrors(res, "minimum", check.value, check.message, refs);
878
- }
879
- break;
880
- case "max":
881
- if (refs.target === "jsonSchema7") {
882
- if (check.inclusive) {
883
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
884
- } else {
885
- setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs);
886
- }
887
- } else {
888
- if (!check.inclusive) {
889
- res.exclusiveMaximum = true;
890
- }
891
- setResponseValueAndErrors(res, "maximum", check.value, check.message, refs);
892
- }
893
- break;
894
- case "multipleOf":
895
- setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs);
896
- break;
897
- }
898
- }
899
- return res;
900
- }
901
-
902
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/object.js
903
- import { ZodOptional } from "zod";
904
- function parseObjectDef(def, refs) {
905
- const forceOptionalIntoNullable = refs.target === "openAi";
906
- const result = {
907
- type: "object",
908
- properties: {}
909
- };
910
- const required = [];
911
- const shape = def.shape();
912
- for (const propName in shape) {
913
- let propDef = shape[propName];
914
- if (propDef === void 0 || propDef._def === void 0) {
915
- continue;
916
- }
917
- let propOptional = safeIsOptional(propDef);
918
- if (propOptional && forceOptionalIntoNullable) {
919
- if (propDef instanceof ZodOptional) {
920
- propDef = propDef._def.innerType;
921
- }
922
- if (!propDef.isNullable()) {
923
- propDef = propDef.nullable();
924
- }
925
- propOptional = false;
926
- }
927
- const parsedDef = parseDef(propDef._def, {
928
- ...refs,
929
- currentPath: [...refs.currentPath, "properties", propName],
930
- propertyPath: [...refs.currentPath, "properties", propName]
931
- });
932
- if (parsedDef === void 0) {
933
- continue;
934
- }
935
- result.properties[propName] = parsedDef;
936
- if (!propOptional) {
937
- required.push(propName);
938
- }
939
- }
940
- if (required.length) {
941
- result.required = required;
942
- }
943
- const additionalProperties = decideAdditionalProperties(def, refs);
944
- if (additionalProperties !== void 0) {
945
- result.additionalProperties = additionalProperties;
946
- }
947
- return result;
948
- }
949
- function decideAdditionalProperties(def, refs) {
950
- if (def.catchall._def.typeName !== "ZodNever") {
951
- return parseDef(def.catchall._def, {
952
- ...refs,
953
- currentPath: [...refs.currentPath, "additionalProperties"]
954
- });
955
- }
956
- switch (def.unknownKeys) {
957
- case "passthrough":
958
- return refs.allowedAdditionalProperties;
959
- case "strict":
960
- return refs.rejectedAdditionalProperties;
961
- case "strip":
962
- return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties;
963
- }
964
- }
965
- function safeIsOptional(schema) {
966
- try {
967
- return schema.isOptional();
968
- } catch {
969
- return true;
970
- }
971
- }
972
-
973
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/optional.js
974
- var parseOptionalDef = (def, refs) => {
975
- if (refs.currentPath.toString() === refs.propertyPath?.toString()) {
976
- return parseDef(def.innerType._def, refs);
977
- }
978
- const innerSchema = parseDef(def.innerType._def, {
979
- ...refs,
980
- currentPath: [...refs.currentPath, "anyOf", "1"]
981
- });
982
- return innerSchema ? {
983
- anyOf: [
984
- {
985
- not: {}
986
- },
987
- innerSchema
988
- ]
989
- } : {};
990
- };
991
-
992
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/pipeline.js
993
- var parsePipelineDef = (def, refs) => {
994
- if (refs.pipeStrategy === "input") {
995
- return parseDef(def.in._def, refs);
996
- } else if (refs.pipeStrategy === "output") {
997
- return parseDef(def.out._def, refs);
998
- }
999
- const a = parseDef(def.in._def, {
1000
- ...refs,
1001
- currentPath: [...refs.currentPath, "allOf", "0"]
1002
- });
1003
- const b = parseDef(def.out._def, {
1004
- ...refs,
1005
- currentPath: [...refs.currentPath, "allOf", a ? "1" : "0"]
1006
- });
1007
- return {
1008
- allOf: [a, b].filter((x) => x !== void 0)
1009
- };
1010
- };
1011
-
1012
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/promise.js
1013
- function parsePromiseDef(def, refs) {
1014
- return parseDef(def.type._def, refs);
1015
- }
1016
-
1017
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/set.js
1018
- function parseSetDef(def, refs) {
1019
- const items = parseDef(def.valueType._def, {
1020
- ...refs,
1021
- currentPath: [...refs.currentPath, "items"]
1022
- });
1023
- const schema = {
1024
- type: "array",
1025
- uniqueItems: true,
1026
- items
1027
- };
1028
- if (def.minSize) {
1029
- setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs);
1030
- }
1031
- if (def.maxSize) {
1032
- setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs);
1033
- }
1034
- return schema;
1035
- }
1036
-
1037
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/tuple.js
1038
- function parseTupleDef(def, refs) {
1039
- if (def.rest) {
1040
- return {
1041
- type: "array",
1042
- minItems: def.items.length,
1043
- items: def.items.map((x, i) => parseDef(x._def, {
1044
- ...refs,
1045
- currentPath: [...refs.currentPath, "items", `${i}`]
1046
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []),
1047
- additionalItems: parseDef(def.rest._def, {
1048
- ...refs,
1049
- currentPath: [...refs.currentPath, "additionalItems"]
1050
- })
1051
- };
1052
- } else {
1053
- return {
1054
- type: "array",
1055
- minItems: def.items.length,
1056
- maxItems: def.items.length,
1057
- items: def.items.map((x, i) => parseDef(x._def, {
1058
- ...refs,
1059
- currentPath: [...refs.currentPath, "items", `${i}`]
1060
- })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], [])
1061
- };
1062
- }
1063
- }
1064
-
1065
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/undefined.js
1066
- function parseUndefinedDef() {
1067
- return {
1068
- not: {}
1069
- };
1070
- }
1071
-
1072
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/unknown.js
1073
- function parseUnknownDef() {
1074
- return {};
1075
- }
1076
-
1077
- // ../../node_modules/zod-to-json-schema/dist/esm/parsers/readonly.js
1078
- var parseReadonlyDef = (def, refs) => {
1079
- return parseDef(def.innerType._def, refs);
1080
- };
1081
-
1082
- // ../../node_modules/zod-to-json-schema/dist/esm/selectParser.js
1083
- var selectParser = (def, typeName, refs) => {
1084
- switch (typeName) {
1085
- case ZodFirstPartyTypeKind3.ZodString:
1086
- return parseStringDef(def, refs);
1087
- case ZodFirstPartyTypeKind3.ZodNumber:
1088
- return parseNumberDef(def, refs);
1089
- case ZodFirstPartyTypeKind3.ZodObject:
1090
- return parseObjectDef(def, refs);
1091
- case ZodFirstPartyTypeKind3.ZodBigInt:
1092
- return parseBigintDef(def, refs);
1093
- case ZodFirstPartyTypeKind3.ZodBoolean:
1094
- return parseBooleanDef();
1095
- case ZodFirstPartyTypeKind3.ZodDate:
1096
- return parseDateDef(def, refs);
1097
- case ZodFirstPartyTypeKind3.ZodUndefined:
1098
- return parseUndefinedDef();
1099
- case ZodFirstPartyTypeKind3.ZodNull:
1100
- return parseNullDef(refs);
1101
- case ZodFirstPartyTypeKind3.ZodArray:
1102
- return parseArrayDef(def, refs);
1103
- case ZodFirstPartyTypeKind3.ZodUnion:
1104
- case ZodFirstPartyTypeKind3.ZodDiscriminatedUnion:
1105
- return parseUnionDef(def, refs);
1106
- case ZodFirstPartyTypeKind3.ZodIntersection:
1107
- return parseIntersectionDef(def, refs);
1108
- case ZodFirstPartyTypeKind3.ZodTuple:
1109
- return parseTupleDef(def, refs);
1110
- case ZodFirstPartyTypeKind3.ZodRecord:
1111
- return parseRecordDef(def, refs);
1112
- case ZodFirstPartyTypeKind3.ZodLiteral:
1113
- return parseLiteralDef(def, refs);
1114
- case ZodFirstPartyTypeKind3.ZodEnum:
1115
- return parseEnumDef(def);
1116
- case ZodFirstPartyTypeKind3.ZodNativeEnum:
1117
- return parseNativeEnumDef(def);
1118
- case ZodFirstPartyTypeKind3.ZodNullable:
1119
- return parseNullableDef(def, refs);
1120
- case ZodFirstPartyTypeKind3.ZodOptional:
1121
- return parseOptionalDef(def, refs);
1122
- case ZodFirstPartyTypeKind3.ZodMap:
1123
- return parseMapDef(def, refs);
1124
- case ZodFirstPartyTypeKind3.ZodSet:
1125
- return parseSetDef(def, refs);
1126
- case ZodFirstPartyTypeKind3.ZodLazy:
1127
- return () => def.getter()._def;
1128
- case ZodFirstPartyTypeKind3.ZodPromise:
1129
- return parsePromiseDef(def, refs);
1130
- case ZodFirstPartyTypeKind3.ZodNaN:
1131
- case ZodFirstPartyTypeKind3.ZodNever:
1132
- return parseNeverDef();
1133
- case ZodFirstPartyTypeKind3.ZodEffects:
1134
- return parseEffectsDef(def, refs);
1135
- case ZodFirstPartyTypeKind3.ZodAny:
1136
- return parseAnyDef();
1137
- case ZodFirstPartyTypeKind3.ZodUnknown:
1138
- return parseUnknownDef();
1139
- case ZodFirstPartyTypeKind3.ZodDefault:
1140
- return parseDefaultDef(def, refs);
1141
- case ZodFirstPartyTypeKind3.ZodBranded:
1142
- return parseBrandedDef(def, refs);
1143
- case ZodFirstPartyTypeKind3.ZodReadonly:
1144
- return parseReadonlyDef(def, refs);
1145
- case ZodFirstPartyTypeKind3.ZodCatch:
1146
- return parseCatchDef(def, refs);
1147
- case ZodFirstPartyTypeKind3.ZodPipeline:
1148
- return parsePipelineDef(def, refs);
1149
- case ZodFirstPartyTypeKind3.ZodFunction:
1150
- case ZodFirstPartyTypeKind3.ZodVoid:
1151
- case ZodFirstPartyTypeKind3.ZodSymbol:
1152
- return void 0;
1153
- default:
1154
- return /* @__PURE__ */ ((_) => void 0)(typeName);
1155
- }
1156
- };
1157
-
1158
- // ../../node_modules/zod-to-json-schema/dist/esm/parseDef.js
1159
- function parseDef(def, refs, forceResolution = false) {
1160
- const seenItem = refs.seen.get(def);
1161
- if (refs.override) {
1162
- const overrideResult = refs.override?.(def, refs, seenItem, forceResolution);
1163
- if (overrideResult !== ignoreOverride) {
1164
- return overrideResult;
1165
- }
1166
- }
1167
- if (seenItem && !forceResolution) {
1168
- const seenSchema = get$ref(seenItem, refs);
1169
- if (seenSchema !== void 0) {
1170
- return seenSchema;
1171
- }
1172
- }
1173
- const newItem = { def, path: refs.currentPath, jsonSchema: void 0 };
1174
- refs.seen.set(def, newItem);
1175
- const jsonSchemaOrGetter = selectParser(def, def.typeName, refs);
1176
- const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter;
1177
- if (jsonSchema) {
1178
- addMeta(def, refs, jsonSchema);
1179
- }
1180
- if (refs.postProcess) {
1181
- const postProcessResult = refs.postProcess(jsonSchema, def, refs);
1182
- newItem.jsonSchema = jsonSchema;
1183
- return postProcessResult;
1184
- }
1185
- newItem.jsonSchema = jsonSchema;
1186
- return jsonSchema;
1187
- }
1188
- var get$ref = (item, refs) => {
1189
- switch (refs.$refStrategy) {
1190
- case "root":
1191
- return { $ref: item.path.join("/") };
1192
- case "relative":
1193
- return { $ref: getRelativePath(refs.currentPath, item.path) };
1194
- case "none":
1195
- case "seen": {
1196
- if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) {
1197
- console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`);
1198
- return {};
1199
- }
1200
- return refs.$refStrategy === "seen" ? {} : void 0;
1201
- }
1202
- }
1203
- };
1204
- var getRelativePath = (pathA, pathB) => {
1205
- let i = 0;
1206
- for (; i < pathA.length && i < pathB.length; i++) {
1207
- if (pathA[i] !== pathB[i])
1208
- break;
1209
- }
1210
- return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/");
1211
- };
1212
- var addMeta = (def, refs, jsonSchema) => {
1213
- if (def.description) {
1214
- jsonSchema.description = def.description;
1215
- if (refs.markdownDescription) {
1216
- jsonSchema.markdownDescription = def.description;
1217
- }
1218
- }
1219
- return jsonSchema;
1220
- };
1221
-
1222
- // ../../node_modules/zod-to-json-schema/dist/esm/zodToJsonSchema.js
1223
- var zodToJsonSchema = (schema, options) => {
1224
- const refs = getRefs(options);
1225
- const definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name2, schema2]) => ({
1226
- ...acc,
1227
- [name2]: parseDef(schema2._def, {
1228
- ...refs,
1229
- currentPath: [...refs.basePath, refs.definitionPath, name2]
1230
- }, true) ?? {}
1231
- }), {}) : void 0;
1232
- const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name;
1233
- const main = parseDef(schema._def, name === void 0 ? refs : {
1234
- ...refs,
1235
- currentPath: [...refs.basePath, refs.definitionPath, name]
1236
- }, false) ?? {};
1237
- const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0;
1238
- if (title !== void 0) {
1239
- main.title = title;
1240
- }
1241
- const combined = name === void 0 ? definitions ? {
1242
- ...main,
1243
- [refs.definitionPath]: definitions
1244
- } : main : {
1245
- $ref: [
1246
- ...refs.$refStrategy === "relative" ? [] : refs.basePath,
1247
- refs.definitionPath,
1248
- name
1249
- ].join("/"),
1250
- [refs.definitionPath]: {
1251
- ...definitions,
1252
- [name]: main
1253
- }
1254
- };
1255
- if (refs.target === "jsonSchema7") {
1256
- combined.$schema = "http://json-schema.org/draft-07/schema#";
1257
- } else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") {
1258
- combined.$schema = "https://json-schema.org/draft/2019-09/schema#";
1259
- }
1260
- if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) {
1261
- console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");
1262
- }
1263
- return combined;
1264
- };
1265
-
1266
- // src/MCPLocal.ts
1267
- import {
1268
- Field,
1269
- Fields,
1270
- HandlInst,
1271
- MDEntryType,
1272
- Messages,
1273
- OrdType,
1274
- SubscriptionRequestType,
1275
- TimeInForce
1276
- } from "fixparser";
1277
6
  var MCPLocal = class {
1278
- logger;
1279
7
  parser;
1280
8
  server = new Server(
1281
9
  {
@@ -1283,39 +11,260 @@ var MCPLocal = class {
1283
11
  version: "1.0.0"
1284
12
  },
1285
13
  {
1286
- capabilities: { tools: {} }
14
+ capabilities: {
15
+ tools: {
16
+ parse: {
17
+ description: "Parses a FIX message and describes it in plain language",
18
+ parameters: {
19
+ type: "object",
20
+ properties: {
21
+ fixString: { type: "string" }
22
+ },
23
+ required: ["fixString"]
24
+ }
25
+ },
26
+ parseToJSON: {
27
+ description: "Parses a FIX message into JSON",
28
+ parameters: {
29
+ type: "object",
30
+ properties: {
31
+ fixString: { type: "string" }
32
+ },
33
+ required: ["fixString"]
34
+ }
35
+ },
36
+ verifyOrder: {
37
+ description: "Verifies order parameters before execution",
38
+ parameters: {
39
+ type: "object",
40
+ properties: {
41
+ clOrdID: { type: "string" },
42
+ handlInst: { type: "string", enum: ["1", "2", "3"] },
43
+ quantity: { type: "string" },
44
+ price: { type: "string" },
45
+ ordType: {
46
+ type: "string",
47
+ enum: [
48
+ "1",
49
+ "2",
50
+ "3",
51
+ "4",
52
+ "5",
53
+ "6",
54
+ "7",
55
+ "8",
56
+ "9",
57
+ "A",
58
+ "B",
59
+ "C",
60
+ "D",
61
+ "E",
62
+ "F",
63
+ "G",
64
+ "H",
65
+ "I",
66
+ "J",
67
+ "K",
68
+ "L",
69
+ "M",
70
+ "P",
71
+ "Q",
72
+ "R",
73
+ "S"
74
+ ]
75
+ },
76
+ side: {
77
+ type: "string",
78
+ enum: [
79
+ "1",
80
+ "2",
81
+ "3",
82
+ "4",
83
+ "5",
84
+ "6",
85
+ "7",
86
+ "8",
87
+ "9",
88
+ "A",
89
+ "B",
90
+ "C",
91
+ "D",
92
+ "E",
93
+ "F",
94
+ "G",
95
+ "H"
96
+ ]
97
+ },
98
+ symbol: { type: "string" },
99
+ timeInForce: {
100
+ type: "string",
101
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"]
102
+ }
103
+ },
104
+ required: [
105
+ "clOrdID",
106
+ "handlInst",
107
+ "quantity",
108
+ "price",
109
+ "ordType",
110
+ "side",
111
+ "symbol",
112
+ "timeInForce"
113
+ ]
114
+ }
115
+ },
116
+ executeOrder: {
117
+ description: "Executes a verified order",
118
+ parameters: {
119
+ type: "object",
120
+ properties: {
121
+ clOrdID: { type: "string" },
122
+ handlInst: { type: "string", enum: ["1", "2", "3"] },
123
+ quantity: { type: "string" },
124
+ price: { type: "string" },
125
+ ordType: { type: "string" },
126
+ side: { type: "string" },
127
+ symbol: { type: "string" },
128
+ timeInForce: { type: "string" }
129
+ },
130
+ required: [
131
+ "clOrdID",
132
+ "handlInst",
133
+ "quantity",
134
+ "price",
135
+ "ordType",
136
+ "side",
137
+ "symbol",
138
+ "timeInForce"
139
+ ]
140
+ }
141
+ },
142
+ marketDataRequest: {
143
+ description: "Requests market data for specified symbols",
144
+ parameters: {
145
+ type: "object",
146
+ properties: {
147
+ mdUpdateType: { type: "string", enum: ["0", "1"] },
148
+ symbols: { type: "array", items: { type: "string" } },
149
+ mdReqID: { type: "string" },
150
+ subscriptionRequestType: { type: "string", enum: ["0", "1", "2"] },
151
+ mdEntryTypes: { type: "array", items: { type: "string" } }
152
+ },
153
+ required: ["mdUpdateType", "symbols", "mdReqID", "subscriptionRequestType", "mdEntryTypes"]
154
+ }
155
+ },
156
+ getStockGraph: {
157
+ description: "Generates a price chart for a given symbol",
158
+ parameters: {
159
+ type: "object",
160
+ properties: {
161
+ symbol: { type: "string" }
162
+ },
163
+ required: ["symbol"]
164
+ }
165
+ },
166
+ getStockPriceHistory: {
167
+ description: "Returns price history for a given symbol",
168
+ parameters: {
169
+ type: "object",
170
+ properties: {
171
+ symbol: { type: "string" }
172
+ },
173
+ required: ["symbol"]
174
+ }
175
+ }
176
+ },
177
+ resources: {
178
+ greeting: {
179
+ description: "A simple greeting resource",
180
+ uri: "greeting-resource"
181
+ },
182
+ stockGraph: {
183
+ description: "Generates a price chart for a given symbol",
184
+ uri: "stockGraph/{symbol}"
185
+ },
186
+ stockPriceHistory: {
187
+ description: "Returns price history for a given symbol",
188
+ uri: "stockPriceHistory/{symbol}"
189
+ }
190
+ }
191
+ }
1287
192
  }
1288
193
  );
1289
194
  transport = new StdioServerTransport();
1290
195
  onReady = void 0;
1291
196
  pendingRequests = /* @__PURE__ */ new Map();
197
+ verifiedOrders = /* @__PURE__ */ new Map();
198
+ // Store market data prices with timestamps
199
+ marketDataPrices = /* @__PURE__ */ new Map();
200
+ MAX_PRICE_HISTORY = 1e5;
201
+ // Maximum number of price points to store per symbol
1292
202
  constructor({ logger, onReady }) {
1293
- if (logger) this.logger = logger;
1294
203
  if (onReady) this.onReady = onReady;
1295
204
  }
1296
205
  async register(parser) {
1297
206
  this.parser = parser;
1298
207
  this.parser.addOnMessageCallback((message) => {
1299
- this.logger?.log({
208
+ this.parser?.logger.log({
1300
209
  level: "info",
1301
- message: `FIXParser (MCP): (${parser.protocol?.toUpperCase()}): << received ${message.description}`
210
+ message: `MCP Server received message: ${message.messageType}: ${message.description}`
1302
211
  });
1303
212
  const msgType = message.messageType;
1304
- if (msgType === Messages.MarketDataSnapshotFullRefresh || msgType === Messages.ExecutionReport) {
1305
- const idField = msgType === Messages.MarketDataSnapshotFullRefresh ? message.getField(Fields.MDReqID) : message.getField(Fields.ClOrdID);
1306
- if (idField) {
1307
- const id = idField.value;
1308
- if (typeof id === "string" || typeof id === "number") {
1309
- const callback = this.pendingRequests.get(String(id));
1310
- if (callback) {
1311
- callback(message);
1312
- this.pendingRequests.delete(String(id));
213
+ if (msgType === Messages.MarketDataSnapshotFullRefresh || msgType === Messages.ExecutionReport || msgType === Messages.Reject || msgType === Messages.MarketDataIncrementalRefresh) {
214
+ this.parser?.logger.log({
215
+ level: "info",
216
+ message: `MCP Server handling message type: ${msgType}`
217
+ });
218
+ let id;
219
+ if (msgType === Messages.MarketDataIncrementalRefresh || msgType === Messages.MarketDataSnapshotFullRefresh) {
220
+ const symbol = message.getField(Fields.Symbol);
221
+ const price = message.getField(Fields.MDEntryPx);
222
+ const timestamp = message.getField(Fields.MDEntryTime)?.value || Date.now();
223
+ if (symbol?.value && price?.value) {
224
+ const symbolStr = String(symbol.value);
225
+ const priceNum = Number(price.value);
226
+ const priceHistory = this.marketDataPrices.get(symbolStr) || [];
227
+ priceHistory.push({
228
+ timestamp: Number(timestamp),
229
+ price: priceNum
230
+ });
231
+ if (priceHistory.length > this.MAX_PRICE_HISTORY) {
232
+ priceHistory.shift();
1313
233
  }
234
+ this.marketDataPrices.set(symbolStr, priceHistory);
235
+ this.parser?.logger.log({
236
+ level: "info",
237
+ message: `MCP Server added ${symbol}: ${priceNum}`
238
+ });
239
+ this.server.notification({
240
+ method: "priceUpdate",
241
+ params: {
242
+ symbol: symbolStr,
243
+ price: priceNum,
244
+ timestamp: Number(timestamp)
245
+ }
246
+ });
247
+ }
248
+ }
249
+ if (msgType === Messages.MarketDataSnapshotFullRefresh) {
250
+ const mdReqID = message.getField(Fields.MDReqID);
251
+ if (mdReqID) id = String(mdReqID.value);
252
+ } else if (msgType === Messages.ExecutionReport) {
253
+ const clOrdID = message.getField(Fields.ClOrdID);
254
+ if (clOrdID) id = String(clOrdID.value);
255
+ } else if (msgType === Messages.Reject) {
256
+ const refSeqNum = message.getField(Fields.RefSeqNum);
257
+ if (refSeqNum) id = String(refSeqNum.value);
258
+ }
259
+ if (id) {
260
+ const callback = this.pendingRequests.get(id);
261
+ if (callback) {
262
+ callback(message);
263
+ this.pendingRequests.delete(id);
1314
264
  }
1315
265
  }
1316
266
  }
1317
267
  });
1318
- this.logger = parser.logger;
1319
268
  this.addWorkflows();
1320
269
  await this.server.connect(this.transport);
1321
270
  if (this.onReady) {
@@ -1324,443 +273,716 @@ var MCPLocal = class {
1324
273
  }
1325
274
  addWorkflows() {
1326
275
  if (!this.parser) {
1327
- this.logger?.log({
1328
- level: "error",
1329
- message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of workflows..."
1330
- });
1331
276
  return;
1332
277
  }
1333
278
  if (!this.server) {
1334
- this.logger?.log({
1335
- level: "error",
1336
- message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of workflows..."
1337
- });
1338
279
  return;
1339
280
  }
1340
- this.server.setRequestHandler(ListToolsRequestSchema, async () => {
1341
- return {
1342
- tools: [
1343
- {
1344
- name: "parse",
1345
- description: "Parses a FIX message and describes it in plain language",
1346
- inputSchema: zodToJsonSchema(
1347
- z.object({
1348
- fixString: z.string().describe("FIX message string to parse")
1349
- }),
1350
- { name: "ParseInput" }
1351
- )
1352
- },
1353
- {
1354
- name: "parseToJSON",
1355
- description: "Parses a FIX message into JSON",
1356
- inputSchema: zodToJsonSchema(
1357
- z.object({
1358
- fixString: z.string().describe("FIX message string to parse")
1359
- }),
1360
- { name: "ParseToJSONInput" }
1361
- )
1362
- },
1363
- {
1364
- name: "newOrderSingle",
1365
- description: "Creates and sends a New Order Single",
1366
- inputSchema: zodToJsonSchema(
1367
- z.object({
1368
- clOrdID: z.string().describe("Client Order ID"),
1369
- handlInst: z.enum(["1", "2", "3"]).default(HandlInst.AutomatedExecutionNoIntervention).optional().describe("Handling instruction"),
1370
- quantity: z.number().describe("Order quantity"),
1371
- price: z.number().describe("Order price"),
1372
- ordType: z.enum([
1373
- "1",
1374
- "2",
1375
- "3",
1376
- "4",
1377
- "5",
1378
- "6",
1379
- "7",
1380
- "8",
1381
- "9",
1382
- "A",
1383
- "B",
1384
- "C",
1385
- "D",
1386
- "E",
1387
- "F",
1388
- "G",
1389
- "H",
1390
- "I",
1391
- "J",
1392
- "K",
1393
- "L",
1394
- "M",
1395
- "P",
1396
- "Q",
1397
- "R",
1398
- "S"
1399
- ]).default("1").optional().describe("Order type"),
1400
- side: z.enum([
1401
- "1",
1402
- "2",
1403
- "3",
1404
- "4",
1405
- "5",
1406
- "6",
1407
- "7",
1408
- "8",
1409
- "9",
1410
- "A",
1411
- "B",
1412
- "C",
1413
- "D",
1414
- "E",
1415
- "F",
1416
- "G",
1417
- "H"
1418
- ]).describe("Order side (1=Buy, 2=Sell)"),
1419
- symbol: z.string().describe("Trading symbol"),
1420
- timeInForce: z.enum(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"]).default(TimeInForce.Day).optional().describe("Time in force")
1421
- }),
1422
- { name: "NewOrderSingleInput" }
1423
- )
1424
- },
1425
- {
1426
- name: "marketDataRequest",
1427
- description: "Sends a request for Market Data with the given symbol",
1428
- inputSchema: zodToJsonSchema(
1429
- z.object({
1430
- mdUpdateType: z.enum(["0", "1"]).default("0").optional().describe("Market data update type"),
1431
- symbol: z.string().describe("Trading symbol"),
1432
- mdReqID: z.string().describe("Market data request ID"),
1433
- subscriptionRequestType: z.enum(["0", "1", "2"]).default(SubscriptionRequestType.SnapshotAndUpdates).optional().describe("Subscription request type"),
1434
- mdEntryType: z.enum([
1435
- "0",
1436
- "1",
1437
- "2",
1438
- "3",
1439
- "4",
1440
- "5",
1441
- "6",
1442
- "7",
1443
- "8",
1444
- "9",
1445
- "A",
1446
- "B",
1447
- "C",
1448
- "D",
1449
- "E",
1450
- "F",
1451
- "G",
1452
- "H",
1453
- "J",
1454
- "K",
1455
- "L",
1456
- "M",
1457
- "N",
1458
- "O",
1459
- "P",
1460
- "Q",
1461
- "S",
1462
- "R",
1463
- "T",
1464
- "U",
1465
- "V",
1466
- "W",
1467
- "X",
1468
- "Y",
1469
- "Z",
1470
- "a",
1471
- "b",
1472
- "c",
1473
- "d",
1474
- "e",
1475
- "g",
1476
- "h",
1477
- "i",
1478
- "t"
1479
- ]).default(MDEntryType.Bid).optional().describe("Market data entry type")
1480
- }),
1481
- { name: "MarketDataRequestInput" }
1482
- )
1483
- }
1484
- ]
1485
- };
1486
- });
1487
- this.server.setRequestHandler(CallToolRequestSchema, async (request) => {
1488
- const { name, arguments: args } = request.params;
1489
- switch (name) {
1490
- case "parse": {
1491
- const { fixString } = z.object({
1492
- fixString: z.string().describe("FIX message string to parse")
1493
- }).parse(args || {});
1494
- try {
1495
- const parsedMessage = this.parser?.parse(fixString);
1496
- if (!parsedMessage || parsedMessage.length === 0) {
281
+ this.server.setRequestHandler(
282
+ z.object({ method: z.literal("resources/list") }),
283
+ async (request, extra) => {
284
+ return {
285
+ resources: [
286
+ {
287
+ name: "greeting",
288
+ description: "A simple greeting resource",
289
+ uri: "greeting-resource"
290
+ }
291
+ ]
292
+ };
293
+ }
294
+ );
295
+ this.server.setRequestHandler(
296
+ z.object({ method: z.literal("resources/templates/list") }),
297
+ async (request, extra) => {
298
+ return {
299
+ resourceTemplates: [
300
+ {
301
+ name: "stockGraph",
302
+ description: "Generates a price chart for a given symbol",
303
+ uriTemplate: "stockGraph/{symbol}",
304
+ parameters: {
305
+ type: "object",
306
+ properties: {
307
+ symbol: { type: "string" }
308
+ },
309
+ required: ["symbol"]
310
+ }
311
+ },
312
+ {
313
+ name: "stockPriceHistory",
314
+ description: "Returns price history for a given symbol",
315
+ uriTemplate: "stockPriceHistory/{symbol}",
316
+ parameters: {
317
+ type: "object",
318
+ properties: {
319
+ symbol: { type: "string" }
320
+ },
321
+ required: ["symbol"]
322
+ }
323
+ }
324
+ ]
325
+ };
326
+ }
327
+ );
328
+ this.server.setRequestHandler(
329
+ z.object({ method: z.literal("tools/list") }),
330
+ async (request, extra) => {
331
+ return {
332
+ tools: [
333
+ {
334
+ name: "parse",
335
+ description: "Parses a FIX message and describes it in plain language",
336
+ inputSchema: {
337
+ type: "object",
338
+ properties: {
339
+ fixString: { type: "string" }
340
+ },
341
+ required: ["fixString"]
342
+ }
343
+ },
344
+ {
345
+ name: "parseToJSON",
346
+ description: "Parses a FIX message into JSON",
347
+ inputSchema: {
348
+ type: "object",
349
+ properties: {
350
+ fixString: { type: "string" }
351
+ },
352
+ required: ["fixString"]
353
+ }
354
+ },
355
+ {
356
+ name: "verifyOrder",
357
+ description: "Verifies order parameters before execution",
358
+ inputSchema: {
359
+ type: "object",
360
+ properties: {
361
+ clOrdID: { type: "string" },
362
+ handlInst: { type: "string", enum: ["1", "2", "3"] },
363
+ quantity: { type: "string" },
364
+ price: { type: "string" },
365
+ ordType: {
366
+ type: "string",
367
+ enum: [
368
+ "1",
369
+ "2",
370
+ "3",
371
+ "4",
372
+ "5",
373
+ "6",
374
+ "7",
375
+ "8",
376
+ "9",
377
+ "A",
378
+ "B",
379
+ "C",
380
+ "D",
381
+ "E",
382
+ "F",
383
+ "G",
384
+ "H",
385
+ "I",
386
+ "J",
387
+ "K",
388
+ "L",
389
+ "M",
390
+ "P",
391
+ "Q",
392
+ "R",
393
+ "S"
394
+ ]
395
+ },
396
+ side: {
397
+ type: "string",
398
+ enum: [
399
+ "1",
400
+ "2",
401
+ "3",
402
+ "4",
403
+ "5",
404
+ "6",
405
+ "7",
406
+ "8",
407
+ "9",
408
+ "A",
409
+ "B",
410
+ "C",
411
+ "D",
412
+ "E",
413
+ "F",
414
+ "G",
415
+ "H"
416
+ ]
417
+ },
418
+ symbol: { type: "string" },
419
+ timeInForce: {
420
+ type: "string",
421
+ enum: ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"]
422
+ }
423
+ },
424
+ required: [
425
+ "clOrdID",
426
+ "handlInst",
427
+ "quantity",
428
+ "price",
429
+ "ordType",
430
+ "side",
431
+ "symbol",
432
+ "timeInForce"
433
+ ]
434
+ }
435
+ },
436
+ {
437
+ name: "executeOrder",
438
+ description: "Executes a verified order",
439
+ inputSchema: {
440
+ type: "object",
441
+ properties: {
442
+ clOrdID: { type: "string" },
443
+ handlInst: { type: "string", enum: ["1", "2", "3"] },
444
+ quantity: { type: "string" },
445
+ price: { type: "string" },
446
+ ordType: { type: "string" },
447
+ side: { type: "string" },
448
+ symbol: { type: "string" },
449
+ timeInForce: { type: "string" }
450
+ },
451
+ required: [
452
+ "clOrdID",
453
+ "handlInst",
454
+ "quantity",
455
+ "price",
456
+ "ordType",
457
+ "side",
458
+ "symbol",
459
+ "timeInForce"
460
+ ]
461
+ }
462
+ },
463
+ {
464
+ name: "marketDataRequest",
465
+ description: "Requests market data for specified symbols",
466
+ inputSchema: {
467
+ type: "object",
468
+ properties: {
469
+ mdUpdateType: { type: "string", enum: ["0", "1"] },
470
+ symbols: { type: "array", items: { type: "string" } },
471
+ mdReqID: { type: "string" },
472
+ subscriptionRequestType: { type: "string", enum: ["0", "1", "2"] },
473
+ mdEntryTypes: { type: "array", items: { type: "string" } }
474
+ },
475
+ required: [
476
+ "mdUpdateType",
477
+ "symbols",
478
+ "mdReqID",
479
+ "subscriptionRequestType",
480
+ "mdEntryTypes"
481
+ ]
482
+ }
483
+ }
484
+ ]
485
+ };
486
+ }
487
+ );
488
+ this.server.setRequestHandler(
489
+ z.object({
490
+ method: z.literal("tools/call"),
491
+ params: z.object({
492
+ name: z.string(),
493
+ arguments: z.any(),
494
+ _meta: z.object({
495
+ progressToken: z.number()
496
+ }).optional()
497
+ })
498
+ }),
499
+ async (request, extra) => {
500
+ const { name, arguments: args } = request.params;
501
+ switch (name) {
502
+ case "parse":
503
+ try {
504
+ const parsedMessage = this.parser?.parse(args.fixString);
505
+ if (!parsedMessage || parsedMessage.length === 0) {
506
+ return {
507
+ contents: [
508
+ {
509
+ type: "text",
510
+ text: "Error: Failed to parse FIX string",
511
+ uri: "parse"
512
+ }
513
+ ],
514
+ isError: true
515
+ };
516
+ }
1497
517
  return {
1498
- isError: true,
1499
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
518
+ contents: [
519
+ {
520
+ type: "text",
521
+ text: `${parsedMessage[0].description}
522
+ ${parsedMessage[0].messageTypeDescription}`,
523
+ uri: "parse"
524
+ }
525
+ ]
526
+ };
527
+ } catch (error) {
528
+ return {
529
+ contents: [
530
+ {
531
+ type: "text",
532
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
533
+ uri: "parse"
534
+ }
535
+ ],
536
+ isError: true
1500
537
  };
1501
538
  }
1502
- return {
1503
- content: [
1504
- {
1505
- type: "text",
1506
- text: `Parsed FIX message: ${fixString} (placeholder implementation)`
1507
- }
1508
- ]
1509
- };
1510
- } catch (error) {
1511
- return {
1512
- isError: true,
1513
- content: [
1514
- {
1515
- type: "text",
1516
- text: "Error: Failed to parse FIX string"
1517
- }
1518
- ]
1519
- };
1520
- }
1521
- }
1522
- case "parseToJSON": {
1523
- const { fixString } = z.object({
1524
- fixString: z.string().describe("FIX message string to parse")
1525
- }).parse(args || {});
1526
- try {
1527
- const parsedMessage = this.parser?.parse(fixString);
1528
- if (!parsedMessage || parsedMessage.length === 0) {
539
+ case "parseToJSON":
540
+ try {
541
+ const parsedMessage = this.parser?.parse(args.fixString);
542
+ if (!parsedMessage || parsedMessage.length === 0) {
543
+ return {
544
+ contents: [
545
+ {
546
+ type: "text",
547
+ text: "Error: Failed to parse FIX string",
548
+ uri: "parseToJSON"
549
+ }
550
+ ],
551
+ isError: true
552
+ };
553
+ }
554
+ return {
555
+ contents: [
556
+ {
557
+ type: "text",
558
+ text: `${parsedMessage[0].toFIXJSON()}`,
559
+ uri: "parseToJSON"
560
+ }
561
+ ]
562
+ };
563
+ } catch (error) {
1529
564
  return {
1530
- isError: true,
1531
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
565
+ contents: [
566
+ {
567
+ type: "text",
568
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`,
569
+ uri: "parseToJSON"
570
+ }
571
+ ],
572
+ isError: true
1532
573
  };
1533
574
  }
1534
- return {
1535
- content: [
1536
- {
1537
- type: "text",
1538
- text: JSON.stringify({ fixString, parsed: "placeholder" })
1539
- }
1540
- ]
1541
- };
1542
- } catch (error) {
1543
- return {
1544
- isError: true,
1545
- content: [
1546
- {
1547
- type: "text",
1548
- text: "Error: Failed to parse FIX string"
1549
- }
1550
- ]
1551
- };
1552
- }
1553
- }
1554
- case "newOrderSingle": {
1555
- const { clOrdID, handlInst, quantity, price, ordType, side, symbol, timeInForce } = z.object({
1556
- clOrdID: z.string().describe("Client Order ID"),
1557
- handlInst: z.enum(["1", "2", "3"]).default(HandlInst.AutomatedExecutionNoIntervention).optional().describe("Handling instruction"),
1558
- quantity: z.number().describe("Order quantity"),
1559
- price: z.number().describe("Order price"),
1560
- ordType: z.enum([
1561
- "1",
1562
- "2",
1563
- "3",
1564
- "4",
1565
- "5",
1566
- "6",
1567
- "7",
1568
- "8",
1569
- "9",
1570
- "A",
1571
- "B",
1572
- "C",
1573
- "D",
1574
- "E",
1575
- "F",
1576
- "G",
1577
- "H",
1578
- "I",
1579
- "J",
1580
- "K",
1581
- "L",
1582
- "M",
1583
- "P",
1584
- "Q",
1585
- "R",
1586
- "S"
1587
- ]).default(OrdType.Market).optional().describe("Order type"),
1588
- side: z.enum([
1589
- "1",
1590
- "2",
1591
- "3",
1592
- "4",
1593
- "5",
1594
- "6",
1595
- "7",
1596
- "8",
1597
- "9",
1598
- "A",
1599
- "B",
1600
- "C",
1601
- "D",
1602
- "E",
1603
- "F",
1604
- "G",
1605
- "H"
1606
- ]).describe("Order side (1=Buy, 2=Sell)"),
1607
- symbol: z.string().describe("Trading symbol"),
1608
- timeInForce: z.enum(["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C"]).default(TimeInForce.Day).optional().describe("Time in force")
1609
- }).parse(args || {});
1610
- const response = new Promise((resolve) => {
1611
- this.pendingRequests.set(clOrdID, resolve);
1612
- });
1613
- const order = this.parser?.createMessage(
1614
- new Field(Fields.MsgType, Messages.NewOrderSingle),
1615
- new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
1616
- new Field(Fields.SenderCompID, this.parser?.sender),
1617
- new Field(Fields.TargetCompID, this.parser?.target),
1618
- new Field(Fields.SendingTime, this.parser?.getTimestamp()),
1619
- new Field(Fields.ClOrdID, clOrdID),
1620
- new Field(Fields.Side, side),
1621
- new Field(Fields.Symbol, symbol),
1622
- new Field(Fields.OrderQty, quantity),
1623
- new Field(Fields.Price, price),
1624
- new Field(Fields.OrdType, ordType),
1625
- new Field(Fields.HandlInst, handlInst),
1626
- new Field(Fields.TimeInForce, timeInForce),
1627
- new Field(Fields.TransactTime, this.parser?.getTimestamp())
1628
- );
1629
- if (!this.parser?.connected) {
1630
- this.logger?.log({
1631
- level: "error",
1632
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
1633
- });
1634
- return {
1635
- isError: true,
1636
- content: [
1637
- {
1638
- type: "text",
1639
- text: "Error: Not connected. Ignoring message."
1640
- }
1641
- ]
1642
- };
1643
- }
1644
- this.parser?.send(order);
1645
- this.logger?.log({
1646
- level: "info",
1647
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${order?.description}`
1648
- });
1649
- const fixData = await response;
1650
- return {
1651
- content: [
1652
- {
1653
- type: "text",
1654
- text: `Execution Report for order ${clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`
575
+ case "verifyOrder":
576
+ try {
577
+ this.verifiedOrders.set(args.clOrdID, {
578
+ clOrdID: args.clOrdID,
579
+ handlInst: args.handlInst,
580
+ quantity: Number.parseFloat(args.quantity),
581
+ price: Number.parseFloat(args.price),
582
+ ordType: args.ordType,
583
+ side: args.side,
584
+ symbol: args.symbol,
585
+ timeInForce: args.timeInForce
586
+ });
587
+ const ordTypeNames = {
588
+ "1": "Market",
589
+ "2": "Limit",
590
+ "3": "Stop",
591
+ "4": "StopLimit",
592
+ "5": "MarketOnClose",
593
+ "6": "WithOrWithout",
594
+ "7": "LimitOrBetter",
595
+ "8": "LimitWithOrWithout",
596
+ "9": "OnBasis",
597
+ A: "OnClose",
598
+ B: "LimitOnClose",
599
+ C: "ForexMarket",
600
+ D: "PreviouslyQuoted",
601
+ E: "PreviouslyIndicated",
602
+ F: "ForexLimit",
603
+ G: "ForexSwap",
604
+ H: "ForexPreviouslyQuoted",
605
+ I: "Funari",
606
+ J: "MarketIfTouched",
607
+ K: "MarketWithLeftOverAsLimit",
608
+ L: "PreviousFundValuationPoint",
609
+ M: "NextFundValuationPoint",
610
+ P: "Pegged",
611
+ Q: "CounterOrderSelection",
612
+ R: "StopOnBidOrOffer",
613
+ S: "StopLimitOnBidOrOffer"
614
+ };
615
+ const sideNames = {
616
+ "1": "Buy",
617
+ "2": "Sell",
618
+ "3": "BuyMinus",
619
+ "4": "SellPlus",
620
+ "5": "SellShort",
621
+ "6": "SellShortExempt",
622
+ "7": "Undisclosed",
623
+ "8": "Cross",
624
+ "9": "CrossShort",
625
+ A: "CrossShortExempt",
626
+ B: "AsDefined",
627
+ C: "Opposite",
628
+ D: "Subscribe",
629
+ E: "Redeem",
630
+ F: "Lend",
631
+ G: "Borrow",
632
+ H: "SellUndisclosed"
633
+ };
634
+ const timeInForceNames = {
635
+ "0": "Day",
636
+ "1": "GoodTillCancel",
637
+ "2": "AtTheOpening",
638
+ "3": "ImmediateOrCancel",
639
+ "4": "FillOrKill",
640
+ "5": "GoodTillCrossing",
641
+ "6": "GoodTillDate",
642
+ "7": "AtTheClose",
643
+ "8": "GoodThroughCrossing",
644
+ "9": "AtCrossing",
645
+ A: "GoodForTime",
646
+ B: "GoodForAuction",
647
+ C: "GoodForMonth"
648
+ };
649
+ const handlInstNames = {
650
+ "1": "AutomatedExecutionNoIntervention",
651
+ "2": "AutomatedExecutionInterventionOK",
652
+ "3": "ManualOrder"
653
+ };
654
+ return {
655
+ contents: [
656
+ {
657
+ type: "text",
658
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
659
+
660
+ Parameters verified:
661
+ - ClOrdID: ${args.clOrdID}
662
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
663
+ - Quantity: ${args.quantity}
664
+ - Price: ${args.price}
665
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
666
+ - Side: ${args.side} (${sideNames[args.side]})
667
+ - Symbol: ${args.symbol}
668
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
669
+
670
+ To execute this order, call the executeOrder tool with these exact same parameters.`,
671
+ uri: "verifyOrder"
672
+ }
673
+ ]
674
+ };
675
+ } catch (error) {
676
+ return {
677
+ contents: [
678
+ {
679
+ type: "text",
680
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`,
681
+ uri: "verifyOrder"
682
+ }
683
+ ],
684
+ isError: true
685
+ };
686
+ }
687
+ case "executeOrder":
688
+ try {
689
+ const verifiedOrder = this.verifiedOrders.get(args.clOrdID);
690
+ if (!verifiedOrder) {
691
+ return {
692
+ contents: [
693
+ {
694
+ type: "text",
695
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`,
696
+ uri: "executeOrder"
697
+ }
698
+ ],
699
+ isError: true
700
+ };
1655
701
  }
1656
- ]
1657
- };
1658
- }
1659
- case "marketDataRequest": {
1660
- const { mdUpdateType, symbol, mdReqID, subscriptionRequestType, mdEntryType } = z.object({
1661
- mdUpdateType: z.enum(["0", "1"]).default("0").optional().describe("Market data update type"),
1662
- symbol: z.string().describe("Trading symbol"),
1663
- mdReqID: z.string().describe("Market data request ID"),
1664
- subscriptionRequestType: z.enum(["0", "1", "2"]).default(SubscriptionRequestType.SnapshotAndUpdates).optional().describe("Subscription request type"),
1665
- mdEntryType: z.enum([
1666
- "0",
1667
- "1",
1668
- "2",
1669
- "3",
1670
- "4",
1671
- "5",
1672
- "6",
1673
- "7",
1674
- "8",
1675
- "9",
1676
- "A",
1677
- "B",
1678
- "C",
1679
- "D",
1680
- "E",
1681
- "F",
1682
- "G",
1683
- "H",
1684
- "J",
1685
- "K",
1686
- "L",
1687
- "M",
1688
- "N",
1689
- "O",
1690
- "P",
1691
- "Q",
1692
- "S",
1693
- "R",
1694
- "T",
1695
- "U",
1696
- "V",
1697
- "W",
1698
- "X",
1699
- "Y",
1700
- "Z",
1701
- "a",
1702
- "b",
1703
- "c",
1704
- "d",
1705
- "e",
1706
- "g",
1707
- "h",
1708
- "i",
1709
- "t"
1710
- ]).default(MDEntryType.Bid).optional().describe("Market data entry type")
1711
- }).parse(args || {});
1712
- const response = new Promise((resolve) => {
1713
- this.pendingRequests.set(mdReqID, resolve);
1714
- });
1715
- const marketDataRequest = this.parser?.createMessage(
1716
- new Field(Fields.MsgType, Messages.MarketDataRequest),
1717
- new Field(Fields.SenderCompID, this.parser?.sender),
1718
- new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
1719
- new Field(Fields.TargetCompID, this.parser?.target),
1720
- new Field(Fields.SendingTime, this.parser?.getTimestamp()),
1721
- new Field(Fields.MarketDepth, 0),
1722
- new Field(Fields.MDUpdateType, mdUpdateType),
1723
- new Field(Fields.NoRelatedSym, 1),
1724
- new Field(Fields.Symbol, symbol),
1725
- new Field(Fields.MDReqID, mdReqID),
1726
- new Field(Fields.SubscriptionRequestType, subscriptionRequestType),
1727
- new Field(Fields.NoMDEntryTypes, 1),
1728
- new Field(Fields.MDEntryType, mdEntryType)
1729
- );
1730
- if (!this.parser?.connected) {
1731
- this.logger?.log({
1732
- level: "error",
1733
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
1734
- });
702
+ if (verifiedOrder.handlInst !== args.handlInst || verifiedOrder.quantity !== Number.parseFloat(args.quantity) || verifiedOrder.price !== Number.parseFloat(args.price) || verifiedOrder.ordType !== args.ordType || verifiedOrder.side !== args.side || verifiedOrder.symbol !== args.symbol || verifiedOrder.timeInForce !== args.timeInForce) {
703
+ return {
704
+ contents: [
705
+ {
706
+ type: "text",
707
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified.",
708
+ uri: "executeOrder"
709
+ }
710
+ ],
711
+ isError: true
712
+ };
713
+ }
714
+ const response = new Promise((resolve) => {
715
+ this.pendingRequests.set(args.clOrdID, resolve);
716
+ });
717
+ const order = this.parser?.createMessage(
718
+ new Field(Fields.MsgType, Messages.NewOrderSingle),
719
+ new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
720
+ new Field(Fields.SenderCompID, this.parser?.sender),
721
+ new Field(Fields.TargetCompID, this.parser?.target),
722
+ new Field(Fields.SendingTime, this.parser?.getTimestamp()),
723
+ new Field(Fields.ClOrdID, args.clOrdID),
724
+ new Field(Fields.Side, args.side),
725
+ new Field(Fields.Symbol, args.symbol),
726
+ new Field(Fields.OrderQty, Number.parseFloat(args.quantity)),
727
+ new Field(Fields.Price, Number.parseFloat(args.price)),
728
+ new Field(Fields.OrdType, args.ordType),
729
+ new Field(Fields.HandlInst, args.handlInst),
730
+ new Field(Fields.TimeInForce, args.timeInForce),
731
+ new Field(Fields.TransactTime, this.parser?.getTimestamp())
732
+ );
733
+ if (!this.parser?.connected) {
734
+ return {
735
+ contents: [
736
+ {
737
+ type: "text",
738
+ text: "Error: Not connected. Ignoring message.",
739
+ uri: "executeOrder"
740
+ }
741
+ ],
742
+ isError: true
743
+ };
744
+ }
745
+ this.parser?.send(order);
746
+ const fixData = await response;
747
+ this.verifiedOrders.delete(args.clOrdID);
748
+ return {
749
+ contents: [
750
+ {
751
+ type: "text",
752
+ text: fixData.messageType === Messages.Reject ? `Reject message for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}` : `Execution Report for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`,
753
+ uri: "executeOrder"
754
+ }
755
+ ]
756
+ };
757
+ } catch (error) {
758
+ return {
759
+ contents: [
760
+ {
761
+ type: "text",
762
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`,
763
+ uri: "executeOrder"
764
+ }
765
+ ],
766
+ isError: true
767
+ };
768
+ }
769
+ case "marketDataRequest":
770
+ try {
771
+ const response = new Promise((resolve) => {
772
+ this.pendingRequests.set(args.mdReqID, resolve);
773
+ });
774
+ const messageFields = [
775
+ new Field(Fields.MsgType, Messages.MarketDataRequest),
776
+ new Field(Fields.SenderCompID, this.parser?.sender),
777
+ new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
778
+ new Field(Fields.TargetCompID, this.parser?.target),
779
+ new Field(Fields.SendingTime, this.parser?.getTimestamp()),
780
+ new Field(Fields.MDReqID, args.mdReqID),
781
+ new Field(Fields.SubscriptionRequestType, args.subscriptionRequestType),
782
+ new Field(Fields.MarketDepth, 0),
783
+ new Field(Fields.MDUpdateType, args.mdUpdateType)
784
+ ];
785
+ messageFields.push(new Field(Fields.NoRelatedSym, args.symbols.length));
786
+ args.symbols.forEach((symbol) => {
787
+ messageFields.push(new Field(Fields.Symbol, symbol));
788
+ });
789
+ messageFields.push(new Field(Fields.NoMDEntryTypes, args.mdEntryTypes.length));
790
+ args.mdEntryTypes.forEach((entryType) => {
791
+ messageFields.push(new Field(Fields.MDEntryType, entryType));
792
+ });
793
+ const mdr = this.parser?.createMessage(...messageFields);
794
+ if (!this.parser?.connected) {
795
+ return {
796
+ contents: [
797
+ {
798
+ type: "text",
799
+ text: "Error: Not connected. Ignoring message.",
800
+ uri: "marketDataRequest"
801
+ }
802
+ ],
803
+ isError: true
804
+ };
805
+ }
806
+ this.parser?.send(mdr);
807
+ const fixData = await response;
808
+ return {
809
+ contents: [
810
+ {
811
+ type: "text",
812
+ text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`,
813
+ uri: "marketDataRequest"
814
+ }
815
+ ]
816
+ };
817
+ } catch (error) {
818
+ return {
819
+ contents: [
820
+ {
821
+ type: "text",
822
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`,
823
+ uri: "marketDataRequest"
824
+ }
825
+ ],
826
+ isError: true
827
+ };
828
+ }
829
+ case "getStockGraph":
830
+ try {
831
+ const symbol = args.symbol;
832
+ const priceHistory = this.marketDataPrices.get(symbol) || [];
833
+ if (priceHistory.length === 0) {
834
+ return {
835
+ contents: [
836
+ {
837
+ type: "text",
838
+ text: `No price data available for ${symbol}`,
839
+ uri: "getStockGraph"
840
+ }
841
+ ]
842
+ };
843
+ }
844
+ const width = 600;
845
+ const height = 300;
846
+ const padding = 40;
847
+ const xScale = (width - 2 * padding) / (priceHistory.length - 1);
848
+ const yMin = Math.min(...priceHistory.map((d) => d.price));
849
+ const yMax = Math.max(...priceHistory.map((d) => d.price));
850
+ const yScale = (height - 2 * padding) / (yMax - yMin);
851
+ const points = priceHistory.map((d, i) => {
852
+ const x = padding + i * xScale;
853
+ const y = height - padding - (d.price - yMin) * yScale;
854
+ return `${x},${y}`;
855
+ }).join(" L ");
856
+ const svg = `<?xml version="1.0" encoding="UTF-8"?>
857
+ <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
858
+ <!-- Background -->
859
+ <rect width="100%" height="100%" fill="#f8f9fa"/>
860
+
861
+ <!-- Grid lines -->
862
+ <g stroke="#e9ecef" stroke-width="1">
863
+ ${Array.from({ length: 5 }, (_, i) => {
864
+ const y = padding + (height - 2 * padding) * i / 4;
865
+ return `<line x1="${padding}" y1="${y}" x2="${width - padding}" y2="${y}"/>`;
866
+ }).join("\n")}
867
+ </g>
868
+
869
+ <!-- Price line -->
870
+ <path d="M ${points}"
871
+ fill="none"
872
+ stroke="#007bff"
873
+ stroke-width="2"/>
874
+
875
+ <!-- Data points -->
876
+ ${priceHistory.map((d, i) => {
877
+ const x = padding + i * xScale;
878
+ const y = height - padding - (d.price - yMin) * yScale;
879
+ return `<circle cx="${x}" cy="${y}" r="3" fill="#007bff"/>`;
880
+ }).join("\n")}
881
+
882
+ <!-- Labels -->
883
+ <g font-family="Arial" font-size="12" fill="#495057">
884
+ ${Array.from({ length: 5 }, (_, i) => {
885
+ const x = padding + (width - 2 * padding) * i / 4;
886
+ const index = Math.floor((priceHistory.length - 1) * i / 4);
887
+ const timestamp = new Date(priceHistory[index].timestamp).toLocaleTimeString();
888
+ return `<text x="${x + padding}" y="${height - padding + 20}" text-anchor="middle">${timestamp}</text>`;
889
+ }).join("\n")}
890
+ ${Array.from({ length: 5 }, (_, i) => {
891
+ const y = padding + (height - 2 * padding) * i / 4;
892
+ const price = yMax - (yMax - yMin) * i / 4;
893
+ return `<text x="${padding - 5}" y="${y + 4}" text-anchor="end">$${price.toFixed(2)}</text>`;
894
+ }).join("\n")}
895
+ </g>
896
+
897
+ <!-- Title -->
898
+ <text x="${width / 2}" y="${padding / 2}"
899
+ font-family="Arial" font-size="16" font-weight="bold"
900
+ text-anchor="middle" fill="#212529">
901
+ ${symbol} - Price Chart (${priceHistory.length} points)
902
+ </text>
903
+ </svg>`;
904
+ return {
905
+ contents: [
906
+ {
907
+ type: "text",
908
+ text: svg,
909
+ uri: "getStockGraph"
910
+ }
911
+ ]
912
+ };
913
+ } catch (error) {
914
+ return {
915
+ contents: [
916
+ {
917
+ type: "text",
918
+ text: `Error: ${error instanceof Error ? error.message : "Failed to generate stock graph"}`,
919
+ uri: "getStockGraph"
920
+ }
921
+ ],
922
+ isError: true
923
+ };
924
+ }
925
+ case "getStockPriceHistory":
926
+ try {
927
+ const symbol = args.symbol;
928
+ const priceHistory = this.marketDataPrices.get(symbol) || [];
929
+ if (priceHistory.length === 0) {
930
+ return {
931
+ contents: [
932
+ {
933
+ type: "text",
934
+ text: `No price data available for ${symbol}`,
935
+ uri: "getStockPriceHistory"
936
+ }
937
+ ]
938
+ };
939
+ }
940
+ return {
941
+ contents: [
942
+ {
943
+ type: "text",
944
+ text: JSON.stringify(
945
+ {
946
+ symbol,
947
+ count: priceHistory.length,
948
+ prices: priceHistory.map((point) => ({
949
+ timestamp: new Date(point.timestamp).toISOString(),
950
+ price: point.price
951
+ }))
952
+ },
953
+ null,
954
+ 2
955
+ ),
956
+ uri: "getStockPriceHistory"
957
+ }
958
+ ]
959
+ };
960
+ } catch (error) {
961
+ return {
962
+ contents: [
963
+ {
964
+ type: "text",
965
+ text: `Error: ${error instanceof Error ? error.message : "Failed to get stock price history"}`,
966
+ uri: "getStockPriceHistory"
967
+ }
968
+ ],
969
+ isError: true
970
+ };
971
+ }
972
+ default:
1735
973
  return {
1736
- isError: true,
1737
- content: [
974
+ contents: [
1738
975
  {
1739
976
  type: "text",
1740
- text: "Error: Not connected. Ignoring message."
977
+ text: `Tool not found: ${name}`,
978
+ uri: name
1741
979
  }
1742
- ]
980
+ ],
981
+ isError: true
1743
982
  };
1744
- }
1745
- this.parser?.send(marketDataRequest);
1746
- this.logger?.log({
1747
- level: "info",
1748
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${marketDataRequest?.description}`
1749
- });
1750
- const fixData = await response;
1751
- return {
1752
- content: [
1753
- {
1754
- type: "text",
1755
- text: `Market data for ${symbol}: ${JSON.stringify(fixData.toFIXJSON())}`
1756
- }
1757
- ]
1758
- };
1759
983
  }
1760
- default:
1761
- throw new Error(`Unknown tool: ${name}`);
1762
984
  }
1763
- });
985
+ );
1764
986
  process.on("SIGINT", async () => {
1765
987
  await this.server.close();
1766
988
  process.exit(0);