ajv-provider.js 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /**
  2. * AJV-based JSON Schema validator provider
  3. */
  4. import Ajv from 'ajv';
  5. import _addFormats from 'ajv-formats';
  6. function createDefaultAjvInstance() {
  7. const ajv = new Ajv({
  8. strict: false,
  9. validateFormats: true,
  10. validateSchema: false,
  11. allErrors: true
  12. });
  13. const addFormats = _addFormats;
  14. addFormats(ajv);
  15. return ajv;
  16. }
  17. /**
  18. * @example
  19. * ```typescript
  20. * // Use with default AJV instance (recommended)
  21. * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
  22. * const validator = new AjvJsonSchemaValidator();
  23. *
  24. * // Use with custom AJV instance
  25. * import { Ajv } from 'ajv';
  26. * const ajv = new Ajv({ strict: true, allErrors: true });
  27. * const validator = new AjvJsonSchemaValidator(ajv);
  28. * ```
  29. */
  30. export class AjvJsonSchemaValidator {
  31. /**
  32. * Create an AJV validator
  33. *
  34. * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.
  35. *
  36. * @example
  37. * ```typescript
  38. * // Use default configuration (recommended for most cases)
  39. * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
  40. * const validator = new AjvJsonSchemaValidator();
  41. *
  42. * // Or provide custom AJV instance for advanced configuration
  43. * import { Ajv } from 'ajv';
  44. * import addFormats from 'ajv-formats';
  45. *
  46. * const ajv = new Ajv({ validateFormats: true });
  47. * addFormats(ajv);
  48. * const validator = new AjvJsonSchemaValidator(ajv);
  49. * ```
  50. */
  51. constructor(ajv) {
  52. this._ajv = ajv ?? createDefaultAjvInstance();
  53. }
  54. /**
  55. * Create a validator for the given JSON Schema
  56. *
  57. * The validator is compiled once and can be reused multiple times.
  58. * If the schema has an $id, it will be cached by AJV automatically.
  59. *
  60. * @param schema - Standard JSON Schema object
  61. * @returns A validator function that validates input data
  62. */
  63. getValidator(schema) {
  64. // Check if schema has $id and is already compiled/cached
  65. const ajvValidator = '$id' in schema && typeof schema.$id === 'string'
  66. ? (this._ajv.getSchema(schema.$id) ?? this._ajv.compile(schema))
  67. : this._ajv.compile(schema);
  68. return (input) => {
  69. const valid = ajvValidator(input);
  70. if (valid) {
  71. return {
  72. valid: true,
  73. data: input,
  74. errorMessage: undefined
  75. };
  76. }
  77. else {
  78. return {
  79. valid: false,
  80. data: undefined,
  81. errorMessage: this._ajv.errorsText(ajvValidator.errors)
  82. };
  83. }
  84. };
  85. }
  86. }
  87. //# sourceMappingURL=ajv-provider.js.map