Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/ajv-validator-compile-reuse.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@modelcontextprotocol/client': patch
'@modelcontextprotocol/server': patch
---

`AjvJsonSchemaValidator` now reuses the compiled validator for a schema without an `$id` when the same schema content is passed again, instead of compiling and retaining a new validator on every `getValidator()` call. Long-running clients and servers that repeatedly validate the same schema, such as a form schema in `elicitInput`, no longer grow the Ajv engine's memory with each call.
18 changes: 17 additions & 1 deletion packages/core-internal/src/validators/ajvProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ export class AjvJsonSchemaValidator implements jsonSchemaValidator {
private _ajv2019: AjvLike | undefined;
/** True iff the constructor received a caller-supplied engine; the `$schema` dispatch is skipped. */
private readonly _userAjv: boolean;
/** Compiled validators for schemas without an `$id`, keyed by their JSON text. */
private readonly _compiledWithoutId = new Map<string, AjvValidateFunction>();

/**
* @param ajv - Optional pre-configured AJV-compatible instance. When supplied, this instance is
Expand Down Expand Up @@ -128,12 +130,26 @@ export class AjvJsonSchemaValidator implements jsonSchemaValidator {
return (this._ajvDraft7 ??= createDefaultAjvInstance(Draft7Ajv));
}

/**
* AJV retains every schema it compiles for the life of the engine, so compiling an equal schema
* again (a re-fetched tool list parses to fresh objects) would grow it without bound. Reuse by content.
*/
private _compileWithoutId(engine: AjvLike, schema: JsonSchemaType): AjvValidateFunction {
const key = JSON.stringify(schema);
let compiled = this._compiledWithoutId.get(key);
if (compiled === undefined) {
compiled = engine.compile(schema);
this._compiledWithoutId.set(key, compiled);
}
return compiled;
}

getValidator<T>(schema: JsonSchemaType): JsonSchemaValidator<T> {
const engine = this._engineFor(schema);
const ajvValidator =
'$id' in schema && typeof schema.$id === 'string'
? (engine.getSchema(schema.$id) ?? engine.compile(schema))
: engine.compile(schema);
: this._compileWithoutId(engine, schema);

return (input: unknown): JsonSchemaValidatorResult<T> => {
const valid = ajvValidator(input);
Expand Down
55 changes: 55 additions & 0 deletions packages/core-internal/test/validators/ajvCompileReuse.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import { Ajv2020 } from 'ajv/dist/2020.js';
import { describe, expect, it, vi } from 'vitest';

import { AjvJsonSchemaValidator } from '../../src/validators/ajvProvider';

const outputSchema = {
type: 'object',
properties: { count: { type: 'number' } },
required: ['count']
};

/** A schema as it arrives again from the wire: equal content, a new object. */
const refetched = (schema: object) => JSON.parse(JSON.stringify(schema)) as typeof outputSchema;

function providerWithCompileSpy() {
const ajv = new Ajv2020({ strict: false, validateSchema: false, allErrors: true });
const compile = vi.spyOn(ajv, 'compile');
return { provider: new AjvJsonSchemaValidator(ajv), compile };
}

describe('AjvJsonSchemaValidator compiled validator reuse', () => {
it('compiles an equal schema without an $id once, even when it arrives as a new object', () => {
const { provider, compile } = providerWithCompileSpy();

const validators = Array.from({ length: 5 }, () => provider.getValidator<{ count: number }>(refetched(outputSchema)));

expect(compile).toHaveBeenCalledTimes(1);
for (const validate of validators) {
expect(validate({ count: 1 })).toEqual({ valid: true, data: { count: 1 }, errorMessage: undefined });
expect(validate({ count: 'x' }).valid).toBe(false);
}
});

it('compiles schemas with different content separately', () => {
const { provider, compile } = providerWithCompileSpy();

const numeric = provider.getValidator({ type: 'number' });
const textual = provider.getValidator({ type: 'string' });

expect(compile).toHaveBeenCalledTimes(2);
expect(numeric(1).valid).toBe(true);
expect(numeric('1').valid).toBe(false);
expect(textual('1').valid).toBe(true);
expect(textual(1).valid).toBe(false);
});

it('still reuses a schema with an $id through the engine instead of the content cache', () => {
const { provider, compile } = providerWithCompileSpy();

provider.getValidator({ $id: 'urn:test:with-id', type: 'string' });
provider.getValidator({ $id: 'urn:test:with-id', type: 'string' });

expect(compile).toHaveBeenCalledTimes(1);
});
});
Loading