How the GenerateTheme Tool Creates CSS Styling for AI-Generated Designs in Secure-Design

The GenerateTheme tool is an AI-driven utility that persists complete CSS stylesheets to the workspace by validating file paths, auto-creating directories, and writing AI-generated CSS content via the Vercel AI SDK.

The generateTheme tool is a core component of the Secure-Design Visual Studio Code extension, enabling AI agents to output concrete CSS files for generated UI mock-ups. According to the hbmartin/secure-design source code, this utility bridges the gap between LLM-generated design descriptions and actual stylesheet persistence, ensuring safe file operations within the workspace sandbox.

Architecture of the GenerateTheme Tool

The tool operates through a six-step pipeline defined in src/tools/theme-tool.ts, combining schema validation, security checks, and file system operations to transform AI-generated CSS into persistent workspace files.

Tool Registration and Schema Definition

The tool is exposed to the LLM via the tool() helper from the Vercel AI SDK. Its input schema is strictly defined using zod (source lines 34‑44) and includes:

  • theme_name – A human-readable identifier for the theme.
  • reasoning_reference – A short explanation of the design choices.
  • cssSheet – The complete CSS content, which must obey the constraints listed in cssSheetDescription (source lines 17‑32).
  • cssFilePath – The destination path, relative to the workspace root or absolute within the workspace boundaries.
  • create_dirs – An optional boolean flag (default true) that triggers automatic directory creation.

Security-First Path Validation

Before any file system activity, the tool calls validateWorkspacePath and resolveWorkspacePath (source lines 66‑73) to ensure the supplied path lives inside the current workspace. This resolution step prevents the AI from writing outside the extension’s sandbox via directory traversal attacks.

Directory Preparation and File Persistence

If create_dirs is set to true, the tool checks whether the target directory exists and creates it recursively using fs.mkdirSync while logging the action (source lines 74‑81). The CSS string supplied by the model is then written verbatim to the resolved file using fs.writeFileSync with UTF‑8 encoding (source line 84).

Response Handling and Error Management

Upon successful execution, the tool returns a structured success payload via createSuccessResponse (source lines 86‑97). This payload includes the absolute file path, theme name, reasoning reference, and the raw stylesheet, enabling the calling flow to display confirmations or trigger UI updates. Any exceptions are caught and transformed into uniform error responses via handleToolError (source lines 98‑102), ensuring the LLM receives clear diagnostic messages.

Implementation Examples

Registering the Tool

The tool is instantiated and registered within the agent's toolset in src/services/customAgentService.ts:

import { createThemeTool } from '../tools/theme-tool';

// When constructing the agent's toolset
const tools = [
  createThemeTool(executionContext),
  // other tools …
];

LLM Request Payload

When the AI invokes the tool, it provides a structured payload matching the zod schema:

{
  "theme_name": "Midnight‑Glow",
  "reasoning_reference": "Inspired by dark‑mode UI kits and neon accents",
  "cssSheet": ":root { --background:#0a0a0a; --foreground:#e0e0e0; --primary:#ff5f5f; ... }",
  "cssFilePath": ".superdesign/theme/midnight-glow.css"
}

Consuming the Response

The extension handles the structured response to provide user feedback:

if (toolResponse.success) {
  vscode.window.showInformationMessage(
    `Theme "${toolResponse.theme_name}" saved at ${toolResponse.filePath}`
  );
}

Key Source Files

The following files comprise the generateTheme implementation:

  • src/tools/theme-tool.ts – Core implementation containing the tool definition, validation logic, and file I/O operations.
  • src/services/customAgentService.ts – Registers createThemeTool so the LLM can invoke it during design generation sessions.
  • src/tools/tool-utils.ts – Provides helper functions for path validation (validateWorkspacePath, resolveWorkspacePath) and response formatting (createSuccessResponse, handleToolError).
  • src/webview/utils/themeParser.ts – Parses generated CSS for previewing in the webview (optional consumption, not part of the creation pipeline).

Summary

  • The generateTheme tool uses the Vercel AI SDK and zod to expose a type-safe interface for LLM-generated CSS persistence.
  • Path validation via validateWorkspacePath ensures all writes remain within the workspace sandbox.
  • The create_dirs parameter enables recursive directory creation, allowing nested theme structures without manual setup.
  • CSS content is written verbatim using fs.writeFileSync with UTF-8 encoding, preserving the AI's exact styling instructions.
  • Structured success and error responses via createSuccessResponse and handleToolError maintain clear communication between the tool and the calling agent.

Frequently Asked Questions

What parameters does the generateTheme tool require?

The tool requires theme_name (string), reasoning_reference (string), cssSheet (string), and cssFilePath (string). It also accepts an optional create_dirs boolean that defaults to true. These parameters are strictly validated using a zod schema defined in src/tools/theme-tool.ts at lines 34‑44.

How does the tool prevent writing files outside the workspace?

Before writing, the tool calls validateWorkspacePath and resolveWorkspacePath (lines 66‑73) to verify the supplied path resolves to a location inside the current workspace. This security check prevents directory traversal attacks and ensures the extension remains within its sandboxed environment.

Can the tool create nested directory structures automatically?

Yes. When the create_dirs parameter is set to true (the default), the tool checks for the existence of the target directory and creates it recursively using fs.mkdirSync (lines 74‑81). This allows the LLM to specify deep paths like .superdesign/themes/dark/midnight.css without requiring manual directory creation.

What happens if the CSS file cannot be written?

Any exception during file writing is caught and handled by handleToolError (lines 98‑102), which transforms the error into a uniform error response. This response is returned to the LLM with diagnostic details, allowing the agent to report the failure or attempt recovery, while the extension logs the specific error for debugging.

Have a question about this repo?

These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:

Share the following with your agent to get started:
curl -s "https://instagit.com/install.md"

Works with
Claude Codex Cursor VS Code OpenClaw Any MCP Client

Maintain an open-source project? Get it listed too →