Skip to content

Never stop coding. Free MIT AI gateway: one endpoint, 375 providers (150+ free), 1,400+ models Kimi, Claude, GPT, Gemini, GLM, DeepSeek, MiniMax. Works with Claude Code, Codex, Cursor, OpenCode, Cline & Copilot. Quota-aware auto-fallback, RTK+Caveman compression saves 15-95% tokens, MCP/A2A, Desktop/PWA. Built by 900+ contributors

fix(sse): sanitize OpenAI tool schemas for strict upstream validators (kimi-k2.6 via opencode-go) (#1692)

payne67bce7721ba6
diff --git a/open-sse/handlers/chatCore.ts b/open-sse/handlers/chatCore.ts
index b32ee29255..fb2198aeaa 100644
--- a/open-sse/handlers/chatCore.ts
+++ b/open-sse/handlers/chatCore.ts
@@ -73,6 +73,7 @@ import {
import { getCacheMetrics } from "@/lib/db/settings.ts";
import { getCachedSettings } from "@/lib/db/readCache";
import { cacheReasoningFromAssistantMessage } from "../services/reasoningCache.ts";
+import { sanitizeOpenAITool } from "../services/toolSchemaSanitizer.ts";
import {
parseCodexQuotaHeaders,
@@ -1433,6 +1434,13 @@ export async function handleChatCore({
const name = fn?.name ?? tool.name;
return name && String(name).trim().length > 0;
});
+
+ // Sanitize OpenAI-format function tool schemas before they reach strict
+ // upstream JSON Schema validators (e.g. Moonshot AI behind
+ // opencode-go/kimi-k2.6). See toolSchemaSanitizer.ts for the specific bug.
+ // sanitizeOpenAITool is safe to call on any input — it no-ops non-function
+ // tools (e.g. Responses API built-ins) and non-object values.
+ body.tools = body.tools.map((tool) => sanitizeOpenAITool(tool) as (typeof body.tools)[number]);
}
const memoryOwnerId = resolveMemoryOwnerId(apiKeyInfo as Record<string, unknown> | null);
diff --git a/open-sse/services/toolSchemaSanitizer.ts b/open-sse/services/toolSchemaSanitizer.ts
new file mode 100644
index 0000000000..1606be64e4
--- /dev/null
+++ b/open-sse/services/toolSchemaSanitizer.ts
@@ -0,0 +1,120 @@
+/**
+ * Sanitize OpenAI-format tool definitions for strict upstream JSON Schema
+ * validators (e.g. Moonshot AI behind opencode-go/kimi-k2.6).
+ *
+ * The concrete bug this was written for: ForgeCode emits enum schemas like
+ * { type: "string", enum: ["a", "b", "c", null], nullable: true }
+ * for nullable optional fields. Lenient providers (Z.AI / GLM) accept the null
+ * entry; Moonshot rejects with
+ * "At path 'properties.X.enum': enum value (<nil>) does not match any type
+ * in [string]"
+ * before the request reaches the model.
+ *
+ * The fix is to strip null/undefined from `enum` arrays. Everything else here
+ * is defensive hygiene: ensures `parameters` is always a valid object schema,
+ * filters `required[]` to keys that exist in `properties`, and normalizes a
+ * few other shapes that strict validators tend to reject.
+ */
+
+const MAX_RECURSION_DEPTH = 32;
+
+function isPlainObject(v: unknown): v is Record<string, unknown> {
+ return v !== null && typeof v === "object" && !Array.isArray(v);
+}
+
+function sanitizeSchema(value: unknown, depth = 0): Record<string, unknown> {
+ if (depth > MAX_RECURSION_DEPTH) return {};
+ if (!isPlainObject(value)) return {};
+
+ const result: Record<string, unknown> = {};
+
+ for (const [k, v] of Object.entries(value)) {
+ if (v === null || v === undefined) continue;
+
+ if (k === "properties" && isPlainObject(v)) {
+ const cleaned: Record<string, unknown> = {};
+ for (const [pk, pv] of Object.entries(v)) {
+ if (isPlainObject(pv)) {
+ cleaned[pk] = sanitizeSchema(pv, depth + 1);
+ } else if (typeof pv === "boolean") {
+ // JSON Schema 2019 boolean form: `true` (anything) / `false` (nothing).
+ // Preserve as-is; Moonshot accepts these.
+ cleaned[pk] = pv;
+ } else {
+ cleaned[pk] = {};
+ }
+ }
+ result[k] = cleaned;
+ } else if (k === "items") {
+ // Recurse into items if it's a single schema. Tuple-form (array) is
+ // valid JSON Schema but rejected by Moonshot; coerce to single schema.
+ if (Array.isArray(v)) {
+ const firstObject = v.find(isPlainObject);
+ result[k] = firstObject ? sanitizeSchema(firstObject, depth + 1) : {};
+ } else if (isPlainObject(v)) {
+ result[k] = sanitizeSchema(v, depth + 1);
+ }
+ } else if (k === "anyOf" || k === "oneOf" || k === "allOf") {
+ // Moonshot recursively validates inside `anyOf` (confirmed empirically),
+ // so we must descend to strip null-in-enum etc. `oneOf`/`allOf` aren't
+ // currently validated by Moonshot but are recursed for symmetry/defense.
+ if (Array.isArray(v)) {
+ result[k] = v.map((s) => (isPlainObject(s) ? sanitizeSchema(s, depth + 1) : {}));
+ }
+ } else if (k === "additionalProperties") {
+ // Moonshot recursively validates the schema form of additionalProperties
+ // (confirmed empirically). The boolean form is also valid JSON Schema.
+ if (isPlainObject(v)) {
+ result[k] = sanitizeSchema(v, depth + 1);
+ } else if (typeof v === "boolean") {
+ result[k] = v;
+ }
+ } else if (k === "enum" && Array.isArray(v)) {
+ // The actual fix: strip null/undefined entries that ForgeCode adds for
+ // nullable optional fields.
+ result[k] = v.filter((e) => e !== null && e !== undefined);
+ } else if (k === "required" && Array.isArray(v)) {
+ result[k] = v.filter((r) => typeof r === "string");
+ } else {
+ result[k] = v;
+ }
+ }
+
+ if (Array.isArray(result.required) && isPlainObject(result.properties)) {
+ const validKeys = new Set(Object.keys(result.properties));
+ result.required = (result.required as string[]).filter((r) => validKeys.has(r));
+ }
+
+ return result;
+}
+
+function normalizeParameters(parameters: unknown): unknown {
+ if (isPlainObject(parameters)) return sanitizeSchema(parameters);
+ if (parameters === null || parameters === undefined) {
+ return { type: "object", properties: {} };
+ }
+ return { type: "object", properties: {} };
+}
+
+export function sanitizeOpenAITool(tool: unknown): unknown {
+ if (!isPlainObject(tool)) return tool;
+ const t = { ...tool };
+
+ if (isPlainObject(t.function)) {
+ // Chat Completions format: { type: "function", function: { name, parameters } }
+ const f = { ...t.function };
+ f.parameters = normalizeParameters(f.parameters);
+ t.function = f;
+ } else if (t.type === "function") {
+ // Responses API format: { type: "function", name, parameters } — no `function`
+ // wrapper. /v1/responses requests reach chatCore in this shape and are only
+ // unwrapped later by the request translator, so we have to sanitize here too.
+ t.parameters = normalizeParameters(t.parameters);
+ }
+
+ return t;
+}
+
+export function sanitizeOpenAITools(tools: unknown[]): unknown[] {
+ return tools.map(sanitizeOpenAITool);
+}
diff --git a/tests/unit/tool-schema-sanitizer.test.mjs b/tests/unit/tool-schema-sanitizer.test.mjs
new file mode 100644
index 0000000000..a83965136d
--- /dev/null
+++ b/tests/unit/tool-schema-sanitizer.test.mjs
@@ -0,0 +1,446 @@
+import { describe, it } from "node:test";
+import assert from "node:assert/strict";
+
+const { sanitizeOpenAITool, sanitizeOpenAITools } =
+ await import("../../open-sse/services/toolSchemaSanitizer.ts");
+
+describe("toolSchemaSanitizer", () => {
+ describe("enum null filter (the actual fix)", () => {
+ it("strips null entries from enum (ForgeCode + Moonshot reproduction)", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "fs_search",
+ parameters: {
+ type: "object",
+ properties: {
+ output_mode: {
+ type: "string",
+ enum: ["content", "files_with_matches", "count", null],
+ nullable: true,
+ },
+ },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.output_mode.enum, [
+ "content",
+ "files_with_matches",
+ "count",
+ ]);
+ });
+
+ it("strips undefined entries from enum", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: { mode: { type: "string", enum: ["a", undefined, "b"] } },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.mode.enum, ["a", "b"]);
+ });
+
+ it("preserves enum without null/undefined", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: { mode: { type: "string", enum: ["a", "b", "c"] } },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.mode.enum, ["a", "b", "c"]);
+ });
+ });
+
+ describe("required[] filter", () => {
+ it("drops required keys that are absent from properties", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: { a: { type: "string" } },
+ required: ["a", "b", "c"],
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.a, { type: "string" });
+ assert.deepEqual(out.function.parameters.required, ["a"]);
+ });
+
+ it("filters non-string entries in required[]", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: { a: { type: "string" } },
+ required: ["a", null, 123, undefined],
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.required, ["a"]);
+ });
+ });
+
+ describe("items normalization", () => {
+ it("collapses tuple items to first plain-object schema", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: {
+ list: { type: "array", items: [{ type: "string" }, { type: "number" }] },
+ },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.list.items, {
+ type: "string",
+ });
+ });
+
+ it("falls back to empty schema when tuple has no plain-object entries", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: {
+ list: { type: "array", items: [null, "junk", 1] },
+ },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.list.items, {});
+ });
+
+ it("preserves single-object items unchanged", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: {
+ list: { type: "array", items: { type: "string" } },
+ },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.list.items, {
+ type: "string",
+ });
+ });
+ });
+
+ describe("parameters shape normalization", () => {
+ it("creates empty object schema when parameters is null", () => {
+ const tool = {
+ type: "function",
+ function: { name: "x", parameters: null },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters, { type: "object", properties: {} });
+ });
+
+ it("creates empty object schema when parameters is missing", () => {
+ const tool = { type: "function", function: { name: "x" } };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters, { type: "object", properties: {} });
+ });
+
+ it("replaces non-object/non-boolean property values with empty schema", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: { a: null, b: 1, c: "string-not-object" },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.a, {});
+ assert.deepEqual(out.function.parameters.properties.b, {});
+ assert.deepEqual(out.function.parameters.properties.c, {});
+ });
+
+ it("preserves valid property schemas", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: {
+ a: { type: "string", description: "first" },
+ b: { type: "integer", minimum: 0 },
+ },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.a, {
+ type: "string",
+ description: "first",
+ });
+ assert.deepEqual(out.function.parameters.properties.b, {
+ type: "integer",
+ minimum: 0,
+ });
+ });
+ });
+
+ describe("anyOf / oneOf / allOf recursion", () => {
+ it("strips null from enum nested inside anyOf (Moonshot validates here)", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: {
+ mode: {
+ anyOf: [{ type: "string", enum: ["a", "b", null] }, { type: "null" }],
+ },
+ },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.mode.anyOf[0].enum, ["a", "b"]);
+ });
+
+ it("strips null from enum nested inside oneOf", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: {
+ mode: {
+ oneOf: [{ type: "string", enum: ["a", null] }, { type: "integer" }],
+ },
+ },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.mode.oneOf[0].enum, ["a"]);
+ });
+
+ it("strips null from enum nested inside allOf", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: {
+ mode: {
+ allOf: [{ type: "string", enum: ["a", null] }],
+ },
+ },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.mode.allOf[0].enum, ["a"]);
+ });
+
+ it("replaces non-object entries inside anyOf/oneOf/allOf with empty schema", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: {
+ mode: { anyOf: [{ type: "string" }, null, "junk", 1] },
+ },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.mode.anyOf, [
+ { type: "string" },
+ {},
+ {},
+ {},
+ ]);
+ });
+ });
+
+ describe("additionalProperties recursion", () => {
+ it("strips null from enum nested inside additionalProperties (Moonshot validates here)", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: {
+ map: {
+ type: "object",
+ additionalProperties: { type: "string", enum: ["a", null] },
+ },
+ },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.map.additionalProperties.enum, ["a"]);
+ });
+
+ it("preserves boolean additionalProperties", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: {
+ map: { type: "object", additionalProperties: false },
+ },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.equal(out.function.parameters.properties.map.additionalProperties, false);
+ });
+ });
+
+ describe("boolean property schemas (JSON Schema 2019)", () => {
+ it("preserves true / false property values rather than coercing to {}", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: { allow_anything: true, deny_anything: false },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.equal(out.function.parameters.properties.allow_anything, true);
+ assert.equal(out.function.parameters.properties.deny_anything, false);
+ });
+
+ it("still coerces other non-object property values (null, string, number) to {}", () => {
+ const tool = {
+ type: "function",
+ function: {
+ name: "x",
+ parameters: {
+ type: "object",
+ properties: { a: null, b: "junk", c: 1 },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.function.parameters.properties.a, {});
+ assert.deepEqual(out.function.parameters.properties.b, {});
+ assert.deepEqual(out.function.parameters.properties.c, {});
+ });
+ });
+
+ describe("Responses API tool shape (top-level parameters)", () => {
+ it("strips null from enum in Responses-format tool (top-level parameters)", () => {
+ // /v1/responses tools have { type, name, parameters } at top level — no
+ // `function` wrapper. They reach chatCore in this shape before the
+ // request translator unwraps them, so the sanitizer must handle both.
+ const tool = {
+ type: "function",
+ name: "fs_search",
+ description: "search",
+ parameters: {
+ type: "object",
+ properties: {
+ output_mode: {
+ type: "string",
+ enum: ["a", "b", null],
+ },
+ },
+ },
+ };
+ const out = sanitizeOpenAITool(tool);
+ assert.equal(out.name, "fs_search");
+ assert.deepEqual(out.parameters.properties.output_mode.enum, ["a", "b"]);
+ });
+
+ it("normalizes missing parameters in Responses-format tool", () => {
+ const tool = { type: "function", name: "x" };
+ const out = sanitizeOpenAITool(tool);
+ assert.deepEqual(out.parameters, { type: "object", properties: {} });
+ });
+
+ it("does not touch Responses-format tool without type=function", () => {
+ const tool = { type: "web_search", name: "websearch" };
+ assert.deepEqual(sanitizeOpenAITool(tool), {
+ type: "web_search",
+ name: "websearch",
+ });
+ });
+ });
+
+ describe("non-function tools", () => {
+ it("leaves Responses API built-in tool types untouched", () => {
+ const tool = { type: "web_search" };
+ assert.deepEqual(sanitizeOpenAITool(tool), { type: "web_search" });
+ });
+ });
+
+ describe("sanitizeOpenAITools", () => {
+ it("maps over an array", () => {
+ const tools = [
+ {
+ type: "function",
+ function: {
+ name: "a",
+ parameters: {
+ type: "object",
+ properties: { m: { type: "string", enum: ["x", null] } },
+ },
+ },
+ },
+ {
+ type: "function",
+ function: {
+ name: "b",
+ parameters: {
+ type: "object",
+ properties: { n: { type: "string" } },
+ },
+ },
+ },
+ ];
+ const out = sanitizeOpenAITools(tools);
+ assert.deepEqual(out[0].function.parameters.properties.m.enum, ["x"]);
+ assert.deepEqual(out[1].function.parameters.properties.n, { type: "string" });
+ });
+ });
+});