Skip to main content
Glama

generate_from_template

Generate test data with pre-built schema templates for common use cases like ecommerce or blog. Customize scale, locale, and format to match your needs.

Instructions

Generate test data using a pre-built schema template.

Pick a template (ecommerce, blog, saas, social) and optionally adjust the scale, locale, format, and seed. The template handles all the table definitions, field types, and foreign key relationships for you.

Scale multiplier: 1.0 = default counts, 2.0 = double, 0.5 = half. Example: ecommerce template at scale 2.0 generates 100 users, 200 products, etc.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
templateYesTemplate name
scaleNoScale multiplier for record counts (default 1.0)
localeNoDefault locale (en, de, fr, es, etc.)
formatNoOutput formatjson
sql_dialectNoSQL dialect (only when format=sql)
seedNoSeed for reproducible output

Implementation Reference

  • The MCP tool handler for 'generate_from_template'. It extracts args (template, locale, scale, format, seed), calls generateFromTemplate() to build a GenerateRequest, invokes generate() to produce data, and optionally formats the output (CSV/SQL).
    async function handleGenerateFromTemplate(
      args: Record<string, unknown>
    ): Promise<ToolResult> {
      const { template, locale, scale, format, seed } = args as {
        template: string;
        locale?: string;
        scale?: number;
        format?: string;
        seed?: number;
      };
    
      if (!template) {
        return err("'template' is required. Available templates: ecommerce, blog, saas, social");
      }
    
      let request: GenerateRequest;
      try {
        request = generateFromTemplate({
          template,
          locale: locale as GenerateRequest["locale"],
          scale,
          format: format as GenerateRequest["format"],
          seed,
        });
      } catch (e) {
        return err(`Template error: ${e instanceof Error ? e.message : String(e)}`);
      }
    
      const result = await generate(request);
      if (!result.success) {
        if ("errors" in result) {
          return err(
            `Generation failed:\n${result.errors
              .map((e) => `  - ${e.field}: ${e.message}`)
              .join("\n")}`
          );
        }
        return err(`Generation failed: circular dependency between tables: ${result.cycle.join(" -> ")}`);
      }
    
      // Optionally format output
      if (format && format !== "json") {
        const sqlDialect = args.sql_dialect as string | undefined;
        const formatted = formatOutput(
          result.result,
          request.tables,
          format as "csv" | "sql",
          sqlDialect as "postgres" | "mysql" | "sqlite" | undefined
        );
        return ok(formatted.body);
      }
    
      return ok({ data: result.result.data, meta: result.result.meta });
    }
  • The core generateFromTemplate() helper function. It looks up the template in TEMPLATE_REGISTRY, applies the scale multiplier to each table's count (clamped 0.01-100), and builds a GenerateRequest with optional overrides for locale, format, sql_dialect, and seed.
    export function generateFromTemplate(options: TemplateGenerateOptions): GenerateRequest {
      const template = TEMPLATE_REGISTRY[options.template];
      if (!template) {
        throw new Error(`Unknown template: "${options.template}"`);
      }
    
      const rawScale = options.scale ?? 1;
      if (rawScale < 0) {
        throw new Error(`Invalid scale: ${rawScale}. Scale must be a positive number (e.g. 0.5 for half, 2 for double).`);
      }
      const scale = Math.min(Math.max(rawScale, 0.01), 100);
    
      const tables = template.schema.tables.map((table) => ({
        ...table,
        count: Math.max(1, Math.round(table.count * scale)),
      }));
    
      const request: GenerateRequest = {
        ...template.schema,
        tables,
      };
    
      if (options.locale !== undefined) {
        request.locale = options.locale;
      }
      if (options.format !== undefined) {
        request.format = options.format;
      }
      if (options.sql_dialect !== undefined) {
        request.sql_dialect = options.sql_dialect;
      }
      if (options.seed !== undefined) {
        request.seed = options.seed;
      }
    
      return request;
    }
  • Type definitions for TemplateGenerateOptions (what generateFromTemplate accepts) and TemplateDefinition/TemplateSummary (template registry structure).
    import type { GenerateRequest, Locale, OutputFormat, SqlDialect } from "../types";
    
    export interface TemplateDefinition {
      id: string;
      name: string;
      description: string;
      tables: string[]; // table names
      default_counts: Record<string, number>;
      schema: GenerateRequest;
    }
    
    export interface TemplateSummary {
      id: string;
      name: string;
      description: string;
      tables: string[];
      default_counts: Record<string, number>;
    }
    
    export interface TemplateGenerateOptions {
      template: string;
      locale?: Locale;
      scale?: number; // multiplier for all table counts
      format?: OutputFormat;
      sql_dialect?: SqlDialect;
      seed?: number;
    }
  • MCP tool inputSchema definition for generate_from_template, defining the JSON schema for template, locale, scale, format, and seed parameters.
    {
      name: "generate_from_template",
      description:
        "Generate test data using a pre-built template. Available templates: ecommerce, blog, saas, social. Use 'scale' to multiply record counts.",
      inputSchema: {
        type: "object",
        properties: {
          template: {
            type: "string",
            description:
              "Template ID: ecommerce, blog, saas, or social",
          },
          locale: {
            type: "string",
            description: "Locale for generated data. Default: en",
          },
          scale: {
            type: "number",
            description:
              "Multiplier for all table record counts. E.g. scale=10 generates 10x the default rows.",
          },
          format: {
            type: "string",
            enum: ["json", "csv", "sql"],
            description: "Output format. Default: json",
          },
          seed: {
            type: "number",
            description: "PRNG seed for reproducible output.",
          },
        },
        required: ["template"],
      },
    },
  • MCP server registration of the 'generate_from_template' tool using server.tool() with Zod schema validation and a handler that calls the API endpoint POST /api/v1/generate.
    // Tool: generate_from_template
    // ---------------------------------------------------------------------------
    
    server.tool(
      "generate_from_template",
      `Generate test data using a pre-built schema template.
    
    Pick a template (ecommerce, blog, saas, social) and optionally adjust the scale,
    locale, format, and seed. The template handles all the table definitions,
    field types, and foreign key relationships for you.
    
    Scale multiplier: 1.0 = default counts, 2.0 = double, 0.5 = half.
    Example: ecommerce template at scale 2.0 generates 100 users, 200 products, etc.`,
      {
        template: z
          .enum(["ecommerce", "blog", "saas", "social"])
          .describe("Template name"),
        scale: z
          .number()
          .optional()
          .default(1.0)
          .describe("Scale multiplier for record counts (default 1.0)"),
        locale: z
          .string()
          .optional()
          .describe("Default locale (en, de, fr, es, etc.)"),
        format: z
          .enum(["json", "csv", "sql"])
          .optional()
          .default("json")
          .describe("Output format"),
        sql_dialect: z
          .enum(["postgres", "mysql", "sqlite"])
          .optional()
          .describe("SQL dialect (only when format=sql)"),
        seed: z
          .number()
          .optional()
          .describe("Seed for reproducible output"),
      },
      async (params) => {
        // Templates are resolved server-side via the generate endpoint
        // We construct a request with the template parameter
        const body: Record<string, unknown> = {
          template: params.template,
          scale: params.scale,
        };
        if (params.locale) body.locale = params.locale;
        if (params.format) body.format = params.format;
        if (params.sql_dialect) body.sql_dialect = params.sql_dialect;
        if (params.seed !== undefined) body.seed = params.seed;
    
        const res = await apiCall("POST", "/api/v1/generate", body);
    
        if (!res.ok) {
          return {
            content: [
              {
                type: "text" as const,
                text: `API error (${res.status}): ${JSON.stringify(res.data, null, 2)}`,
              },
            ],
            isError: true,
          };
        }
    
        return {
          content: [
            {
              type: "text" as const,
              text: JSON.stringify(res.data, null, 2),
            },
          ],
        };
      }
    );
Behavior4/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

Without annotations, the description explains key behaviors: template handles table definitions, relationships, scale multiplier effect, and seed for reproducibility. It does not mention potential side effects or authorization, but the generative nature implies non-destructive operation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is concise (3 sentences plus examples) and front-loaded with the core purpose. It uses a clear structure with an introductory sentence, optional parameters list, and an illustrative example.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness4/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

For a tool with 6 parameters and no output schema, the description covers templates, scale, locale, format, sql_dialect, and seed adequately. It could explicitly state what the tool returns (e.g., generated data in chosen format), but the format parameter hints at this.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters4/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

All 6 parameters have schema descriptions (100% coverage). The description adds context beyond the schema, such as scale multiplier meaning, locale as default, and sql_dialect only for format=sql, enhancing understanding.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose5/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool generates test data using pre-built schema templates, listing specific templates (ecommerce, blog, saas, social). This distinguishes it from sibling tools like generate_test_data (which likely requires custom schemas).

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines4/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides guidance on when to use the tool (by picking a template and optionally adjusting scale, locale, etc.) and includes an example. However, it lacks explicit when-not-to-use context or direct comparison with sibling tools.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/dinosaur24/mockhero'

If you have feedback or need assistance with the MCP directory API, please join our Discord server