fixparser-plugin-mcp 9.1.7-3e178996 → 9.1.7-400318ef

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,246 @@ 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
+ },
157
+ resources: {
158
+ greeting: {
159
+ description: "A simple greeting resource",
160
+ uri: "greeting-resource"
161
+ },
162
+ stockGraph: {
163
+ description: "Generates a price chart for a given symbol",
164
+ uri: "stockGraph",
165
+ parameters: {
166
+ type: "object",
167
+ properties: {
168
+ symbol: { type: "string" }
169
+ },
170
+ required: ["symbol"]
171
+ }
172
+ },
173
+ stockPriceHistory: {
174
+ description: "Returns price history for a given symbol",
175
+ uri: "stockPriceHistory",
176
+ parameters: {
177
+ type: "object",
178
+ properties: {
179
+ symbol: { type: "string" }
180
+ },
181
+ required: ["symbol"]
182
+ }
183
+ }
184
+ }
185
+ }
1287
186
  }
1288
187
  );
1289
188
  transport = new StdioServerTransport();
1290
189
  onReady = void 0;
1291
190
  pendingRequests = /* @__PURE__ */ new Map();
191
+ verifiedOrders = /* @__PURE__ */ new Map();
192
+ // Store market data prices with timestamps
193
+ marketDataPrices = /* @__PURE__ */ new Map();
194
+ MAX_PRICE_HISTORY = 1e5;
195
+ // Maximum number of price points to store per symbol
1292
196
  constructor({ logger, onReady }) {
1293
- if (logger) this.logger = logger;
1294
197
  if (onReady) this.onReady = onReady;
1295
198
  }
