Skip to main content
Glama

layout.generate_code

Generate React, Vue, or HTML code from section patterns with options for TypeScript/JavaScript and Tailwind/Vanilla CSS.

Instructions

セクションパターンからReact/Vue/HTMLコードを生成します。パターンIDを指定して、選択したフレームワーク(React, Vue, HTML)でコードを出力できます。TypeScript/JavaScript、Tailwind CSS/Vanilla CSSの選択も可能です。

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
patternIdYesセクションパターンID(UUID形式、必須)
optionsNoコード生成オプション

Implementation Reference

  • The actual handler function for layout.generate_code (reused from layout.to_code).
    /**
     * layout.to_code ツールハンドラー
     *
     * @param input - 入力パラメータ
     * @returns 生成されたコード(Response Objectパターン)
     *
     * @example
     * ```typescript
     * const result = await layoutToCodeHandler({
     *   patternId: '11111111-1111-1111-1111-111111111111',
     *   options: {
     *     framework: 'react',
     *     typescript: true,
     *     tailwind: true,
     *   },
     * });
     *
     * if (result.success) {
     *   console.log(result.data.code);
     * } else {
     *   console.error(result.error.message);
     * }
     * ```
     */
    export async function layoutToCodeHandler(input: unknown): Promise<LayoutToCodeOutput> {
      // 開発環境でのログ出力
      if (isDevelopment()) {
        logger.info("[MCP Tool] layout.to_code called", {
          patternId: (input as Record<string, unknown>)?.patternId,
        });
      }
    
      // 入力バリデーション
      let validated: LayoutToCodeInput;
      try {
        validated = layoutToCodeInputSchema.parse(input);
      } catch (error) {
        if (error instanceof ZodError) {
          const errorMessage = error.errors.map((e) => `${e.path.join(".")}: ${e.message}`).join(", ");
    
          if (isDevelopment()) {
            logger.error("[MCP Tool] layout.to_code validation error", {
              errors: error.errors,
            });
          }
    
          return createErrorResponse(
            LAYOUT_MCP_ERROR_CODES.VALIDATION_ERROR,
            `Validation error: ${errorMessage}`
          ) as LayoutToCodeOutput;
        }
    
        const errorMessage = error instanceof Error ? error.message : String(error);
        return createErrorResponse(
          LAYOUT_MCP_ERROR_CODES.INTERNAL_ERROR,
          errorMessage
        ) as LayoutToCodeOutput;
      }
    
      // サービスファクトリーチェック
      if (!serviceFactory) {
        if (isDevelopment()) {
          logger.error("[MCP Tool] layout.to_code service factory not set");
        }
    
        return createErrorResponse(
          "SERVICE_UNAVAILABLE",
          "Code generation service is not available"
        ) as LayoutToCodeOutput;
      }
    
      const service = serviceFactory();
    
      try {
        // セクションパターン取得
        const pattern = await service.getSectionPatternById(validated.patternId);
    
        if (!pattern) {
          if (isDevelopment()) {
            logger.warn("[MCP Tool] layout.to_code pattern not found", {
              patternId: validated.patternId,
            });
          }
    
          return createErrorResponse(
            LAYOUT_MCP_ERROR_CODES.PATTERN_NOT_FOUND,
            `Pattern not found: ${validated.patternId}`
          ) as LayoutToCodeOutput;
        }
    
        // オプション正規化
        const options = normalizeOptions(validated.options);
    
        if (isDevelopment()) {
          logger.debug("[MCP Tool] layout.to_code generating code", {
            patternId: validated.patternId,
            sectionType: pattern.sectionType,
            framework: options.framework,
            typescript: options.typescript,
            tailwind: options.tailwind,
          });
        }
    
        // コード生成
        let generatedCode: GeneratedCode;
        try {
          generatedCode = await service.generateCode(pattern, options);
        } catch (error) {
          const errorMessage = error instanceof Error ? error.message : String(error);
    
          if (isDevelopment()) {
            logger.error("[MCP Tool] layout.to_code generation error", {
              error: errorMessage,
            });
          }
    
          return createErrorResponse(
            LAYOUT_MCP_ERROR_CODES.CODE_GENERATION_FAILED,
            `Code generation failed: ${errorMessage}`
          ) as LayoutToCodeOutput;
        }
    
        // 結果を構築
        const data: LayoutToCodeData = {
          code: generatedCode.code,
          framework: options.framework,
          componentName: generatedCode.componentName,
          filename: generatedCode.filename,
          dependencies: generatedCode.dependencies,
          inspirationUrls: [pattern.webPage.url],
          usageScope: pattern.webPage.usageScope as UsageScope,
        };
    
        // データバリデーション
        layoutToCodeDataSchema.parse(data);
    
        if (isDevelopment()) {
          logger.info("[MCP Tool] layout.to_code completed", {
            patternId: validated.patternId,
            framework: options.framework,
            componentName: generatedCode.componentName,
            codeLength: generatedCode.code.length,
          });
        }
    
        return createSuccessResponse(data) as LayoutToCodeOutput;
      } catch (error) {
        // その他のエラーは変換
        const errorMessage = error instanceof Error ? error.message : String(error);
        const errorCode = determineErrorCode(error instanceof Error ? error : errorMessage);
    
        if (isDevelopment()) {
          logger.error("[MCP Tool] layout.to_code error", {
            code: errorCode,
            error: errorMessage,
          });
        }
    
        return createErrorResponse(errorCode, errorMessage) as LayoutToCodeOutput;
      }
    }
  • Registration of layout.generate_code handler.
    "layout.generate_code": layoutGenerateCodeHandler,
  • Definition of the layout.generate_code MCP tool including input schema.
    export const layoutGenerateCodeToolDefinition = {
      name: "layout.generate_code",
      description:
        "セクションパターンからReact/Vue/HTMLコードを生成します。" +
        "パターンIDを指定して、選択したフレームワーク(React, Vue, HTML)でコードを出力できます。" +
        "TypeScript/JavaScript、Tailwind CSS/Vanilla CSSの選択も可能です。",
      annotations: {
        title: "Layout Generate Code",
        readOnlyHint: false,
        idempotentHint: true,
        openWorldHint: false,
      },
      inputSchema: {
        type: "object" as const,
        properties: {
          patternId: {
            type: "string",
            format: "uuid",
            description: "セクションパターンID(UUID形式、必須)",
          },
          options: {
            type: "object",
            description: "コード生成オプション",
            properties: {
              framework: {
                type: "string",
                enum: ["react", "vue", "html"],
                description: "出力フレームワーク(デフォルト: react)",
                default: "react",
              },
              typescript: {
                type: "boolean",
                description: "TypeScript出力するか(デフォルト: true)",
                default: true,
              },
              tailwind: {
                type: "boolean",
                description: "Tailwind CSSを使用するか(デフォルト: true)",
                default: true,
              },
              componentName: {
                type: "string",
                description: "カスタムコンポーネント名(PascalCase形式)",
                pattern: "^[A-Z][a-zA-Z0-9]*$",
              },
              paletteId: {
                type: "string",
                format: "uuid",
                description: "適用するブランドパレットID(UUID形式)",
              },
              responsive: {
                type: "boolean",
                description:
                  "レスポンシブブレークポイント自動生成(デフォルト: true)。" +
                  "大きなwidth/padding/font-size/flex-directionをモバイルファーストのレスポンシブクラスに変換します。",
                default: true,
              },
            },
          },
        },
        required: ["patternId"],
      },
    };

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/TKMD/reftrix-mcp'

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