fix: resolve $ref references in tool input schema properties

This commit is contained in:
yanOO1497 2025-10-25 17:02:25 +08:00
commit fb7fae1436
2 changed files with 65 additions and 7 deletions

View file

@ -48,6 +48,7 @@ export type JsonSchemaType = {
const?: JsonValue;
oneOf?: (JsonSchemaType | JsonSchemaConst)[];
anyOf?: (JsonSchemaType | JsonSchemaConst)[];
$ref?: string;
};
export type JsonObject = { [key: string]: JsonValue };

View file

@ -145,6 +145,50 @@ export function isPropertyRequired(
return schema.required?.includes(propertyName) ?? false;
}
/**
* Resolves $ref references in JSON schema
* @param schema The schema that may contain $ref
* @param rootSchema The root schema to resolve references against
* @returns The resolved schema without $ref
*/
export function resolveRef(
schema: JsonSchemaType,
rootSchema: JsonSchemaType,
): JsonSchemaType {
if (!("$ref" in schema) || !schema.$ref) {
return schema;
}
const ref = schema.$ref;
// Handle simple #/properties/name references
if (ref.startsWith("#/")) {
const path = ref.substring(2).split("/");
let current: unknown = rootSchema;
for (const segment of path) {
if (
current &&
typeof current === "object" &&
current !== null &&
segment in current
) {
current = (current as Record<string, unknown>)[segment];
} else {
// If reference cannot be resolved, return the original schema
console.warn(`Could not resolve $ref: ${ref}`);
return schema;
}
}
return current as JsonSchemaType;
}
// For other types of references, return the original schema
console.warn(`Unsupported $ref format: ${ref}`);
return schema;
}
/**
* Normalizes union types (like string|null from FastMCP) to simple types for form rendering
* @param schema The JSON schema to normalize