1296
199
  async register(parser) {
1297
200
  this.parser = parser;
1298
201
  this.parser.addOnMessageCallback((message) => {
1299
- this.logger?.log({
202
+ this.parser?.logger.log({
1300
203
  level: "info",
1301
- message: `FIXParser (MCP): (${parser.protocol?.toUpperCase()}): << received ${message.description}`
204
+ message: `MCP Server received message: ${message.messageType}: ${message.description}`
1302
205
  });
1303
206
  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));
207
+ if (msgType === Messages.MarketDataSnapshotFullRefresh || msgType === Messages.ExecutionReport || msgType === Messages.Reject || msgType === Messages.MarketDataIncrementalRefresh) {
208
+ this.parser?.logger.log({
209
+ level: "info",
210
+ message: `MCP Server handling message type: ${msgType}`
211
+ });
212
+ let id;
213
+ if (msgType === Messages.MarketDataIncrementalRefresh || msgType === Messages.MarketDataSnapshotFullRefresh) {
214
+ const symbol = message.getField(Fields.Symbol);
215
+ const price = message.getField(Fields.MDEntryPx);
216
+ const timestamp = message.getField(Fields.MDEntryTime)?.value || Date.now();
217
+ if (symbol?.value && price?.value) {
218
+ const symbolStr = String(symbol.value);
219
+ const priceNum = Number(price.value);
220
+ const priceHistory = this.marketDataPrices.get(symbolStr) || [];
221
+ priceHistory.push({
222
+ timestamp: Number(timestamp),
223
+ price: priceNum
224
+ });
225
+ if (priceHistory.length > this.MAX_PRICE_HISTORY) {
226
+ priceHistory.shift();
1313
227
  }
228
+ this.marketDataPrices.set(symbolStr, priceHistory);
229
+ this.parser?.logger.log({
230
+ level: "info",
231
+ message: `MCP Server added ${symbol}: ${priceNum}`
232
+ });
233
+ }
234
+ }
235
+ if (msgType === Messages.MarketDataSnapshotFullRefresh) {
236
+ const mdReqID = message.getField(Fields.MDReqID);
237
+ if (mdReqID) id = String(mdReqID.value);
238
+ } else if (msgType === Messages.ExecutionReport) {
239
+ const clOrdID = message.getField(Fields.ClOrdID);
240
+ if (clOrdID) id = String(clOrdID.value);
241
+ } else if (msgType === Messages.Reject) {
242
+ const refSeqNum = message.getField(Fields.RefSeqNum);
243
+ if (refSeqNum) id = String(refSeqNum.value);
244
+ }
245
+ if (id) {
246
+ const callback = this.pendingRequests.get(id);
247
+ if (callback) {
248
+ callback(message);
249
+ this.pendingRequests.delete(id);
1314
250
  }
1315
251
  }
1316
252
  }
1317
253
  });
1318
- this.logger = parser.logger;
1319
254
  this.addWorkflows();
1320
255
  await this.server.connect(this.transport);
1321
256
  if (this.onReady) {
@@ -1324,291 +259,220 @@ var MCPLocal = class {
1324
259
  }
1325
260
  addWorkflows() {
1326
261
  if (!this.parser) {
1327
- this.logger?.log({
1328
- level: "error",
1329
- message: "FIXParser (MCP): -- FIXParser instance not initialized. Ignoring setup of workflows..."
1330
- });
1331
262
  return;
1332
263
  }
1333
264
  if (!this.server) {
1334
- this.logger?.log({
1335
- level: "error",
1336
- message: "FIXParser (MCP): -- MCP Server not initialized. Ignoring setup of workflows..."
1337
- });
1338
265
  return;
1339
266
  }
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) {
1497
- return {
1498
- isError: true,
1499
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
1500
- };
267
+ this.server.setRequestHandler(z.object({ method: z.literal("parse") }), async (request, extra) => {
268
+ try {
269
+ const args = request.params;
270
+ const parsedMessage = this.parser?.parse(args.fixString);
271
+ if (!parsedMessage || parsedMessage.length === 0) {
272
+ return {
273
+ content: [{ type: "text", text: "Error: Failed to parse FIX string" }],
274
+ isError: true
275
+ };
276
+ }
277
+ return {
278
+ content: [
279
+ {
280
+ type: "text",
281
+ text: `${parsedMessage[0].description}
282
+ ${parsedMessage[0].messageTypeDescription}`
1501
283
  }
284
+ ]
285
+ };
286
+ } catch (error) {
287
+ return {
288
+ content: [
289
+ {
290
+ type: "text",
291
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
292
+ }
293
+ ],
294
+ isError: true
295
+ };
296
+ }
297
+ });
298
+ this.server.setRequestHandler(
299
+ z.object({ method: z.literal("parseToJSON") }),
300
+ async (request, extra) => {
301
+ try {
302
+ const args = request.params;
303
+ const parsedMessage = this.parser?.parse(args.fixString);
304
+ if (!parsedMessage || parsedMessage.length === 0) {
1502
305
  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
- ]
306
+ content: [{ type: "text", text: "Error: Failed to parse FIX string" }],
307
+ isError: true
1519
308
  };
1520
309
  }
310
+ return {
311
+ content: [
312
+ {
313
+ type: "text",
314
+ text: `${parsedMessage[0].toFIXJSON()}`
315
+ }
316
+ ]
317
+ };
318
+ } catch (error) {
319
+ return {
320
+ content: [
321
+ {
322
+ type: "text",
323
+ text: `Error: ${error instanceof Error ? error.message : "Failed to parse FIX string"}`
324
+ }
325
+ ],
326
+ isError: true
327
+ };
1521
328
  }
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) {
1529
- return {
1530
- isError: true,
1531
- content: [{ type: "text", text: "Error: Failed to parse FIX string" }]
1532
- };
1533
- }
329
+ }
330
+ );
331
+ this.server.setRequestHandler(
332
+ z.object({ method: z.literal("verifyOrder") }),
333
+ async (request, extra) => {
334
+ try {
335
+ const args = request.params;
336
+ this.verifiedOrders.set(args.clOrdID, {
337
+ clOrdID: args.clOrdID,
338
+ handlInst: args.handlInst,
339
+ quantity: Number.parseFloat(args.quantity),
340
+ price: Number.parseFloat(args.price),
341
+ ordType: args.ordType,
342
+ side: args.side,
343
+ symbol: args.symbol,
344
+ timeInForce: args.timeInForce
345
+ });
346
+ const ordTypeNames = {
347
+ "1": "Market",
348
+ "2": "Limit",
349
+ "3": "Stop",
350
+ "4": "StopLimit",
351
+ "5": "MarketOnClose",
352
+ "6": "WithOrWithout",
353
+ "7": "LimitOrBetter",
354
+ "8": "LimitWithOrWithout",
355
+ "9": "OnBasis",
356
+ A: "OnClose",
357
+ B: "LimitOnClose",
358
+ C: "ForexMarket",
359
+ D: "PreviouslyQuoted",
360
+ E: "PreviouslyIndicated",
361
+ F: "ForexLimit",
362
+ G: "ForexSwap",
363
+ H: "ForexPreviouslyQuoted",
364
+ I: "Funari",
365
+ J: "MarketIfTouched",
366
+ K: "MarketWithLeftOverAsLimit",
367
+ L: "PreviousFundValuationPoint",
368
+ M: "NextFundValuationPoint",
369
+ P: "Pegged",
370
+ Q: "CounterOrderSelection",
371
+ R: "StopOnBidOrOffer",
372
+ S: "StopLimitOnBidOrOffer"
373
+ };
374
+ const sideNames = {
375
+ "1": "Buy",
376
+ "2": "Sell",
377
+ "3": "BuyMinus",
378
+ "4": "SellPlus",
379
+ "5": "SellShort",
380
+ "6": "SellShortExempt",
381
+ "7": "Undisclosed",
382
+ "8": "Cross",
383
+ "9": "CrossShort",
384
+ A: "CrossShortExempt",
385
+ B: "AsDefined",
386
+ C: "Opposite",
387
+ D: "Subscribe",
388
+ E: "Redeem",
389
+ F: "Lend",
390
+ G: "Borrow",
391
+ H: "SellUndisclosed"
392
+ };
393
+ const timeInForceNames = {
394
+ "0": "Day",
395
+ "1": "GoodTillCancel",
396
+ "2": "AtTheOpening",
397
+ "3": "ImmediateOrCancel",
398
+ "4": "FillOrKill",
399
+ "5": "GoodTillCrossing",
400
+ "6": "GoodTillDate",
401
+ "7": "AtTheClose",
402
+ "8": "GoodThroughCrossing",
403
+ "9": "AtCrossing",
404
+ A: "GoodForTime",
405
+ B: "GoodForAuction",
406
+ C: "GoodForMonth"
407
+ };
408
+ const handlInstNames = {
409
+ "1": "AutomatedExecutionNoIntervention",
410
+ "2": "AutomatedExecutionInterventionOK",
411
+ "3": "ManualOrder"
412
+ };
413
+ return {
414
+ content: [
415
+ {
416
+ type: "text",
417
+ text: `VERIFICATION: All parameters valid. Ready to proceed with order execution.
418
+
419
+ Parameters verified:
420
+ - ClOrdID: ${args.clOrdID}
421
+ - HandlInst: ${args.handlInst} (${handlInstNames[args.handlInst]})
422
+ - Quantity: ${args.quantity}
423
+ - Price: ${args.price}
424
+ - OrdType: ${args.ordType} (${ordTypeNames[args.ordType]})
425
+ - Side: ${args.side} (${sideNames[args.side]})
426
+ - Symbol: ${args.symbol}
427
+ - TimeInForce: ${args.timeInForce} (${timeInForceNames[args.timeInForce]})
428
+
429
+ To execute this order, call the executeOrder tool with these exact same parameters.`
430
+ }
431
+ ]
432
+ };
433
+ } catch (error) {
434
+ return {
435
+ content: [
436
+ {
437
+ type: "text",
438
+ text: `Error: ${error instanceof Error ? error.message : "Failed to verify order parameters"}`
439
+ }
440
+ ],
441
+ isError: true
442
+ };
443
+ }
444
+ }
445
+ );
446
+ this.server.setRequestHandler(
447
+ z.object({ method: z.literal("executeOrder") }),
448
+ async (request, extra) => {
449
+ try {
450
+ const args = request.params;
451
+ const verifiedOrder = this.verifiedOrders.get(args.clOrdID);
452
+ if (!verifiedOrder) {
1534
453
  return {
1535
454
  content: [
1536
455
  {
1537
456
  type: "text",
1538
- text: JSON.stringify({ fixString, parsed: "placeholder" })
457
+ text: `Error: Order ${args.clOrdID} has not been verified. Please call verifyOrder first.`
1539
458
  }
1540
- ]
459
+ ],
460
+ isError: true
1541
461
  };
1542
- } catch (error) {
462
+ }
463
+ if (verifiedOrder.handlInst !== args.handlInst || verifiedOrder.quantity !== Number.parseFloat(args.quantity) || verifiedOrder.price !== Number.parseFloat(args.price) || verifiedOrder.ordType !== args.ordType || verifiedOrder.side !== args.side || verifiedOrder.symbol !== args.symbol || verifiedOrder.timeInForce !== args.timeInForce) {
1543
464
  return {
1544
- isError: true,
1545
465
  content: [
1546
466
  {
1547
467
  type: "text",
1548
- text: "Error: Failed to parse FIX string"
468
+ text: "Error: Order parameters do not match the verified order. Please use the exact same parameters that were verified."
1549
469
  }
1550
- ]
470
+ ],
471
+ isError: true
1551
472
  };
1552
473
  }
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
474
  const response = new Promise((resolve) => {
1611
- this.pendingRequests.set(clOrdID, resolve);
475
+ this.pendingRequests.set(args.clOrdID, resolve);
1612
476
  });
1613
477
  const order = this.parser?.createMessage(
1614
478
  new Field(Fields.MsgType, Messages.NewOrderSingle),
@@ -1616,151 +480,251 @@ var MCPLocal = class {
1616
480
  new Field(Fields.SenderCompID, this.parser?.sender),
1617
481
  new Field(Fields.TargetCompID, this.parser?.target),
1618
482
  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),
483
+ new Field(Fields.ClOrdID, args.clOrdID),
484
+ new Field(Fields.Side, args.side),
485
+ new Field(Fields.Symbol, args.symbol),
486
+ new Field(Fields.OrderQty, Number.parseFloat(args.quantity)),
487
+ new Field(Fields.Price, Number.parseFloat(args.price)),
488
+ new Field(Fields.OrdType, args.ordType),
489
+ new Field(Fields.HandlInst, args.handlInst),
490
+ new Field(Fields.TimeInForce, args.timeInForce),
1627
491
  new Field(Fields.TransactTime, this.parser?.getTimestamp())
1628
492
  );
1629
493
  if (!this.parser?.connected) {
1630
- this.logger?.log({
1631
- level: "error",
1632
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
1633
- });
1634
494
  return {
1635
- isError: true,
1636
495
  content: [
1637
496
  {
1638
497
  type: "text",
1639
498
  text: "Error: Not connected. Ignoring message."
1640
499
  }
1641
- ]
500
+ ],
501
+ isError: true
1642
502
  };
1643
503
  }
