fix: fix CJS by dynamically importing json-schema-to-zod (#37)

fixes #36
This commit is contained in:
Ben Burns
2025-03-24 15:42:25 +13:00
committed by GitHub
parent 2fc9bfa79e
commit 18daa5b83f
2 changed files with 46 additions and 34 deletions
Binary file not shown.
+46 -34
View File
@@ -18,10 +18,19 @@ import {
MessageContentImageUrl,
MessageContentText,
} from "@langchain/core/messages";
import { JSONSchema, JSONSchemaToZod } from "@dmitryrechkin/json-schema-to-zod";
import type { JSONSchema } from "@dmitryrechkin/json-schema-to-zod";
import type { ZodSchema } from "zod";
import debug from "debug";
let JSONSchemaToZod: { convert: (schema: JSONSchema) => ZodSchema } | undefined;
async function convertSchema(schema: JSONSchema): Promise<ZodSchema> {
if (!JSONSchemaToZod) {
({ JSONSchemaToZod } = await import("@dmitryrechkin/json-schema-to-zod"));
}
return JSONSchemaToZod.convert(schema);
}
// Replace direct initialization with lazy initialization
let debugLog: debug.Debugger;
function getDebugLog() {
@@ -208,36 +217,39 @@ export async function loadMcpTools(
getDebugLog()(`INFO: Found ${toolsResponse.tools?.length || 0} MCP tools`);
// Filter out tools without names and convert in a single map operation
return (toolsResponse.tools || [])
.filter((tool: MCPTool) => !!tool.name)
.map((tool: MCPTool) => {
try {
const dst = new DynamicStructuredTool({
name: tool.name,
description: tool.description || "",
schema: JSONSchemaToZod.convert(
(tool.inputSchema ?? {
type: "object",
properties: {},
}) as JSONSchema
),
responseFormat: "content_and_artifact",
func: _callTool.bind(
null,
serverName,
tool.name,
client
) as DynamicStructuredToolInput["func"],
});
getDebugLog()(`INFO: Successfully loaded tool: ${dst.name}`);
return dst;
} catch (error) {
getDebugLog()(`ERROR: Failed to load tool "${tool.name}":`, error);
if (throwOnLoadError) {
throw error;
}
return null;
}
})
.filter(Boolean) as StructuredToolInterface[];
return (
await Promise.all(
(toolsResponse.tools || [])
.filter((tool: MCPTool) => !!tool.name)
.map(async (tool: MCPTool) => {
try {
const dst = new DynamicStructuredTool({
name: tool.name,
description: tool.description || "",
schema: await convertSchema(
(tool.inputSchema ?? {
type: "object",
properties: {},
}) as JSONSchema
),
responseFormat: "content_and_artifact",
func: _callTool.bind(
null,
serverName,
tool.name,
client
) as DynamicStructuredToolInput["func"],
});
getDebugLog()(`INFO: Successfully loaded tool: ${dst.name}`);
return dst;
} catch (error) {
getDebugLog()(`ERROR: Failed to load tool "${tool.name}":`, error);
if (throwOnLoadError) {
throw error;
}
return null;
}
})
)
).filter(Boolean) as StructuredToolInterface[];
}