fixparser-plugin-mcp 9.1.7-71fc8a2b → 9.1.7-75ded9c1

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