Add JSON validation to tool execution

Prevents execution of tools with invalid JSON parameters by validating JSON
syntax before tool execution and showing error UI for invalid input.

- Add validateJson method to DynamicJsonForm via forwardRef
- Add validation check in ToolsTab before tool execution
- Reuse existing JsonEditor error display for consistent UX
This commit is contained in:
Nandha Reddy 2025-06-19 02:32:40 +10:00
commit d65ed01922

View file

@ -1,4 +1,4 @@
import { useState, useEffect, useCallback, useRef } from "react";
import { useState, useEffect, useCallback, useRef, forwardRef, useImperativeHandle } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import JsonEditor from "./JsonEditor";
@ -13,6 +13,10 @@ interface DynamicJsonFormProps {
maxDepth?: number;
}
export interface DynamicJsonFormRef {
validateJson: () => { isValid: boolean; error: string | null };
}
const isSimpleObject = (schema: JsonSchemaType): boolean => {
const supportedTypes = ["string", "number", "integer", "boolean", "null"];
if (supportedTypes.includes(schema.type)) return true;
@ -22,12 +26,12 @@ const isSimpleObject = (schema: JsonSchemaType): boolean => {
);
};
const DynamicJsonForm = ({
const DynamicJsonForm = forwardRef<DynamicJsonFormRef, DynamicJsonFormProps>(({
schema,
value,
onChange,
maxDepth = 3,
}: DynamicJsonFormProps) => {
}, ref) => {
const isOnlyJSON = !isSimpleObject(schema);
const [isJsonMode, setIsJsonMode] = useState(isOnlyJSON);
const [jsonError, setJsonError] = useState<string>();
@ -108,6 +112,25 @@ const DynamicJsonForm = ({
}
};
const validateJson = () => {
if (!isJsonMode) return { isValid: true, error: null };
try {
const jsonStr = rawJsonValue.trim();
if (!jsonStr) return { isValid: true, error: null };
JSON.parse(jsonStr);
setJsonError(undefined);
return { isValid: true, error: null };
} catch (err) {
const errorMessage = err instanceof Error ? err.message : "Invalid JSON";
setJsonError(errorMessage);
return { isValid: false, error: errorMessage };
}
};
useImperativeHandle(ref, () => ({
validateJson,
}));
const renderFormFields = (
propSchema: JsonSchemaType,
currentValue: JsonValue,
@ -303,6 +326,6 @@ const DynamicJsonForm = ({
)}
</div>
);
};
});
export default DynamicJsonForm;