Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix: normalize MCP tool schemas for strict provider validation (#7017) (#7941)

Jordanafeb55c6b894
diff --git a/src-tauri/src/core/server/proxy.rs b/src-tauri/src/core/server/proxy.rs
index 56ee40403..5e63c8d31 100644
--- a/src-tauri/src/core/server/proxy.rs
+++ b/src-tauri/src/core/server/proxy.rs
@@ -24,11 +24,13 @@ use crate::core::{
///
/// A strict JSON schema converter inside the upstream server rejects those schemas.
/// To be robust, we default `type` to `"string"` for description-only leaf schemas.
+/// Keep this behavior aligned with `normalizeToolInputSchema` in the frontend.
pub(crate) fn normalize_openai_tool_parameters_schema(schema: &mut serde_json::Value) {
match schema {
serde_json::Value::Object(map) => {
let has_description = map.contains_key("description");
let has_type = map.contains_key("type");
+ let is_object_type = map.get("type").and_then(|v| v.as_str()) == Some("object");
let has_nested_schema_keywords = map.contains_key("properties")
|| map.contains_key("items")
|| map.contains_key("anyOf")
@@ -36,6 +38,13 @@ pub(crate) fn normalize_openai_tool_parameters_schema(schema: &mut serde_json::V
|| map.contains_key("allOf")
|| map.contains_key("$ref");
+ if is_object_type && !map.contains_key("properties") {
+ map.insert(
+ "properties".to_string(),
+ serde_json::Value::Object(serde_json::Map::new()),
+ );
+ }
+
// Only patch leaf nodes (description without `type` AND without nested schema keywords).
if has_description && !has_type && !has_nested_schema_keywords {
map.insert(
@@ -716,8 +725,11 @@ async fn collect_mcp_openai_tools(
for tool in tools {
tool_to_server.insert(tool.name.to_string(), server_name.clone());
- // Reuse the same schema conversion as the `get_tools` command.
- let parameters = serde_json::Value::Object((*tool.input_schema).clone());
+ // Normalize schemas before sending them to strict OpenAI-compatible providers.
+ // The `get_tools` Tauri command still returns raw schemas; the frontend
+ // normalizes those separately before provider registration.
+ let mut parameters = serde_json::Value::Object((*tool.input_schema).clone());
+ normalize_openai_tool_parameters_schema(&mut parameters);
let description = tool
.description
.as_ref()
diff --git a/src-tauri/src/core/server/tests.rs b/src-tauri/src/core/server/tests.rs
index 25b2dc8a3..4c23c5c47 100644
--- a/src-tauri/src/core/server/tests.rs
+++ b/src-tauri/src/core/server/tests.rs
@@ -313,6 +313,17 @@ mod tests {
assert_eq!(schema["properties"]["url"]["type"], json!("string"));
}
+ #[test]
+ fn adds_empty_properties_for_object_without_properties() {
+ let mut schema = json!({
+ "type": "object"
+ });
+
+ proxy::normalize_openai_tool_parameters_schema(&mut schema);
+
+ assert_eq!(schema["properties"], json!({}));
+ }
+
#[test]
fn normalizes_nested_object_and_array_leaves() {
let mut schema = json!({
@@ -326,10 +337,13 @@ mod tests {
}
}
},
+ "filters": {
+ "type": "object"
+ },
"items": {
"type": "array",
"items": {
- "description": "Array item schema"
+ "type": "object"
}
}
}
@@ -338,7 +352,8 @@ mod tests {
proxy::normalize_openai_tool_parameters_schema(&mut schema);
assert_eq!(schema["properties"]["payload"]["properties"]["title"]["type"], json!("string"));
- assert_eq!(schema["properties"]["items"]["items"]["type"], json!("string"));
+ assert_eq!(schema["properties"]["filters"]["properties"], json!({}));
+ assert_eq!(schema["properties"]["items"]["items"]["properties"], json!({}));
}
#[test]
@@ -370,4 +385,84 @@ mod tests {
json!("string"),
);
}
+
+ #[test]
+ fn leaves_existing_valid_object_schema_unchanged() {
+ let mut schema = json!({
+ "type": "object",
+ "properties": {
+ "payload": {
+ "type": "object",
+ "properties": {
+ "name": {
+ "type": "string"
+ }
+ },
+ "required": ["name"]
+ }
+ }
+ });
+
+ let original = schema.clone();
+ proxy::normalize_openai_tool_parameters_schema(&mut schema);
+
+ assert_eq!(schema, original);
+ }
+
+ #[test]
+ fn normalizes_mixed_schema_without_altering_valid_fields() {
+ let mut schema = json!({
+ "type": "object",
+ "properties": {
+ "count": {
+ "type": "integer"
+ },
+ "title": {
+ "description": "A title"
+ },
+ "metadata": {
+ "type": "object",
+ "description": "Optional metadata"
+ }
+ }
+ });
+
+ proxy::normalize_openai_tool_parameters_schema(&mut schema);
+
+ assert_eq!(schema["properties"]["count"]["type"], json!("integer"));
+ assert_eq!(schema["properties"]["title"]["type"], json!("string"));
+ assert_eq!(schema["properties"]["metadata"]["description"], json!("Optional metadata"));
+ assert_eq!(schema["properties"]["metadata"]["properties"], json!({}));
+ }
+
+ #[test]
+ fn normalizes_combinator_members_recursively() {
+ let mut schema = json!({
+ "anyOf": [
+ {
+ "type": "object"
+ },
+ {
+ "description": "fallback string"
+ }
+ ],
+ "oneOf": [
+ {
+ "type": "object"
+ }
+ ],
+ "allOf": [
+ {
+ "description": "merged leaf"
+ }
+ ]
+ });
+
+ proxy::normalize_openai_tool_parameters_schema(&mut schema);
+
+ assert_eq!(schema["anyOf"][0]["properties"], json!({}));
+ assert_eq!(schema["anyOf"][1]["type"], json!("string"));
+ assert_eq!(schema["oneOf"][0]["properties"], json!({}));
+ assert_eq!(schema["allOf"][0]["type"], json!("string"));
+ }
}
diff --git a/web-app/src/lib/__tests__/custom-chat-transport.test.ts b/web-app/src/lib/__tests__/custom-chat-transport.test.ts
new file mode 100644
index 000000000..a2d7d37f7
--- /dev/null
+++ b/web-app/src/lib/__tests__/custom-chat-transport.test.ts
@@ -0,0 +1,170 @@
+import { describe, expect, it } from 'vitest'
+
+import { normalizeToolInputSchema } from '../custom-chat-transport'
+
+describe('normalizeToolInputSchema', () => {
+ it('adds empty properties for object schemas without properties', () => {
+ expect(normalizeToolInputSchema({ type: 'object' })).toEqual({
+ type: 'object',
+ properties: {},
+ })
+ })
+
+ it('adds string type for description-only leaves', () => {
+ expect(
+ normalizeToolInputSchema({
+ type: 'object',
+ properties: {
+ url: {
+ description: 'Target URL',
+ },
+ },
+ })
+ ).toEqual({
+ type: 'object',
+ properties: {
+ url: {
+ description: 'Target URL',
+ type: 'string',
+ },
+ },
+ })
+ })
+
+ it('normalizes nested object and array schemas recursively', () => {
+ expect(
+ normalizeToolInputSchema({
+ type: 'object',
+ properties: {
+ filters: {
+ type: 'object',
+ },
+ items: {
+ type: 'array',
+ items: {
+ type: 'object',
+ },
+ },
+ },
+ })
+ ).toEqual({
+ type: 'object',
+ properties: {
+ filters: {
+ type: 'object',
+ properties: {},
+ },
+ items: {
+ type: 'array',
+ items: {
+ type: 'object',
+ properties: {},
+ },
+ },
+ },
+ })
+ })
+
+ it('preserves already valid schemas', () => {
+ const schema = {
+ type: 'object',
+ properties: {
+ payload: {
+ type: 'object',
+ properties: {
+ id: {
+ type: 'string',
+ },
+ },
+ required: ['id'],
+ },
+ },
+ }
+
+ expect(normalizeToolInputSchema(schema)).toEqual(schema)
+ })
+
+ it('patches only underspecified nodes in mixed schemas', () => {
+ expect(
+ normalizeToolInputSchema({
+ type: 'object',
+ properties: {
+ count: {
+ type: 'integer',
+ },
+ title: {
+ description: 'A title',
+ },
+ metadata: {
+ type: 'object',
+ description: 'Optional metadata',
+ },
+ },
+ })
+ ).toEqual({
+ type: 'object',
+ properties: {
+ count: {
+ type: 'integer',
+ },
+ title: {
+ description: 'A title',
+ type: 'string',
+ },
+ metadata: {
+ type: 'object',
+ description: 'Optional metadata',
+ properties: {},
+ },
+ },
+ })
+ })
+
+ it('normalizes combinator members recursively', () => {
+ expect(
+ normalizeToolInputSchema({
+ anyOf: [
+ {
+ type: 'object',
+ },
+ {
+ description: 'fallback string',
+ },
+ ],
+ oneOf: [
+ {
+ type: 'object',
+ },
+ ],
+ allOf: [
+ {
+ description: 'merged leaf',
+ },
+ ],
+ })
+ ).toEqual({
+ anyOf: [
+ {
+ type: 'object',
+ properties: {},
+ },
+ {
+ description: 'fallback string',
+ type: 'string',
+ },
+ ],
+ oneOf: [
+ {
+ type: 'object',
+ properties: {},
+ },
+ ],
+ allOf: [
+ {
+ description: 'merged leaf',
+ type: 'string',
+ },
+ ],
+ })
+ })
+})
diff --git a/web-app/src/lib/custom-chat-transport.ts b/web-app/src/lib/custom-chat-transport.ts
index e59230557..e9aeab74f 100644
--- a/web-app/src/lib/custom-chat-transport.ts
+++ b/web-app/src/lib/custom-chat-transport.ts
@@ -65,6 +65,52 @@ export type ServiceHub = {
}
}
+function normalizeToolInputSchemaValue(value: unknown): unknown {
+ if (Array.isArray(value)) {
+ return value.map(normalizeToolInputSchemaValue)
+ }
+
+ if (!value || typeof value !== 'object') {
+ return value
+ }
+
+ const normalized = Object.fromEntries(
+ Object.entries(value as Record<string, unknown>).map(([key, childValue]) => [
+ key,
+ normalizeToolInputSchemaValue(childValue),
+ ])
+ )
+
+ const hasDescription = Object.prototype.hasOwnProperty.call(normalized, 'description')
+ const hasType = Object.prototype.hasOwnProperty.call(normalized, 'type')
+ const hasNestedSchemaKeywords =
+ Object.prototype.hasOwnProperty.call(normalized, 'properties') ||
+ Object.prototype.hasOwnProperty.call(normalized, 'items') ||
+ Object.prototype.hasOwnProperty.call(normalized, 'anyOf') ||
+ Object.prototype.hasOwnProperty.call(normalized, 'oneOf') ||
+ Object.prototype.hasOwnProperty.call(normalized, 'allOf') ||
+ Object.prototype.hasOwnProperty.call(normalized, '$ref')
+
+ if (normalized.type === 'object' && !Object.prototype.hasOwnProperty.call(normalized, 'properties')) {
+ normalized.properties = {}
+ }
+
+ if (hasDescription && !hasType && !hasNestedSchemaKeywords) {
+ normalized.type = 'string'
+ }
+
+ return normalized
+}
+
+type ToolInputSchema = Record<string, unknown>
+
+// Keep this behavior aligned with `normalize_openai_tool_parameters_schema` in Rust.
+export function normalizeToolInputSchema(
+ schema: ToolInputSchema
+): ToolInputSchema {
+ return normalizeToolInputSchemaValue(schema) as ToolInputSchema
+}
+
/** Text from the most recent user message (for MCP server routing). */
function extractLatestUserText(messages: UIMessage[]): string {
for (let i = messages.length - 1; i >= 0; i--) {
@@ -248,7 +294,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
toolsRecord[tool.name] = {
description: tool.description,
inputSchema: jsonSchema(
- tool.inputSchema as Record<string, unknown>
+ normalizeToolInputSchema(tool.inputSchema as Record<string, unknown>)
),
} as Tool
}
@@ -304,7 +350,7 @@ export class CustomChatTransport implements ChatTransport<UIMessage> {
toolsRecord[tool.name] = {
description: tool.description,
inputSchema: jsonSchema(
- tool.inputSchema as Record<string, unknown>
+ normalizeToolInputSchema(tool.inputSchema as Record<string, unknown>)
),
} as Tool
}