The fastest, litest AI Gateway. Rust core with Python SDK. Call 100+ LLM APIs in OpenAI (or native) format with cost tracking, guardrails, load balancing, and logging [Bedrock, Azure, OpenAI, Anthropic, OpenAI, VertexAI, vLLM, Nvidia NIM]
Python ai-gatewayanthropicazure-openaibedrockgatewaylangchainlitellmllmllm-gatewayllmopsmcp-gatewayopenaiopenai-proxyrustrust-aivertex-ai
fix(ui): render optional array and object MCP tool parameters as JSON inputs (#37548)
yuneng-jiang0edd24554551
diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/ToolArgumentsForm.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/ToolArgumentsForm.tsxindex 9238d604246..14d69c358ba 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/ToolArgumentsForm.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/ToolArgumentsForm.tsx@@ -10,11 +10,13 @@ import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from "@/compimport { FieldGroup } from "@/components/shared/form/field";import { FormField, type FormFieldControlProps } from "@/components/shared/form/FormField";import { UiLoadingSpinner } from "@/components/ui/ui-loading-spinner";+import type { InputSchemaProperty } from "@/components/mcp_tools/types";import {ToolArgumentField,ToolArgumentsFormValues,buildToolCallArguments,initialArgumentValues,+ resolveSchemaProperty,toolArgumentsResolver,} from "./toolCallArguments";@@ -44,9 +46,10 @@ const booleanTitle = (value: unknown): string | undefined => {const JsonArgumentControl: React.FC<{field: ToolArgumentField;+ prop: InputSchemaProperty;control: FormFieldControlProps<ToolArgumentsFormValues, `args.${number}`>;-}> = ({ field, control }) => {- const isObject = field.prop.type === "object";+}> = ({ field, prop, control }) => {+ const isObject = prop.type === "object";const fallbackPlaceholder = isObject ? `Enter JSON object for ${field.key}` : `Enter JSON array for ${field.key}`;return (<div className="space-y-2">@@ -54,7 +57,7 @@ const JsonArgumentControl: React.FC<{{...control}rows={isObject ? 6 : 4}value={(control.value as string) ?? ""}- placeholder={field.prop.description || fallbackPlaceholder}+ placeholder={prop.description || fallbackPlaceholder}spellCheck={false}data-testid={`textarea-${field.key}`}className="rounded-lg font-mono"@@ -70,7 +73,9 @@ const ToolArgumentControl: React.FC<{field: ToolArgumentField;control: FormFieldControlProps<ToolArgumentsFormValues, `args.${number}`>;}> = ({ field, control }) => {- if (field.prop.type === "string" && field.prop.enum) {+ const prop = resolveSchemaProperty(field.prop);++ if (prop.type === "string" && prop.enum) {return (<select{...control}@@ -78,7 +83,7 @@ const ToolArgumentControl: React.FC<{className="w-full rounded-lg border border-input bg-transparent px-3 py-2 text-sm shadow-xs transition-colors focus:border-ring focus:ring-3 focus:ring-ring/50 focus:outline-hidden">{!field.required && <option value="">Select {field.key}</option>}- {field.prop.enum.map((option) => (+ {prop.enum.map((option) => (<option key={option} value={option}>{option}</option>@@ -87,20 +92,20 @@ const ToolArgumentControl: React.FC<{);}- if (field.prop.type === "number" || field.prop.type === "integer") {+ if (prop.type === "number" || prop.type === "integer") {return (<Input{...control}type="number"- step={field.prop.type === "integer" ? 1 : "any"}+ step={prop.type === "integer" ? 1 : "any"}value={(control.value as number | string) ?? ""}- placeholder={field.prop.description || `Enter ${field.key}`}+ placeholder={prop.description || `Enter ${field.key}`}className="rounded-lg"/>);}- if (field.prop.type === "boolean") {+ if (prop.type === "boolean") {return (<Selectitems={field.required ? BOOLEAN_ITEMS : [{ value: "", label: `Select ${field.key}` }, ...BOOLEAN_ITEMS]}@@ -124,15 +129,15 @@ const ToolArgumentControl: React.FC<{);}- if (field.prop.type === "object" || field.prop.type === "array") {- return <JsonArgumentControl field={field} control={control} />;+ if (prop.type === "object" || prop.type === "array") {+ return <JsonArgumentControl field={field} prop={prop} control={control} />;}return (<Input{...control}value={(control.value as string) ?? ""}- placeholder={field.prop.description || `Enter ${field.key}`}+ placeholder={prop.description || `Enter ${field.key}`}className="rounded-lg"/>);diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/ToolTestPanel.test.tsx b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/ToolTestPanel.test.tsxindex 3fb5d602402..26e66c8338c 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/ToolTestPanel.test.tsx+++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/ToolTestPanel.test.tsx@@ -1,5 +1,5 @@import React from "react";-import { render, screen } from "@testing-library/react";+import { fireEvent, render, screen } from "@testing-library/react";import userEvent from "@testing-library/user-event";import type { UserEvent } from "@testing-library/user-event";import { describe, expect, it, vi } from "vitest";@@ -389,3 +389,85 @@ describe("ToolTestPanel schema changes under a stable tool name", () => {expect(screen.getByLabelText("message")).toHaveValue("typed by hand");});});++describe("ToolTestPanel optional union-typed parameters", () => {+ const qaEchoSchema: InputSchema = {+ type: "object",+ properties: {+ message: { type: "string" },+ repeat: { type: "integer", default: 1 },+ loud: { type: "boolean", default: false },+ tags: { anyOf: [{ type: "array", items: { type: "string" } }, { type: "null" }], default: null },+ },+ required: ["message"],+ };++ const runPanel = async (drive: () => void) => {+ const onSubmit = vi.fn();+ render(+ <ToolTestPanel+ tool={buildTool(qaEchoSchema)}+ onSubmit={onSubmit}+ isLoading={false}+ result={null}+ error={null}+ onClose={vi.fn()}+ />,+ );+ drive();+ await userEvent.setup().click(screen.getByRole("button", { name: "Call Tool" }));+ return onSubmit;+ };++ it("renders the JSON textarea for an optional array parameter, not a plain text input", () => {+ renderPanel(qaEchoSchema);++ const tags = screen.getByTestId("textarea-tags");+ expect(tags.tagName).toBe("TEXTAREA");+ expect(tags).toHaveValue("");+ expect(screen.getByPlaceholderText("Enter JSON array for tags")).toBe(tags);+ expect(screen.queryByPlaceholderText("Enter tags")).not.toBeInTheDocument();+ });++ it("renders the JSON textarea for an optional object parameter, not a plain text input", () => {+ renderPanel({+ type: "object",+ properties: {+ payload: { anyOf: [{ type: "object", properties: { id: { type: "string" } } }, { type: "null" }] },+ },+ });++ const payload = screen.getByTestId("textarea-payload");+ expect(payload).toHaveValue(JSON.stringify({ id: "" }, null, 2));+ expect(screen.getByPlaceholderText("Enter JSON object for payload")).toBe(payload);+ expect(screen.queryByPlaceholderText("Enter payload")).not.toBeInTheDocument();+ });++ it("sends an optional array parameter as a real array", async () => {+ const onSubmit = await runPanel(() => {+ fireEvent.change(screen.getByPlaceholderText("Enter message"), { target: { value: "hi" } });+ fireEvent.change(screen.getByTestId("textarea-tags"), { target: { value: '["a","b"]' } });+ });++ const expected = { message: "hi", repeat: 1, loud: false, tags: ["a", "b"] };+ expect(onSubmit).toHaveBeenCalledWith(expected);+ });++ it("omits an optional array parameter the user never filled in", async () => {+ const onSubmit = await runPanel(() => {+ fireEvent.change(screen.getByPlaceholderText("Enter message"), { target: { value: "hi" } });+ });++ expect(onSubmit).toHaveBeenCalledWith({ message: "hi", repeat: 1, loud: false });+ });++ it("blocks the call instead of sending comma-separated text as a raw string", async () => {+ const onSubmit = await runPanel(() => {+ fireEvent.change(screen.getByPlaceholderText("Enter message"), { target: { value: "hi" } });+ fireEvent.change(screen.getByTestId("textarea-tags"), { target: { value: "a,b" } });+ });++ expect(await screen.findByText("Invalid JSON")).toBeInTheDocument();+ expect(onSubmit).not.toHaveBeenCalled();+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/toolCallArguments.test.ts b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/toolCallArguments.test.tsindex 80157a5bc99..5c717402f19 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/toolCallArguments.test.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/toolCallArguments.test.ts@@ -1,12 +1,13 @@import { describe, expect, it } from "vitest";-import { InputSchema } from "@/components/mcp_tools/types";+import { InputSchema, InputSchemaProperty } from "@/components/mcp_tools/types";import {ToolArgumentField,argumentsFormKey,buildToolCallArguments,hasNestedParamsSchema,initialArgumentValues,+ resolveSchemaProperty,toolArgumentFields,toolArgumentsResolver,validateToolArgument,@@ -332,3 +333,119 @@ describe("argumentsFormKey", () => {expect(argumentsFormKey(one)).toBe(argumentsFormKey(two));});});++describe("union-typed properties", () => {+ const optionalArray: InputSchemaProperty = {+ anyOf: [{ type: "array", items: { type: "string" } }, { type: "null" }],+ default: null,+ };+ const optionalObject: InputSchemaProperty = {+ anyOf: [{ type: "object", properties: { id: { type: "string" } } }, { type: "null" }],+ default: null,+ };+ const unionField = (key: string, prop: InputSchemaProperty, required = false): ToolArgumentField => ({+ key,+ prop,+ required,+ });++ describe("resolveSchemaProperty", () => {+ it("collapses an optional array to the array member", () => {+ expect(resolveSchemaProperty(optionalArray)).toMatchObject({ type: "array", items: { type: "string" } });+ });++ it("carries the outer description and default onto the resolved member", () => {+ const resolved = resolveSchemaProperty({+ anyOf: [{ type: "array", items: { type: "string" } }, { type: "null" }],+ description: "outer text",+ default: ["a"],+ });++ expect(resolved).toMatchObject({ type: "array", description: "outer text", default: ["a"] });+ });++ it("keeps the enum of a resolved string member so the select still renders", () => {+ expect(resolveSchemaProperty({ anyOf: [{ type: "string", enum: ["a", "b"] }, { type: "null" }] })).toMatchObject({+ type: "string",+ enum: ["a", "b"],+ });+ });++ it("resolves oneOf the same way as anyOf", () => {+ expect(resolveSchemaProperty({ oneOf: [{ type: "object" }, { type: "null" }] })).toMatchObject({+ type: "object",+ });+ });++ it("leaves a property that already declares a type untouched", () => {+ const plain: InputSchemaProperty = { type: "string", anyOf: [{ type: "array" }, { type: "null" }] };++ expect(resolveSchemaProperty(plain)).toBe(plain);+ });++ it("leaves a genuine multi-type union unresolved", () => {+ const multi: InputSchemaProperty = { anyOf: [{ type: "string" }, { type: "integer" }, { type: "null" }] };++ expect(resolveSchemaProperty(multi)).toBe(multi);+ });+ });++ describe("validateToolArgument", () => {+ it("reports an object supplied to an optional array parameter", () => {+ expect(validateToolArgument(unionField("tags", optionalArray), '{"k":1}')).toBe("Please enter a JSON array");+ });++ it("reports an array supplied to an optional object parameter", () => {+ expect(validateToolArgument(unionField("payload", optionalObject), "[1,2]")).toBe("Please enter a JSON object");+ });++ it("reports the comma-separated text a plain input would have produced as invalid JSON", () => {+ expect(validateToolArgument(unionField("tags", optionalArray), "a,b")).toBe("Invalid JSON");+ });++ it("accepts a well-formed value and an empty optional value", () => {+ expect(validateToolArgument(unionField("tags", optionalArray), '["a","b"]')).toBeUndefined();+ expect(validateToolArgument(unionField("tags", optionalArray), "")).toBeUndefined();+ });+ });++ describe("buildToolCallArguments", () => {+ it("sends a real array for an optional array parameter", () => {+ expect(buildToolCallArguments([unionField("tags", optionalArray)], ['["a","b"]'])).toEqual({+ tags: ["a", "b"],+ });+ });++ it("sends a real object for an optional object parameter", () => {+ expect(buildToolCallArguments([unionField("payload", optionalObject)], ['{"id":"x"}'])).toEqual({+ payload: { id: "x" },+ });+ });+ });++ describe("initialArgumentValues", () => {+ it("leaves a null-defaulted optional parameter blank so it is not submitted at all", () => {+ const fields = [unionField("tags", optionalArray), unionField("payload", optionalObject)];++ expect(initialArgumentValues(fields)).toEqual(["", ""]);+ expect(buildToolCallArguments(fields, initialArgumentValues(fields))).toEqual({});+ });++ it("builds a sample item from the resolved item schema when the union declares no default", () => {+ const prop: InputSchemaProperty = { anyOf: [{ type: "array", items: { type: "string" } }, { type: "null" }] };++ expect(initialArgumentValues([unionField("tags", prop)])).toEqual([JSON.stringify([""], null, 2)]);+ });++ it("seeds a nested optional array inside an object from the resolved member", () => {+ const [payload] = initialArgumentValues([+ unionField("payload", {+ type: "object",+ properties: { tags: { anyOf: [{ type: "array", items: { type: "string" } }, { type: "null" }] } },+ }),+ ]);++ expect(payload).toBe(JSON.stringify({ tags: [""] }, null, 2));+ });+ });+});diff --git a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/toolCallArguments.ts b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/toolCallArguments.tsindex 5fdeccd41bc..bdf0a52d02d 100644--- a/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/toolCallArguments.ts+++ b/ui/litellm-dashboard/src/app/(dashboard)/mcp-servers/_components/toolCallArguments.ts@@ -15,6 +15,17 @@ export interface ToolArgumentsFormValues {const isPlainObject = (value: unknown): value is Record<string, unknown> =>typeof value === "object" && value !== null && !Array.isArray(value);+export const resolveSchemaProperty = (prop: InputSchemaProperty): InputSchemaProperty => {+ if (prop.type !== undefined) return prop;+ const members = (prop.anyOf ?? prop.oneOf ?? []).filter((member) => member.type !== "null");+ if (members.length !== 1 || members[0].type === undefined) return prop;+ return {+ ...members[0],+ description: prop.description ?? members[0].description,+ default: prop.default !== undefined ? prop.default : members[0].default,+ };+};+const isJsonField = (prop: InputSchemaProperty): boolean => prop.type === "object" || prop.type === "array";export const toolArgumentFields = (schema: InputSchema): readonly ToolArgumentField[] =>@@ -38,27 +49,29 @@ const parseJson = (raw: unknown): ParsedJson => {const isBlank = (value: unknown): boolean => value === undefined || value === null || value === "";export const validateToolArgument = (field: ToolArgumentField, value: unknown): string | undefined => {+ const prop = resolveSchemaProperty(field.prop);const normalized = typeof value === "string" ? value.trim() : value;if (field.required && isBlank(normalized)) {return `Please enter ${field.key}`;}- if (!isJsonField(field.prop) || (isBlank(value) && !field.required)) {+ if (!isJsonField(prop) || (isBlank(value) && !field.required)) {return undefined;}const parsed = parseJson(value);if (parsed.kind === "invalid") {return "Invalid JSON";}- if (field.prop.type === "object" && !isPlainObject(parsed.value)) {+ if (prop.type === "object" && !isPlainObject(parsed.value)) {return "Please enter a JSON object";}- if (field.prop.type === "array" && !Array.isArray(parsed.value)) {+ if (prop.type === "array" && !Array.isArray(parsed.value)) {return "Please enter a JSON array";}return undefined;};-const coerceArgument = (prop: InputSchemaProperty, value: unknown): unknown => {+const coerceArgument = (declared: InputSchemaProperty, value: unknown): unknown => {+ const prop = resolveSchemaProperty(declared);const normalized = typeof value === "string" ? value.trim() : value;switch (prop.type) {case "boolean":@@ -162,9 +175,11 @@ function buildArrayDefault(prop: InputSchemaProperty, effectiveDefault: unknown)return buildArrayItems(prop.items);}-function buildDefaultValue(prop: InputSchemaProperty | undefined, overrideDefault?: unknown): unknown {- if (!prop) return undefined;+function buildDefaultValue(declared: InputSchemaProperty | undefined, overrideDefault?: unknown): unknown {+ if (!declared) return undefined;+ const prop = resolveSchemaProperty(declared);const effectiveDefault: unknown = overrideDefault !== undefined ? overrideDefault : prop.default;+ if (effectiveDefault === null) return null;if (prop.type === "object") return buildObjectDefault(prop, effectiveDefault);if (prop.type === "array") return buildArrayDefault(prop, effectiveDefault);@@ -183,9 +198,10 @@ function buildDefaultValue(prop: InputSchemaProperty | undefined, overrideDefaulexport const initialArgumentValues = (fields: readonly ToolArgumentField[]): unknown[] =>fields.map(({ prop }) => {- const defaultValue = buildDefaultValue(prop);- if (isJsonField(prop)) {- return JSON.stringify(defaultValue ?? (prop.type === "array" ? [] : {}), null, 2);+ const resolved = resolveSchemaProperty(prop);+ const defaultValue = buildDefaultValue(resolved);+ if (isJsonField(resolved)) {+ return isBlank(defaultValue) ? "" : JSON.stringify(defaultValue, null, 2);}return defaultValue;});diff --git a/ui/litellm-dashboard/src/components/mcp_tools/types.tsx b/ui/litellm-dashboard/src/components/mcp_tools/types.tsxindex 734c158ea42..67e51ab23aa 100644--- a/ui/litellm-dashboard/src/components/mcp_tools/types.tsx+++ b/ui/litellm-dashboard/src/components/mcp_tools/types.tsx@@ -294,13 +294,15 @@ export const handleAuth = (authType?: string | null): string => {// Define the structure for tool input schema propertiesexport interface InputSchemaProperty {- type: string;+ type?: string;description?: string;properties?: Record<string, InputSchemaProperty>; // For nested object propertiesrequired?: string[]; // For required fields in nested objectsenum?: string[]; // For enum valuesdefault?: any; // For default valuesitems?: InputSchemaProperty | InputSchemaProperty[]; // For array item schemas+ anyOf?: InputSchemaProperty[];+ oneOf?: InputSchemaProperty[];}// Define the structure for the input schema of a tool