1644
504
  this.parser?.send(order);
1645
- this.logger?.log({
1646
- level: "info",
1647
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${order?.description}`
1648
- });
1649
505
  const fixData = await response;
506
+ this.verifiedOrders.delete(args.clOrdID);
1650
507
  return {
1651
508
  content: [
1652
509
  {
1653
510
  type: "text",
1654
- text: `Execution Report for order ${clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`
511
+ text: fixData.messageType === Messages.Reject ? `Reject message for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}` : `Execution Report for order ${args.clOrdID}: ${JSON.stringify(fixData.toFIXJSON())}`
1655
512
  }
1656
513
  ]
1657
514
  };
515
+ } catch (error) {
516
+ return {
517
+ content: [
518
+ {
519
+ type: "text",
520
+ text: `Error: ${error instanceof Error ? error.message : "Failed to execute order"}`
521
+ }
522
+ ],
523
+ isError: true
524
+ };
1658
525
  }
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 || {});
526
+ }
527
+ );
528
+ this.server.setRequestHandler(
529
+ z.object({ method: z.literal("marketDataRequest") }),
530
+ async (request, extra) => {
531
+ try {
532
+ const args = request.params;
1712
533
  const response = new Promise((resolve) => {
1713
- this.pendingRequests.set(mdReqID, resolve);
534
+ this.pendingRequests.set(args.mdReqID, resolve);
1714
535
  });
1715
- const marketDataRequest = this.parser?.createMessage(
536
+ const messageFields = [
1716
537
  new Field(Fields.MsgType, Messages.MarketDataRequest),
1717
538
  new Field(Fields.SenderCompID, this.parser?.sender),
1718
539
  new Field(Fields.MsgSeqNum, this.parser?.getNextTargetMsgSeqNum()),
1719
540
  new Field(Fields.TargetCompID, this.parser?.target),
1720
541
  new Field(Fields.SendingTime, this.parser?.getTimestamp()),
542
+ new Field(Fields.MDReqID, args.mdReqID),
543
+ new Field(Fields.SubscriptionRequestType, args.subscriptionRequestType),
1721
544
  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
- );
545
+ new Field(Fields.MDUpdateType, args.mdUpdateType)
546
+ ];
547
+ messageFields.push(new Field(Fields.NoRelatedSym, args.symbols.length));
548
+ args.symbols.forEach((symbol) => {
549
+ messageFields.push(new Field(Fields.Symbol, symbol));
550
+ });
551
+ messageFields.push(new Field(Fields.NoMDEntryTypes, args.mdEntryTypes.length));
552
+ args.mdEntryTypes.forEach((entryType) => {
553
+ messageFields.push(new Field(Fields.MDEntryType, entryType));
554
+ });
555
+ const mdr = this.parser?.createMessage(...messageFields);
1730
556
  if (!this.parser?.connected) {
1731
- this.logger?.log({
1732
- level: "error",
1733
- message: "FIXParser (MCP): -- Not connected. Ignoring message."
1734
- });
1735
557
  return {
1736
- isError: true,
1737
558
  content: [
1738
559
  {
1739
560
  type: "text",
1740
561
  text: "Error: Not connected. Ignoring message."
1741
562
  }
1742
- ]
563
+ ],
564
+ isError: true
1743
565
  };
1744
566
  }
1745
- this.parser?.send(marketDataRequest);
1746
- this.logger?.log({
1747
- level: "info",
1748
- message: `FIXParser (MCP): (${this.parser?.protocol?.toUpperCase()}): >> sent ${marketDataRequest?.description}`
1749
- });
567
+ this.parser?.send(mdr);
1750
568
  const fixData = await response;
1751
569
  return {
1752
570
  content: [
1753
571
  {
1754
572
  type: "text",
1755
- text: `Market data for ${symbol}: ${JSON.stringify(fixData.toFIXJSON())}`
573
+ text: `Market data for ${args.symbols.join(", ")}: ${JSON.stringify(fixData.toFIXJSON())}`
574
+ }
575
+ ]
576
+ };
577
+ } catch (error) {
578
+ return {
579
+ content: [
580
+ {
581
+ type: "text",
582
+ text: `Error: ${error instanceof Error ? error.message : "Failed to request market data"}`
583
+ }
584
+ ],
585
+ isError: true
586
+ };
587
+ }
588
+ }
589
+ );
590
+ this.server.setRequestHandler(
591
+ z.object({ method: z.literal("greeting-resource") }),
592
+ async (request, extra) => {
593
+ this.parser?.logger.log({
594
+ level: "info",
595
+ message: "MCP Server Resource called: greeting-resource"
596
+ });
597
+ return {
598
+ content: [
599
+ {
600
+ type: "text",
601
+ text: "Hello, world!"
602
+ }
603
+ ]
604
+ };
605
+ }
606
+ );
607
+ this.server.setRequestHandler(
608
+ z.object({ method: z.literal("stockGraph") }),
609
+ async (request, extra) => {
610
+ this.parser?.logger.log({
611
+ level: "info",
612
+ message: "MCP Server Resource called: stockGraph"
613
+ });
614
+ const args = request.params;
615
+ const symbol = args.symbol;
616
+ const priceHistory = this.marketDataPrices.get(symbol) || [];
617
+ if (priceHistory.length === 0) {
618
+ return {
619
+ content: [
620
+ {
621
+ type: "text",
622
+ text: `No price data available for ${symbol}`
1756
623
  }
1757
624
  ]
1758
625
  };
1759
626
  }
1760
- default:
1761
- throw new Error(`Unknown tool: ${name}`);
627
+ const width = 600;
628
+ const height = 300;
629
+ const padding = 40;
630
+ const xScale = (width - 2 * padding) / (priceHistory.length - 1);
631
+ const yMin = Math.min(...priceHistory.map((d) => d.price));
632
+ const yMax = Math.max(...priceHistory.map((d) => d.price));
633
+ const yScale = (height - 2 * padding) / (yMax - yMin);
634
+ const points = priceHistory.map((d, i) => {
635
+ const x = padding + i * xScale;
636
+ const y = height - padding - (d.price - yMin) * yScale;
637
+ return `${x},${y}`;
638
+ }).join(" L ");
639
+ const svg = `<?xml version="1.0" encoding="UTF-8"?>
640
+ <svg width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
641
+ <!-- Background -->
642
+ <rect width="100%" height="100%" fill="#f8f9fa"/>
643
+
644
+ <!-- Grid lines -->
645
+ <g stroke="#e9ecef" stroke-width="1">
646
+ ${Array.from({ length: 5 }, (_, i) => {
647
+ const y = padding + (height - 2 * padding) * i / 4;
648
+ return `<line x1="${padding}" y1="${y}" x2="${width - padding}" y2="${y}"/>`;
649
+ }).join("\n")}
650
+ </g>
651
+
652
+ <!-- Price line -->
653
+ <path d="M ${points}"
654
+ fill="none"
655
+ stroke="#007bff"
656
+ stroke-width="2"/>
657
+
658
+ <!-- Data points -->
659
+ ${priceHistory.map((d, i) => {
660
+ const x = padding + i * xScale;
661
+ const y = height - padding - (d.price - yMin) * yScale;
662
+ return `<circle cx="${x}" cy="${y}" r="3" fill="#007bff"/>`;
663
+ }).join("\n")}
664
+
665
+ <!-- Labels -->
666
+ <g font-family="Arial" font-size="12" fill="#495057">
667
+ ${Array.from({ length: 5 }, (_, i) => {
668
+ const x = padding + (width - 2 * padding) * i / 4;
669
+ const index = Math.floor((priceHistory.length - 1) * i / 4);
670
+ const timestamp = new Date(priceHistory[index].timestamp).toLocaleTimeString();
671
+ return `<text x="${x + padding}" y="${height - padding + 20}" text-anchor="middle">${timestamp}</text>`;
672
+ }).join("\n")}
673
+ ${Array.from({ length: 5 }, (_, i) => {
674
+ const y = padding + (height - 2 * padding) * i / 4;
675
+ const price = yMax - (yMax - yMin) * i / 4;
676
+ return `<text x="${padding - 5}" y="${y + 4}" text-anchor="end">$${price.toFixed(2)}</text>`;
677
+ }).join("\n")}
678
+ </g>
679
+
680
+ <!-- Title -->
681
+ <text x="${width / 2}" y="${padding / 2}"
682
+ font-family="Arial" font-size="16" font-weight="bold"
683
+ text-anchor="middle" fill="#212529">
684
+ ${symbol} - Price Chart (${priceHistory.length} points)
685
+ </text>
686
+ </svg>`;
687
+ return {
688
+ content: [
689
+ {
690
+ type: "text",
691
+ text: svg
692
+ }
693
+ ]
694
+ };
1762
695
  }
1763
- });
696
+ );
697
+ this.server.setRequestHandler(
698
+ z.object({ method: z.literal("stockPriceHistory") }),
699
+ async (request, extra) => {
700
+ this.parser?.logger.log({
701
+ level: "info",
702
+ message: "MCP Server Resource called: stockPriceHistory"
703
+ });
704
+ const args = request.params;
705
+ const symbol = args.symbol;
706
+ const priceHistory = this.marketDataPrices.get(symbol) || [];
707
+ return {
708
+ content: [
709
+ {
710
+ type: "text",
711
+ text: JSON.stringify(
712
+ {
713
+ symbol,
714
+ count: priceHistory.length,
715
+ prices: priceHistory.map((point) => ({
716
+ timestamp: new Date(point.timestamp).toISOString(),
717
+ price: point.price
718
+ }))
719
+ },
720
+ null,
721
+ 2
722
+ )
723
+ }
724
+ ]
725
+ };
726
+ }
727
+ );
1764
728
  process.on("SIGINT", async () => {
1765
729
  await this.server.close();
1766
730
  process.exit(0);