Diagram Publishing Engine Claude Code implementation guide
Red-team corrected architecture

Build a diagram publishing engine. Not a prompt wrapper.

The reliable path is natural-language intent → family-specific typed specification → deterministic SVG layout → geometry and visual validation → exported artifact.

3 diagram familiesSequence, comparison, and architecture
1 canonical formatAccessible, deterministic SVG
0 layout guessesThe model defines semantics, not pixels
No sections match that search.

Finding 01

The original model was too narrow

The earlier analysis treated all examples as graph-based agent workflows. That was not supported by the referenced page.

Incorrect abstraction

“Everything is a graph”

The context-usage visual is a comparative quantitative infographic. It has no graph nodes, control-flow edges, or decision semantics.

Partially correct

“Use an intermediate representation”

An IR remains the right architecture. The correction is to use family-specific schemas instead of forcing every diagram into nodes and edges.

Strong principle

“Separate semantics from rendering”

This remains the central design decision. Claude should identify meaning. Trusted code should own geometry, typography, and export.

A universal graph schema becomes an exception warehouse when it is asked to represent time, quantitative comparison, and architecture with the same primitives.
Previous claimVerdictCorrection
These are graph-based tool orchestration diagrams.Mostly incorrectOne is a segmented comparison graphic. Another is a sequence diagram.
Nodes are tools or agents.IncorrectSequence diagrams use participants, lifelines, activations, and ordered messages.
Edges distinguish control and data flow.UnsupportedThe arrows in the published sequence visual represent messages over time.
Mermaid should be the primary renderer.Too broadUse Mermaid as an adapter. Use deterministic SVG as the canonical output.
Use Neo4j for storage.PrematureA graph database adds complexity without solving the core layout problem.

Finding 02

One visual system. Multiple grammars.

The commonality is editorial design language, not diagram semantics. Select a family before generating a specification.

Time-ordered participant interactions
Programmatic tool-calling sequence User, API, Claude, and code execution environment exchange ordered messages. Claude creates a script, the environment runs tool calls, and the result returns to the user. Programmatic tool calling Participants are stable. Time progresses vertically. User API Claude Code execution environment Request Generate orchestration Run script + tool calls Execution result Final response

Design 01

The corrected system architecture

The model converts intent into a constrained semantic specification. The application converts that specification into a visual artifact.

1 · InterpretNatural-language brief

User intent, evidence, audience, and desired visual outcome.

2 · ClassifyDiagram family

Sequence, comparison, architecture, timeline, or another explicit family.

3 · SpecifyTyped semantic IR

Schema-valid content without pixel positions or arbitrary SVG.

4 · RenderDeterministic SVG scene

Family renderer owns geometry, typography, routing, and tokens.

5 · VerifyAudits + export

Geometry checks, screenshots, accessibility, provenance, and file output.

Model responsibility

What Claude should decide

Which facts and relationships belong in the visual.
Which diagram family best communicates the intended message.
Participant names, event order, metrics, labels, and grouping.
What can be removed to preserve editorial clarity.
Renderer responsibility

What Claude should not decide

×Exact x/y coordinates and manual SVG path geometry.
×Typography measurements based on character-count guesses.
×Whether visual collisions are acceptable.
×Security-sensitive serialization or raw markup injection.

Design 02

Use family-specific typed specifications

A discriminated union provides shared infrastructure while preserving each diagram family’s native grammar.

sequence-diagram.ts
export interface SequenceDiagramSpec {
  kind: "sequence";
  title: string;

  participants: Array<{
    id: string;
    label: string;
    role?: "person" | "service" |
      "model" | "tool";
  }>;

  events: Array<
    | {
        type: "message";
        from: string;
        to: string;
        label: string;
      }
    | {
        type: "activate" | "deactivate";
        participant: string;
      }
    | {
        type: "group-start" | "group-end";
        label?: string;
      }
  >;
}
comparison-diagram.ts
export interface ComparisonDiagramSpec {
  kind: "segmented-comparison";
  title: string;
  capacityLabel?: string;

  scenarios: Array<{
    id: string;
    label: string;
    total: number;
    segments: Array<{
      id: string;
      label: string;
      value: number;
      accent: "blue" | "mint" |
        "coral" | "cream" |
        "neutral";
    }>;
  }>;
}
diagram-spec.ts
export type DiagramSpec =
  | SequenceDiagramSpec
  | ComparisonDiagramSpec
  | ArchitectureDiagramSpec;
Key rule: The specification must be rich enough to express semantics and constrained enough that a deterministic renderer can guarantee layout.

Design 03

Rendering strategy

Each diagram family gets the simplest renderer capable of producing editorial-quality output.

Canonical format

SVG

Resolution-independent, browser-native, accessible, inspectable, and suitable as the source for PNG or PDF export.

Custom layout

Sequence diagrams

Participant lanes, lifelines, event rows, activations, message arrows, and text wrapping are deterministic enough to own directly.

Selective automation

Architecture diagrams

Use ELK-style layered layout for graph-shaped diagrams. Do not use it for segmented comparison or fixed-time sequence layouts.

Typography is the hidden hard problem

Font metrics change geometry. Wrapped labels change heights. Headless rendering can use a fallback font and move every element.

