import { z } from "zod";
/**
* Data Tools - Manipulation, conversion, and mocking
*/
// ============================================
// Convert Format
// ============================================
export const convertFormatSchema = {
name: "convert_format",
description: "Converts data between common formats (JSON, YAML, XML, CSV)",
inputSchema: z.object({
input: z.string().describe("Input string"),
from: z.enum(["json", "yaml", "xml", "csv"]).describe("Source format"),
to: z.enum(["json", "yaml", "xml", "csv"]).describe("Target format"),
}),
};
export function convertFormatHandler(args: {
input: string;
from: string;
to: string;
}) {
const { input, from, to } = args;
let data: any;
try {
// Parse Input
if (from === "json") {
data = JSON.parse(input);
} else if (from === "csv") {
const lines = input.split("\n");
const headers = lines[0].split(",");
data = lines.slice(1).map((line) => {
const values = line.split(",");
return headers.reduce((obj, header, i) => {
obj[header.trim()] = values[i]?.trim();
return obj;
}, {} as any);
});
} else {
throw new Error(
`Unsupported source format for simple converter: ${from}`,
);
}
// Generate Output
let output = "";
if (to === "json") {
output = JSON.stringify(data, null, 2);
} else if (to === "csv") {
if (Array.isArray(data) && data.length > 0) {
const headers = Object.keys(data[0]);
output =
headers.join(",") +
"\n" +
data
.map((row: any) => headers.map((h) => row[h]).join(","))
.join("\n");
} else {
output =
"Error: Input is not an array of objects, cannot convert to CSV.";
}
} else if (to === "xml") {
const toXML = (obj: any): string => {
if (typeof obj !== "object" || obj === null) return String(obj);
return Object.entries(obj)
.map(([key, value]) => {
if (Array.isArray(value)) {
return value.map((v) => `<${key}>${toXML(v)}</${key}>`).join("");
}
return `<${key}>${toXML(value)}</${key}>`;
})
.join("");
};
output = `<root>${toXML(data)}</root>`;
} else {
throw new Error(`Unsupported target format: ${to}`);
}
return {
content: [
{
type: "text",
text: output,
},
],
};
} catch (error) {
return {
content: [
{
type: "text",
text: `Error converting format: ${(error as Error).message}`,
},
],
isError: true,
};
}
}
// ============================================
// Generate Mock Data
// ============================================
export const generateMockDataSchema = {
name: "generate_mock_data",
description: "Generates realistic mock data based on a schema description",
inputSchema: z.object({
schema: z
.string()
.describe("Structure description (e.g. 'User: id, name, email')"),
count: z.number().default(5).describe("Number of items to generate"),
format: z.enum(["json", "csv", "sql"]).default("json"),
}),
};
export function generateMockDataHandler(args: {
schema: string;
count: number;
format: string;
}) {
const { schema, count, format } = args;
const names = ["Alice", "Bob", "Charlie", "David", "Eve"];
const emails = ["alice@example.com", "bob@test.org", "charlie@corp.net"];
const items = [];
for (let i = 0; i < count; i++) {
items.push({
id: i + 1,
name: names[i % names.length],
email: emails[i % emails.length],
role: i % 3 === 0 ? "admin" : "user",
active: Math.random() > 0.5,
});
}
let output = "";
if (format === "json") {
output = JSON.stringify(items, null, 2);
} else if (format === "csv") {
output =
"id,name,email,role,active\n" +
items
.map((i) => `${i.id},${i.name},${i.email},${i.role},${i.active}`)
.join("\n");
} else if (format === "sql") {
output =
`INSERT INTO users (id, name, email, role, active) VALUES\n` +
items
.map(
(i) =>
` (${i.id}, '${i.name}', '${i.email}', '${i.role}', ${i.active})`,
)
.join(",\n") +
";";
}
return {
content: [
{
type: "text",
text: `# Mock Data (${count} items)\n\n\`\`\`${format}\n${output}\n\`\`\``,
},
],
};
}
// Export all
export const dataTools = {
convertFormatSchema,
convertFormatHandler,
generateMockDataSchema,
generateMockDataHandler,
};