Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(model-runtime): normalize tool array `items` schema before sending to providers (#16153)

Arvin Xua924178b13ed
diff --git a/packages/model-runtime/src/core/contextBuilders/google.ts b/packages/model-runtime/src/core/contextBuilders/google.ts
index 77ff6c7364e..914ca074713 100644
--- a/packages/model-runtime/src/core/contextBuilders/google.ts
+++ b/packages/model-runtime/src/core/contextBuilders/google.ts
@@ -385,6 +385,10 @@ export const buildGoogleMessages = async (
* @see https://linear.app/lobehub/issue/
*/
export const sanitizeGeminiSchema = (schema: any): any => {
+ // A boolean schema (`items: true`) is valid JSON Schema but rejected by
+ // Gemini's proto validator. Collapse it to the permissive empty object schema.
+ // See https://linear.app/lobehub/issue/LOBE-10066
+ if (typeof schema === 'boolean') return {};
if (!schema || typeof schema !== 'object') return schema;
const sanitized = { ...schema };
@@ -440,9 +444,12 @@ export const sanitizeGeminiSchema = (schema: any): any => {
}
}
- // Recursively sanitize items (for array types)
- if (sanitized.items) {
+ // Recursively sanitize items (for array types). A node carrying `items` is an
+ // array node; backfill a missing `type` so Gemini's predicate validator
+ // (`$type == Type.ARRAY`) accepts it. See LOBE-10066.
+ if ('items' in sanitized) {
sanitized.items = sanitizeGeminiSchema(sanitized.items);
+ if (sanitized.type === undefined) sanitized.type = 'array';
}
// Recursively sanitize anyOf/oneOf/allOf combinators
diff --git a/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.test.ts b/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.test.ts
new file mode 100644
index 00000000000..c89c4b56547
--- /dev/null
+++ b/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.test.ts
@@ -0,0 +1,144 @@
+import type OpenAI from 'openai';
+import { describe, expect, it } from 'vitest';
+
+import { normalizeToolJsonSchema, normalizeToolsParameters } from './normalizeToolSchema';
+
+describe('normalizeToolJsonSchema', () => {
+ it('collapses a top-level boolean schema to an empty object', () => {
+ expect(normalizeToolJsonSchema(true)).toEqual({});
+ expect(normalizeToolJsonSchema(false)).toEqual({});
+ });
+
+ it('returns primitives untouched', () => {
+ expect(normalizeToolJsonSchema(null)).toBeNull();
+ expect(normalizeToolJsonSchema(undefined)).toBeUndefined();
+ expect(normalizeToolJsonSchema('foo')).toBe('foo');
+ });
+
+ // LOBE-10066: deepseek variant β€” array property with `items: true`
+ it('rewrites `items: true` to an empty object schema', () => {
+ const result = normalizeToolJsonSchema({
+ properties: {
+ sourceIds: { items: true, type: 'array' },
+ },
+ type: 'object',
+ });
+
+ expect(result.properties.sourceIds.items).toEqual({});
+ expect(result.properties.sourceIds.type).toBe('array');
+ });
+
+ // LOBE-10066: gemini variant β€” array property carrying `items` but missing `type`
+ it('backfills `type: array` on a node that carries `items` without a type', () => {
+ const result = normalizeToolJsonSchema({
+ properties: {
+ sourceIds: { items: { type: 'string' } },
+ },
+ type: 'object',
+ });
+
+ expect(result.properties.sourceIds.type).toBe('array');
+ expect(result.properties.sourceIds.items).toEqual({ type: 'string' });
+ });
+
+ it('does not override an existing array type', () => {
+ const result = normalizeToolJsonSchema({
+ items: { type: 'number' },
+ type: ['array', 'null'],
+ });
+
+ expect(result.type).toEqual(['array', 'null']);
+ });
+
+ it('normalizes nested items within items (array of arrays)', () => {
+ const result = normalizeToolJsonSchema({
+ items: { items: true },
+ type: 'array',
+ });
+
+ expect(result.items.type).toBe('array');
+ expect(result.items.items).toEqual({});
+ });
+
+ it('recurses into anyOf / oneOf / allOf combinators', () => {
+ const result = normalizeToolJsonSchema({
+ anyOf: [{ items: true }, { type: 'string' }],
+ });
+
+ expect(result.anyOf[0].items).toEqual({});
+ expect(result.anyOf[0].type).toBe('array');
+ expect(result.anyOf[1]).toEqual({ type: 'string' });
+ });
+
+ it('recurses into $defs / definitions', () => {
+ const result = normalizeToolJsonSchema({
+ $defs: {
+ Tag: { items: true },
+ },
+ type: 'object',
+ });
+
+ expect(result.$defs.Tag.items).toEqual({});
+ expect(result.$defs.Tag.type).toBe('array');
+ });
+
+ it('recurses into prefixItems and object additionalProperties', () => {
+ const result = normalizeToolJsonSchema({
+ additionalProperties: { items: true },
+ prefixItems: [{ items: true }],
+ type: 'object',
+ });
+
+ expect(result.prefixItems[0].items).toEqual({});
+ expect(result.additionalProperties.items).toEqual({});
+ });
+
+ it('keeps boolean additionalProperties untouched (a valid, accepted form)', () => {
+ expect(normalizeToolJsonSchema({ additionalProperties: false, type: 'object' })).toEqual({
+ additionalProperties: false,
+ type: 'object',
+ });
+ });
+
+ it('does not mutate the input schema', () => {
+ const input = { properties: { ids: { items: true, type: 'array' } }, type: 'object' };
+ const snapshot = JSON.parse(JSON.stringify(input));
+
+ normalizeToolJsonSchema(input);
+
+ expect(input).toEqual(snapshot);
+ });
+});
+
+describe('normalizeToolsParameters', () => {
+ it('returns undefined when no tools are provided', () => {
+ expect(normalizeToolsParameters(undefined)).toBeUndefined();
+ });
+
+ it('normalizes the parameters of every function tool', () => {
+ const tools: OpenAI.ChatCompletionTool[] = [
+ {
+ function: {
+ name: 'reetp14-openalex-mcp____autocomplete____mcp',
+ parameters: {
+ properties: { sourceIds: { items: true, type: 'array' } },
+ type: 'object',
+ },
+ },
+ type: 'function',
+ },
+ ];
+
+ const result = normalizeToolsParameters(tools)!;
+
+ expect((result[0] as any).function.parameters.properties.sourceIds.items).toEqual({});
+ });
+
+ it('leaves tools without parameters untouched', () => {
+ const tools: OpenAI.ChatCompletionTool[] = [
+ { function: { name: 'noParams' }, type: 'function' },
+ ];
+
+ expect(normalizeToolsParameters(tools)).toEqual(tools);
+ });
+});
diff --git a/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.ts b/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.ts
new file mode 100644
index 00000000000..90c212327d2
--- /dev/null
+++ b/packages/model-runtime/src/core/contextBuilders/normalizeToolSchema.ts
@@ -0,0 +1,106 @@
+import type OpenAI from 'openai';
+
+/**
+ * Normalize a JSON Schema fragment into a shape that strict provider
+ * function-schema validators (OpenAI / DeepSeek, Gemini, ...) accept.
+ *
+ * User-supplied MCP tool schemas sometimes carry non-trivial JSON Schema
+ * constructs that are individually valid but rejected by upstream validators:
+ *
+ * - **Boolean sub-schema** (`items: true`, meaning "any element"). Valid JSON
+ * Schema, but OpenAI / DeepSeek reject it with
+ * `Invalid schema for function '...': true is not of type "array"`.
+ * β†’ rewrite the boolean schema to an empty object schema `{}`.
+ * - **Array property missing `type`** β€” a node carries `items` but omits
+ * `type: 'array'`. Gemini rejects it with
+ * `field predicate failed: $type == Type.ARRAY`.
+ * β†’ backfill `type: 'array'`.
+ *
+ * Normalization is the harness's responsibility (the same family as the Gemini
+ * enum / required sanitizers), so we clean the schema before it reaches any
+ * provider rather than letting the request fail anonymously upstream.
+ *
+ * @see https://linear.app/lobehub/issue/LOBE-10066
+ */
+export const normalizeToolJsonSchema = (schema: any): any => {
+ // A boolean schema (`true` = accept anything, `false` = accept nothing) is
+ // valid JSON Schema but rejected by function-schema validators that expect an
+ // object. Collapse it to the permissive empty object schema.
+ if (typeof schema === 'boolean') return {};
+ if (!schema || typeof schema !== 'object') return schema;
+ if (Array.isArray(schema)) return schema.map((item) => normalizeToolJsonSchema(item));
+
+ const normalized: Record<string, any> = { ...schema };
+
+ // Recurse object property schemas
+ if (normalized.properties && typeof normalized.properties === 'object') {
+ const props: Record<string, any> = {};
+ for (const key of Object.keys(normalized.properties)) {
+ props[key] = normalizeToolJsonSchema(normalized.properties[key]);
+ }
+ normalized.properties = props;
+ }
+
+ // A node carrying `items` is an array node. Normalize the `items` sub-schema
+ // (collapsing a boolean such as `items: true`) and backfill a missing `type`
+ // so predicate-checking validators (Gemini) accept it.
+ if ('items' in normalized) {
+ normalized.items = normalizeToolJsonSchema(normalized.items);
+ if (normalized.type === undefined) normalized.type = 'array';
+ }
+
+ // Tuple-style validation (`prefixItems`) β€” same boolean-collapse treatment.
+ if (Array.isArray(normalized.prefixItems)) {
+ normalized.prefixItems = normalized.prefixItems.map(normalizeToolJsonSchema);
+ }
+
+ // `additionalProperties` may be a nested schema. Leave the boolean form alone
+ // (a boolean is meaningful and accepted here); only recurse the object form.
+ if (normalized.additionalProperties && typeof normalized.additionalProperties === 'object') {
+ normalized.additionalProperties = normalizeToolJsonSchema(normalized.additionalProperties);
+ }
+
+ // Combinators
+ for (const key of ['anyOf', 'oneOf', 'allOf']) {
+ if (Array.isArray(normalized[key])) {
+ normalized[key] = normalized[key].map(normalizeToolJsonSchema);
+ }
+ }
+
+ // Definition maps
+ for (const key of ['definitions', '$defs']) {
+ if (normalized[key] && typeof normalized[key] === 'object') {
+ const defs: Record<string, any> = {};
+ for (const defKey of Object.keys(normalized[key])) {
+ defs[defKey] = normalizeToolJsonSchema(normalized[key][defKey]);
+ }
+ normalized[key] = defs;
+ }
+ }
+
+ return normalized;
+};
+
+/**
+ * Normalize the parameter JSON Schema of every function tool in a tool list.
+ * Non-function tools and tools without parameters are returned untouched.
+ *
+ * @see {@link normalizeToolJsonSchema}
+ */
+export const normalizeToolsParameters = <T extends OpenAI.ChatCompletionTool[] | undefined>(
+ tools: T,
+): T => {
+ if (!tools) return tools;
+
+ return tools.map((tool) => {
+ if (tool.type !== 'function' || !tool.function?.parameters) return tool;
+
+ return {
+ ...tool,
+ function: {
+ ...tool.function,
+ parameters: normalizeToolJsonSchema(tool.function.parameters),
+ },
+ };
+ }) as T;
+};
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
index 0f01c2e61ae..c37412360f7 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.test.ts
@@ -133,6 +133,42 @@ describe('LobeOpenAICompatibleFactory', () => {
expect(result).toBeInstanceOf(Response);
});
+ // LOBE-10066: MCP tool schemas with `items: true` or array props missing
+ // `type` must be normalized before reaching the upstream validator.
+ it('should normalize tool parameter schemas before sending to upstream', async () => {
+ (instance['client'].chat.completions.create as Mock).mockResolvedValue(
+ Promise.resolve(new ReadableStream()),
+ );
+
+ await instance.chat({
+ messages: [{ content: 'Hello', role: 'user' }],
+ model: 'mistralai/mistral-7b-instruct:free',
+ temperature: 0.7,
+ tools: [
+ {
+ function: {
+ name: 'mcp_tool',
+ parameters: {
+ properties: {
+ ids: { items: true, type: 'array' },
+ sourceIds: { items: { type: 'string' } },
+ },
+ type: 'object',
+ },
+ },
+ type: 'function',
+ },
+ ],
+ });
+
+ const callArgs = (instance['client'].chat.completions.create as Mock).mock.calls[0][0];
+ const params = callArgs.tools[0].function.parameters;
+ // `items: true` collapsed to `{}`
+ expect(params.properties.ids.items).toEqual({});
+ // array prop missing `type` gets backfilled
+ expect(params.properties.sourceIds.type).toBe('array');
+ });
+
it('should keep logical model for provider payload handling while sending mapped model id', async () => {
const handlePayload = vi.fn(
(payload: ChatStreamPayload): OpenAI.ChatCompletionCreateParamsStreaming => ({
diff --git a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
index 2891ce84777..4b0da82f3d4 100644
--- a/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
+++ b/packages/model-runtime/src/core/openaiCompatibleFactory/index.ts
@@ -58,6 +58,7 @@ import {
} from '../../utils/resolveSafeMaxTokens';
import { StreamingResponse } from '../../utils/response';
import type { LobeRuntimeAI } from '../BaseAI';
+import { normalizeToolsParameters } from '../contextBuilders/normalizeToolSchema';
import { convertOpenAIMessages, convertOpenAIResponseInputs } from '../contextBuilders/openai';
import { resolveModelSamplingParameters } from '../parameterResolver';
import type { OpenAIStreamOptions } from '../streams';
@@ -507,6 +508,12 @@ export const createOpenAICompatibleRuntime = <T extends Record<string, any> = an
log('chat called with model: %s, stream: %s', payload.model, payload.stream ?? true);
+ // Normalize tool parameter schemas before they fan out to the
+ // Chat-Completions / Responses paths. User MCP tools may emit boolean
+ // sub-schemas (`items: true`) or array properties missing `type`, which
+ // upstream validators (OpenAI/DeepSeek, Gemini) reject. See LOBE-10066.
+ if (payload.tools) payload.tools = normalizeToolsParameters(payload.tools as any) as any;
+
let processedPayload: any = payload;
const userApiMode = (payload as any).apiMode as string | undefined;
const modelId = (payload as any).model as string | undefined;