UNPKG

run402-mcp

Version:

MCP server for Run402 — full-stack backend infrastructure for AI agents: Postgres, auth, storage, serverless functions and atomic deploys. Paid with x402/MPP. Includes $0.03 image generation.

589 lines • 21 kB
/** * The tools' schema builder: one definition gives a tool's published JSON * Schema, its TypeScript type, and the validation of its arguments and * results. In-house, so `run402-mcp` carries no schema library of its own. * * The API is the subset of zod 3 the tools use, with zod 3's semantics: * methods return new schemas; `optional()`, `nullable()` and `catch`-free * wrappers copy the description, as zod 3 did; an object strips undeclared * keys unless `strict()` (refuse them) or `loose()` (keep them). * * `toJsonSchema` reproduces what zod-to-json-schema 3 (draft-07, `$ref` * strategy `root`, `strictUnions`) emitted for the same definitions, byte for * byte: `src/fixtures/tools-list-4.142.0.json` pins it for all eight tools. * A schema object used twice in one tool is emitted once and referenced by * `$ref` to the path where it first appeared. */ export class SchemaError extends Error { issues; constructor(issues) { super(issues.map((i) => `${i.path.join(".") || "(value)"}: ${i.message}`).join("; ")); this.issues = issues; this.name = "SchemaError"; } } /** Marker returned by a parse that failed; never escapes `safeParse`. */ const INVALID = Symbol("invalid"); function received(value) { if (value === null) return "null"; if (Array.isArray(value)) return "array"; if (typeof value === "number" && Number.isNaN(value)) return "nan"; return typeof value; } function isPlainObject(value) { return typeof value === "object" && value !== null && !Array.isArray(value); } export class Schema { description; /** True when `undefined` passes, which makes an object member optional (zod 3's `isOptional`). */ acceptsUndefined() { return false; } describe(description) { const next = this.copy(); next.description = description; return next; } optional() { return new OptionalSchema(this, this.description); } nullable() { return new NullableSchema(this, this.description); } refine(check, opts) { return new RefinedSchema(this, check, opts); } safeParse(value) { const ctx = { issues: [] }; const data = this.parseAt(value, [], ctx); if (data === INVALID || ctx.issues.length > 0) return { success: false, issues: ctx.issues, error: { issues: ctx.issues } }; return { success: true, data: data }; } /** The parsed value, or a thrown `SchemaError` listing every issue. */ parse(value) { const result = this.safeParse(value); if (!result.success) throw new SchemaError(result.issues); return result.data; } fail(ctx, path, message) { ctx.issues.push({ path: [...path], message, code: "invalid" }); return INVALID; } } export class StringSchema extends Schema { checks; constructor(checks = []) { super(); this.checks = checks; } copy() { const next = new StringSchema(this.checks); next.description = this.description; return next; } with(check) { const next = new StringSchema([...this.checks, check]); next.description = this.description; return next; } min(value) { return this.with({ kind: "min", value }); } max(value) { return this.with({ kind: "max", value }); } regex(value) { return this.with({ kind: "regex", value }); } url() { return this.with({ kind: "url" }); } parseAt(value, path, ctx) { if (typeof value !== "string") return this.fail(ctx, path, `Expected string, received ${received(value)}`); for (const check of this.checks) { const problem = stringProblem(check, value); if (problem) return this.fail(ctx, path, problem); } return value; } emitBody() { const out = { type: "string" }; for (const check of this.checks) { if (check.kind === "min") out.minLength = typeof out.minLength === "number" ? Math.max(out.minLength, check.value) : check.value; else if (check.kind === "max") out.maxLength = typeof out.maxLength === "number" ? Math.min(out.maxLength, check.value) : check.value; else if (check.kind === "url") out.format = "uri"; else if (check.kind === "regex") out.pattern = check.value.source; } return out; } } function stringProblem(check, value) { switch (check.kind) { case "min": return value.length < check.value ? `String must contain at least ${check.value} character(s)` : null; case "max": return value.length > check.value ? `String must contain at most ${check.value} character(s)` : null; case "regex": return check.value.test(value) ? null : "Invalid"; case "url": return URL.canParse(value) ? null : "Invalid url"; } } export class NumberSchema extends Schema { checks; constructor(checks = []) { super(); this.checks = checks; } copy() { const next = new NumberSchema(this.checks); next.description = this.description; return next; } with(check) { const next = new NumberSchema([...this.checks, check]); next.description = this.description; return next; } int() { return this.with({ kind: "int" }); } min(value) { return this.with({ kind: "min", value }); } max(value) { return this.with({ kind: "max", value }); } nonnegative() { return this.with({ kind: "min", value: 0 }); } parseAt(value, path, ctx) { if (typeof value !== "number" || Number.isNaN(value)) return this.fail(ctx, path, `Expected number, received ${received(value)}`); for (const check of this.checks) { if (check.kind === "int" && !Number.isInteger(value)) return this.fail(ctx, path, "Expected integer, received float"); if (check.kind === "min" && value < check.value) return this.fail(ctx, path, `Number must be greater than or equal to ${check.value}`); if (check.kind === "max" && value > check.value) return this.fail(ctx, path, `Number must be less than or equal to ${check.value}`); } return value; } emitBody() { const out = { type: "number" }; for (const check of this.checks) { if (check.kind === "int") out.type = "integer"; else if (check.kind === "min") out.minimum = check.value; else out.maximum = check.value; } return out; } } export class BooleanSchema extends Schema { copy() { const next = new BooleanSchema(); next.description = this.description; return next; } parseAt(value, path, ctx) { return typeof value === "boolean" ? value : this.fail(ctx, path, `Expected boolean, received ${received(value)}`); } emitBody() { return { type: "boolean" }; } } export class NullSchema extends Schema { copy() { const next = new NullSchema(); next.description = this.description; return next; } parseAt(value, path, ctx) { return value === null ? null : this.fail(ctx, path, `Expected null, received ${received(value)}`); } emitBody() { return { type: "null" }; } } export class UnknownSchema extends Schema { copy() { const next = new UnknownSchema(); next.description = this.description; return next; } acceptsUndefined() { return true; } parseAt(value) { return value; } emitBody() { return {}; } } export class LiteralSchema extends Schema { value; constructor(value) { super(); this.value = value; } copy() { const next = new LiteralSchema(this.value); next.description = this.description; return next; } parseAt(value, path, ctx) { return value === this.value ? value : this.fail(ctx, path, `Invalid literal value, expected ${JSON.stringify(this.value)}`); } emitBody() { return { type: typeof this.value, const: this.value }; } } export class EnumSchema extends Schema { values; constructor(values) { super(); this.values = values; } copy() { const next = new EnumSchema(this.values); next.description = this.description; return next; } parseAt(value, path, ctx) { if (typeof value === "string" && this.values.includes(value)) return value; return this.fail(ctx, path, `Invalid enum value. Expected ${this.values.map((v) => `'${v}'`).join(" | ")}, received ${typeof value === "string" ? `'${value}'` : received(value)}`); } emitBody() { return { type: "string", enum: [...this.values] }; } } // ------------------------------------------------------------- containers export class ArraySchema extends Schema { item; minItems; maxItems; constructor(item, minItems, maxItems) { super(); this.item = item; this.minItems = minItems; this.maxItems = maxItems; } copy() { const next = new ArraySchema(this.item, this.minItems, this.maxItems); next.description = this.description; return next; } min(value) { const next = new ArraySchema(this.item, value, this.maxItems); next.description = this.description; return next; } max(value) { const next = new ArraySchema(this.item, this.minItems, value); next.description = this.description; return next; } parseAt(value, path, ctx) { if (!Array.isArray(value)) return this.fail(ctx, path, `Expected array, received ${received(value)}`); if (this.minItems !== undefined && value.length < this.minItems) return this.fail(ctx, path, `Array must contain at least ${this.minItems} element(s)`); if (this.maxItems !== undefined && value.length > this.maxItems) return this.fail(ctx, path, `Array must contain at most ${this.maxItems} element(s)`); const out = value.map((entry, i) => this.item.parseAt(entry, [...path, i], ctx)); return out.includes(INVALID) ? INVALID : out; } emitBody(refs) { const out = { type: "array", items: emit(this.item, { ...refs, currentPath: [...refs.currentPath, "items"] }) }; if (this.minItems !== undefined) out.minItems = this.minItems; if (this.maxItems !== undefined) out.maxItems = this.maxItems; return out; } } export class RecordSchema extends Schema { valueSchema; constructor(valueSchema) { super(); this.valueSchema = valueSchema; } copy() { const next = new RecordSchema(this.valueSchema); next.description = this.description; return next; } parseAt(value, path, ctx) { if (!isPlainObject(value)) return this.fail(ctx, path, `Expected object, received ${received(value)}`); const out = {}; let ok = true; for (const [key, entry] of Object.entries(value)) { const parsed = this.valueSchema.parseAt(entry, [...path, key], ctx); if (parsed === INVALID) ok = false; else defineOwn(out, key, parsed); } return ok ? out : INVALID; } emitBody(refs) { return { type: "object", additionalProperties: emit(this.valueSchema, { ...refs, currentPath: [...refs.currentPath, "additionalProperties"] }) ?? true, }; } } export class ObjectSchema extends Schema { shape; unknownKeys; constructor(shape, unknownKeys) { super(); this.shape = shape; this.unknownKeys = unknownKeys; } copy() { const next = new ObjectSchema(this.shape, this.unknownKeys); next.description = this.description; return next; } strict() { const next = new ObjectSchema(this.shape, "strict"); next.description = this.description; return next; } loose() { const next = new ObjectSchema(this.shape, "loose"); next.description = this.description; return next; } parseAt(value, path, ctx) { if (!isPlainObject(value)) return this.fail(ctx, path, `Expected object, received ${received(value)}`); const out = {}; let ok = true; for (const [key, member] of Object.entries(this.shape)) { const present = Object.hasOwn(value, key); const parsed = member.parseAt(present ? value[key] : undefined, [...path, key], ctx); if (parsed === INVALID) ok = false; else if (present || parsed !== undefined) defineOwn(out, key, parsed); } const undeclared = Object.keys(value).filter((key) => !Object.hasOwn(this.shape, key)); if (undeclared.length > 0 && this.unknownKeys === "strict") { ctx.issues.push({ path: [...path], message: `Unrecognized key(s) in object: ${undeclared.map((k) => `'${k}'`).join(", ")}`, code: "unrecognized_keys", keys: undeclared, declared: Object.keys(this.shape) }); ok = false; } if (this.unknownKeys === "loose") for (const key of undeclared) defineOwn(out, key, value[key]); return ok ? out : INVALID; } emitBody(refs) { const properties = {}; const required = []; for (const [key, member] of Object.entries(this.shape)) { const memberPath = [...refs.currentPath, "properties", key]; const emitted = emit(member, { ...refs, currentPath: memberPath, propertyPath: memberPath }); if (emitted === undefined) continue; properties[key] = emitted; if (!member.acceptsUndefined()) required.push(key); } const out = { type: "object", properties }; if (required.length > 0) out.required = required; out.additionalProperties = this.unknownKeys === "loose"; return out; } } /** A JSON object member named `__proto__` stays an own property, as `JSON.parse` keeps it. */ function defineOwn(target, key, value) { Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true }); } const PRIMITIVE_TYPE = new Map([ [StringSchema, "string"], [NumberSchema, "number"], [BooleanSchema, "boolean"], [NullSchema, "null"], ]); /** The JSON type of an unchecked primitive schema (the shapes zod-to-json-schema collapses), else undefined. */ function plainPrimitiveType(schema) { const type = PRIMITIVE_TYPE.get(schema.constructor); if (type === undefined) return undefined; const checks = schema.checks; return checks && checks.length > 0 ? undefined : type; } export class UnionSchema extends Schema { options; constructor(options) { super(); this.options = options; } copy() { const next = new UnionSchema(this.options); next.description = this.description; return next; } acceptsUndefined() { return this.options.some((option) => option.acceptsUndefined()); } parseAt(value, path, ctx) { for (const option of this.options) { const attempt = { issues: [] }; const parsed = option.parseAt(value, path, attempt); if (parsed !== INVALID && attempt.issues.length === 0) return parsed; } return this.fail(ctx, path, "Invalid input"); } emitBody(refs) { const types = this.options.map(plainPrimitiveType); if (types.every((t) => t !== undefined)) { const unique = [...new Set(types)]; return { type: unique.length > 1 ? unique : unique[0] }; } if (this.options.every((o) => o instanceof LiteralSchema && o.description === undefined)) { const literals = this.options; const unique = [...new Set(literals.map((o) => typeof o.value))]; return { type: unique.length > 1 ? unique : unique[0], enum: [...new Set(literals.map((o) => o.value))] }; } if (this.options.every((o) => o instanceof EnumSchema)) { const values = this.options.flatMap((o) => o.values); return { type: "string", enum: [...new Set(values)] }; } const anyOf = this.options .map((option, i) => emit(option, { ...refs, currentPath: [...refs.currentPath, "anyOf", `${i}`] })) .filter((x) => x !== undefined && Object.keys(x).length > 0); return anyOf.length > 0 ? { anyOf } : undefined; } } // --------------------------------------------------------------- wrappers export class OptionalSchema extends Schema { inner; constructor(inner, description) { super(); this.inner = inner; this.description = description; } copy() { return new OptionalSchema(this.inner, this.description); } acceptsUndefined() { return true; } parseAt(value, path, ctx) { return value === undefined ? undefined : this.inner.parseAt(value, path, ctx); } emitBody(refs) { if (refs.currentPath.join(",") === refs.propertyPath?.join(",")) return emit(this.inner, refs); const inner = emit(this.inner, { ...refs, currentPath: [...refs.currentPath, "anyOf", "1"] }); return inner ? { anyOf: [{ not: {} }, inner] } : {}; } } export class NullableSchema extends Schema { inner; constructor(inner, description) { super(); this.inner = inner; this.description = description; } copy() { return new NullableSchema(this.inner, this.description); } acceptsUndefined() { return this.inner.acceptsUndefined(); } parseAt(value, path, ctx) { return value === null ? null : this.inner.parseAt(value, path, ctx); } emitBody(refs) { const type = plainPrimitiveType(this.inner); if (type !== undefined) return { type: [type, "null"] }; const base = emit(this.inner, { ...refs, currentPath: [...refs.currentPath, "anyOf", "0"] }); return base && { anyOf: [base, { type: "null" }] }; } } export class RefinedSchema extends Schema { inner; check; opts; constructor(inner, check, opts) { super(); this.inner = inner; this.check = check; this.opts = opts; } copy() { const next = new RefinedSchema(this.inner, this.check, this.opts); next.description = this.description; return next; } acceptsUndefined() { return this.inner.acceptsUndefined(); } parseAt(value, path, ctx) { const parsed = this.inner.parseAt(value, path, ctx); if (parsed === INVALID) return INVALID; if (!this.check(parsed)) return this.fail(ctx, [...path, ...(this.opts.path ?? [])], this.opts.message); return parsed; } emitBody(refs) { return emit(this.inner, refs); } } /** zod-to-json-schema's `parseDef`: a schema seen before in this document is a `$ref` to where it first appeared. */ function emit(schema, refs) { const seenAt = refs.seen.get(schema); if (seenAt) return { $ref: seenAt.join("/") }; refs.seen.set(schema, refs.currentPath); const body = schema.emitBody(refs); if (body && schema.description !== undefined) body.description = schema.description; return body; } /** The draft-07 JSON Schema a tool publishes for this schema. */ export function toJsonSchema(schema) { const main = emit(schema, { currentPath: ["#"], propertyPath: undefined, seen: new Map() }) ?? {}; return { ...main, $schema: "http://json-schema.org/draft-07/schema#" }; } // ------------------------------------------------------------- factories export const z = { string: () => new StringSchema(), number: () => new NumberSchema(), boolean: () => new BooleanSchema(), null: () => new NullSchema(), unknown: () => new UnknownSchema(), literal: (value) => new LiteralSchema(value), enum: (values) => new EnumSchema(values), array: (item) => new ArraySchema(item), record: (_key, value) => new RecordSchema(value), union: (options) => new UnionSchema(options), object: (shape) => new ObjectSchema(shape, "strip"), }; //# sourceMappingURL=schema.js.map