1Create a draft SVG.
2Load it in a browser runtime.
3Measure rendered text using DOM or SVG APIs.
4Recompute wrapping, boxes, routing, and viewBox.

Use a tokenized visual system

The shared style comes from warm surfaces, restrained strokes, low-saturation accents, strong title hierarchy, direct labels, and generous whitespace.

Theme tokens replace prompt-by-prompt styling.
Accent relationships matter more than exact hexadecimal values.
Layout density is controlled centrally.

Design 04

Validation is a subsystem, not a final check

A successful render is not the same as a correct diagram. Validate content, geometry, accessibility, and visual stability.

Schema + semantic validation

Reject missing or unknown participant and node references.
Reject negative quantitative values and invalid totals.
Validate activation, response, and group ordering.
Apply explicit limits to labels, nesting, and element counts.

Geometry + visual validation

Detect text outside containers and canvas bounds.
Detect text-arrow, node-node, and label-label collisions.
Flag unreadable font sizes and insufficient padding.
Capture fixture screenshots and compare visual regressions.

Minimum fixture matrix

DimensionCasesPurpose
Text lengthShort, wrapped, pathologicalValidates measurement and container growth.
Scale4, 8, and maximum supported participantsExposes density and routing limits.
FlowLoops, parallel groups, empty optional fieldsExercises sequence semantics.
ViewportMobile, desktop, print exportValidates responsive presentation.
ThemeLight, dark, preferred font missingExposes contrast and metric drift.
LanguageLong words, CJK, right-to-leftTests internationalization assumptions.

Design 05

Security boundaries

The renderer processes model-generated and user-provided content. Treat every label and path as untrusted input.

Injection risk

Do not concatenate raw SVG

Escape XML or use a DOM/JSX renderer. Block scripts, event attributes, external URLs, remote fonts, and uncontrolled embedded HTML.

Resource risk

Constrain complexity

Limit elements, label length, nested groups, canvas dimensions, render iterations, export resolution, and total execution time.

Filesystem boundary

Restrict outputs

Generate filenames server-side, reject traversal, write only to approved directories, and avoid arbitrary command execution.

unsafe-vs-safe.tsx
// Unsafe: model or user text is inserted directly into markup.
svg += `<text>${userLabel}</text>`;

// Safer: render text as a DOM/JSX text node and validate length.
return <text>{validatedLabel}</text>;

Integration

Claude Code and MCP integration

Start with a local CLI. Add a Claude Code skill for generation discipline. Add MCP when multiple clients or remote execution justify the boundary.

Phase 1TypeScript CLI

Render, validate, inspect, snapshot, and export.

Phase 2Claude Code skill

Classification rules, schema examples, simplification guidance, CLI usage.

Phase 3MCP server

Expose safe render and validation tools to multiple clients.

Phase 4CI integration

Generate assets, run snapshots, publish diagnostics.

Phase 5Governance

Version schemas, themes, and renderer behavior.

cli.sh
diagram validate diagram.json

diagram render diagram.json \
  --format svg \
  --output architecture.svg

diagram snapshot diagram.json \
  --output architecture.png
mcp-contract.ts
const RenderDiagramInput = z.object({
  spec: DiagramSpecSchema,
  format: z.enum([
    "svg", "png", "pdf", "html"
  ]).default("svg"),
  theme: z.string().default(
    "editorial-warm"
  ),
  validate: z.boolean().default(true)
});

Execution

MVP scope

The smallest useful product should prove both behavioral diagrams and quantitative editorial graphics.

Include

First release

Sequence renderer.
Segmented comparison renderer.
Warm editorial design tokens.
SVG canonical output and PNG export.
Zod schemas, text measurement, and geometry validation.
Fixture screenshots and visual regression tests.
Claude Code skill, optional MCP wrapper, and provenance metadata.
Defer

Later releases

Drag-and-drop editing and real-time collaboration.
Graph databases and arbitrary renderer plugins.
Fully general UML or universal diagram grammar.
AI-generated pixel positioning.
Figma export and image-to-diagram conversion.
The first two renderers should force the architecture to support both behavior over time and quantitative comparison. That is the real design test.

Evidence

Provenance and source map

This document distinguishes direct observations, architectural recommendations, and explicit inference.

Methodology

1Inspect the referenced Anthropic article and published diagram assets.
2Separate the content grammar from the visual design system.
3Audit earlier claims as correct, unsupported, or premature.
4Reconstruct a production architecture using primary technical specifications and official documentation.

Claim classes

OObservation: directly visible in the published visuals or documented behavior.
RRecommendation: engineering guidance proposed in this document.
IInference: a conclusion derived from multiple observations and implementation constraints.
Anthropic — Advanced tool use

Primary reference for the visual examples and advanced tool-use concepts.

Primary
W3C — SVG 2

Canonical specification for scalable vector graphics and text measurement behavior.

Specification
Mermaid — Sequence diagrams

Reference for Mermaid’s sequence-diagram feature set and interoperability role.

Official docs
Eclipse ELK — Layered algorithm

Reference for layered graph layout, routing, ports, and compound graph support.

Official docs
Playwright — Screenshots

Reference for programmatic browser screenshot generation and visual fixtures.

Official docs
Claude Code — MCP

Reference for local and remote MCP server integration with Claude Code.

Official docs
Claude Code — Security

Reference for trust boundaries and security considerations around tools and extensions.

Official docs