54 lines
1.7 KiB
TypeScript
54 lines
1.7 KiB
TypeScript
import * as plugins from './plugins.js';
|
|
|
|
export function jsonTool(): plugins.ToolSet {
|
|
return {
|
|
json_validate: plugins.tool({
|
|
description:
|
|
'Validate a JSON string and optionally check for required fields.',
|
|
inputSchema: plugins.z.object({
|
|
jsonString: plugins.z.string().describe('JSON string to validate'),
|
|
requiredFields: plugins.z
|
|
.array(plugins.z.string())
|
|
.optional()
|
|
.describe('Fields that must exist at the top level'),
|
|
}),
|
|
execute: async ({
|
|
jsonString,
|
|
requiredFields,
|
|
}: {
|
|
jsonString: string;
|
|
requiredFields?: string[];
|
|
}) => {
|
|
try {
|
|
const parsed = JSON.parse(jsonString);
|
|
if (requiredFields?.length) {
|
|
const missing = requiredFields.filter((f) => !(f in parsed));
|
|
if (missing.length) {
|
|
return `Invalid: missing required fields: ${missing.join(', ')}`;
|
|
}
|
|
}
|
|
const type = Array.isArray(parsed) ? 'array' : typeof parsed;
|
|
return `Valid JSON (${type})`;
|
|
} catch (e) {
|
|
return `Invalid JSON: ${(e as Error).message}`;
|
|
}
|
|
},
|
|
}),
|
|
|
|
json_transform: plugins.tool({
|
|
description: 'Parse a JSON string and return it pretty-printed.',
|
|
inputSchema: plugins.z.object({
|
|
jsonString: plugins.z.string().describe('JSON string to format'),
|
|
}),
|
|
execute: async ({ jsonString }: { jsonString: string }) => {
|
|
try {
|
|
const parsed = JSON.parse(jsonString);
|
|
return JSON.stringify(parsed, null, 2);
|
|
} catch (e) {
|
|
return `Error parsing JSON: ${(e as Error).message}`;
|
|
}
|
|
},
|
|
}),
|
|
};
|
|
}
|