@agenite/tool
Version:
Tool interface for Agenite
140 lines (138 loc) • 3.8 kB
JavaScript
import { z } from 'zod';
import zodToJsonSchema from 'zod-to-json-schema';
import { jsonSchemaToZod } from '@n8n/json-schema-to-zod';
// src/tool.ts
var Tool = class {
name;
description;
version;
inputSchema;
executeImpl;
validateImpl;
zodSchema;
jsonSchema;
constructor(options) {
this.name = options.name;
this.description = options.description;
this.version = options.version;
this.executeImpl = options.execute;
this.validateImpl = options.validate;
if (options.inputSchema) {
if (options.inputSchema instanceof z.ZodType) {
this.zodSchema = options.inputSchema;
const { $schema: _, ...schema } = zodToJsonSchema(
options.inputSchema,
{}
);
this.jsonSchema = schema;
this.inputSchema = this.createToolSchema(schema);
} else {
this.jsonSchema = options.inputSchema;
this.inputSchema = this.createToolSchema(options.inputSchema);
}
}
}
createToolSchema(schema) {
return {
type: "object",
properties: schema.properties || {},
required: schema.required
};
}
async execute(params) {
try {
if (this.validateImpl || this.jsonSchema) {
const validationResult = await this.validate(params.input);
if (!validationResult.isValid) {
return {
isError: true,
data: `Validation failed: ${validationResult.errors?.map((e) => e.message).join(", ")}`,
error: {
code: "VALIDATION_ERROR",
message: "Input validation failed",
details: validationResult.errors
}
};
}
}
const startTime = Date.now();
const response = await this.executeImpl(params);
if (!response.duration) {
response.duration = Date.now() - startTime;
}
return response;
} catch (error) {
return {
isError: true,
data: `Tool execution failed: ${error instanceof Error ? error.message : String(error)}`,
error: {
code: "EXECUTION_ERROR",
message: error instanceof Error ? error.message : String(error),
details: error
}
};
}
}
async validate(input) {
try {
if (this.validateImpl) {
return await this.validateImpl(input);
}
if (this.zodSchema) {
try {
this.zodSchema.parse(input);
return { isValid: true };
} catch (error) {
if (error instanceof z.ZodError) {
return {
isValid: false,
errors: error.errors.map((err) => ({
field: err.path.join("."),
message: err.message
}))
};
}
}
}
if (this.jsonSchema) {
return this.validateJsonSchema(input);
}
return { isValid: true };
} catch (error) {
return {
isValid: false,
errors: [
{
field: "*",
message: `Validation error: ${error instanceof Error ? error.message : String(error)}`
}
]
};
}
}
async validateJsonSchema(input) {
try {
const zodSchema = jsonSchemaToZod(this.jsonSchema);
zodSchema.parse(input);
return { isValid: true };
} catch (error) {
if (error instanceof z.ZodError) {
return {
isValid: false,
errors: error.errors.map((err) => ({
field: err.path.join("."),
message: err.message
}))
};
} else {
return {
isValid: false,
errors: [{ field: "*", message: "Validation failed" }]
};
}
}
}
};
export { Tool };
//# sourceMappingURL=index.js.map
//# sourceMappingURL=index.js.map