Files
2026-03-21 18:07:33 +00:00

13 KiB
Raw Permalink Blame History

DungeonMaster.tools — Architecture Plan

1. Architecture Overview

DungeonMaster.tools is a stateless Micro-SaaS that provides D&D Dungeon Masters with AI-powered tools for encounter generation, NPC creation, and quest hook ideation.

┌─────────────────────────────────────────────────────────┐
│                     User (Browser)                        │
│                   (Next.js App Router)                   │
│          Dark Theme / Mobile-First / TypeScript          │
└──────────────────────────┬──────────────────────────────┘
                           │ fetch / POST
                           ▼
┌─────────────────────────────────────────────────────────┐
│                   LLM Proxy API                          │
│           https://llm.molberg.cloud/v1                  │
│              (OpenAI-compatible, sk-lp-*)                │
└─────────────────────────────────────────────────────────┘
                           ▲
                           │ Optional
┌──────────────────────────┴──────────────────────────────┐
│                     MongoDB                               │
│          (Content history — optional MVP)                │
└─────────────────────────────────────────────────────────┘
  • No auth for MVP — each session is stateless
  • Optional MongoDB for history; MVP can ship completely stateless
  • Single deployment on Coolify (LXC 114, subdomain on xmr.network)

2. Tech Decisions & Rationale

Decision Choice Rationale
Framework Next.js 15 (App Router) File-based routing, server actions, easy deployment to Coolify Docker
Language TypeScript (strict) Type safety, better DX, shadcn/ui compatibility
Styling Tailwind CSS + shadcn/ui Dark mode first, fantasy theme via CSS vars, accessible components
AI LLM Proxy (https://llm.molberg.cloud/v1) OpenAI-compatible, access to o4-mini/gpt-4o/Sonnet 4 at reduced cost
Database MongoDB (via Docker on Coolify) Flexible schema for varied generated content, easy to add history later
State React Server Components + use server Minimal client JS, fast initial load
Deployment Coolify Docker (LXC 114) Already provisioned, private GitHub repos, auto-deploy on push
Icons Lucide React shadcn/ui default, consistent stroke weight, fantasy-compatible
Fonts Cinzel (headings) + Crimson Pro (body) D&D-appropriate serif + readable body; loaded via next/font/google

Why Not NextAuth/Auth?

MVP scope is intentionally minimal. No user data means no auth complexity, no database user tables, no session management. This lets us ship in days instead of weeks.

Why MongoDB Over PostgreSQL?

Generated content is semi-structured (encounters → monsters + terrain, NPCs → traits + backstory). MongoDB's document model fits naturally and avoids complex migrations for a v1.


3. File/Folder Structure

dungeonmaster-tools/
├── .env.example                  # Template for env vars
├── .env.local                    # Local secrets (gitignored)
├── .gitignore
├── next.config.ts
├── tailwind.config.ts            # Dark theme + fantasy CSS vars
├── tsconfig.json
├── package.json
├── components.json               # shadcn/ui config
│
├── app/
│   ├── layout.tsx                # Root layout: fonts, theme, nav
│   ├── page.tsx                  # Landing / tool picker
│   ├── globals.css               # Tailwind + fantasy theme vars
│   │
│   ├── encounters/
│   │   └── page.tsx             # Encounter Generator page
│   │
│   ├── npc/
│   │   └── page.tsx             # NPC Generator page
│   │
│   └── quest-hooks/
│       └── page.tsx             # Quest Hooks page
│
├── components/
│   ├── ui/                      # shadcn/ui base components
│   │   ├── button.tsx
│   │   ├── card.tsx
│   │   ├── select.tsx
│   │   ├── slider.tsx
│   │   ├── switch.tsx
│   │   ├── textarea.tsx
│   │   └── badge.tsx
│   │
│   ├── nav.tsx                  # Site nav (logo + links)
│   ├── tool-card.tsx            # Homepage tool selection cards
│   ├── generator-form.tsx       # Shared form wrapper for all tools
│   ├── result-card.tsx           # Shared result display
│   ├── loading-dice.tsx          # Animated dice/loading state
│   └── theme-provider.tsx       # shadcn/ui theme context
│
├── lib/
│   ├── llm.ts                   # LLM Proxy client wrapper
│   ├── prompts/
│   │   ├── encounters.ts        # Encounter generation prompts
│   │   ├── npc.ts               # NPC generation prompts
│   │   └── quest-hooks.ts       # Quest hook prompts
│   └── types.ts                 # Shared TypeScript types
│
└── Dockerfile                   # Multi-stage: build → prod

4. API Design

No dedicated API routes needed for MVP. Use Next.js Server Actions instead — they live alongside the components, type-safe, and require zero extra infrastructure.

Server Actions

// app/encounters/actions.ts
'use server'
export async function generateEncounter(formData: EncounterFormData): Promise<EncounterResult>

// app/npc/actions.ts
'use server'
export async function generateNPC(formData: NPCFormData): Promise<NPCResult>

// app/quest-hooks/actions.ts
'use server'
export async function generateQuestHook(formData: QuestFormData): Promise<QuestResult>

All actions:

  1. Validate input (Zod schemas)
  2. Build prompt from form data
  3. Call llm.ts → LLM Proxy
  4. Parse JSON response
  5. Return typed result to client

If history is added later: Add a MongoDB write inside each action after successful generation. No new API surface needed.


5. Component Inventory

Pages

Page Route Description
Home / Tool picker with 3 fantasy-styled cards
Encounter Generator /encounters CR slider, terrain select, monster type multi-select, generate button
NPC Generator /npc Race/class/alignment selects, personality toggles, generate button
Quest Hooks /quest-hooks Tone/setting/difficulty selects, optional seed prompt, generate button

Shared Components

Component Type Purpose
ThemeProvider provider shadcn/ui theme context (dark default)
Nav client Top nav: logo left, tool links right, mobile hamburger
ToolCard server Homepage cards linking to each tool
GeneratorForm client Wrapper: form inputs + submit + loading state
ResultCard client Displays formatted generated content
LoadingDice client Animated spinning dice icon during generation
Button, Card, Select, Slider, Switch, Textarea, Badge ui shadcn/ui base components

Form Inputs Per Tool

Encounter Generator:

  • CR Range: dual slider (min/max, 0–30)
  • Terrain: select (Forest, Dungeon, Mountain, Swamp, Urban, Desert, Arctic, Underdark, Coastal)
  • Monster Types: multi-select (Aberration, Beast, Celestial, Construct, Dragon, Elemental, Fey, Fiend, Giant, Humanoid, Monstrosity, Ooze, Plant, Undead)
  • Party Size: number input (1–8)
  • Difficulty: radio (Easy / Medium / Hard / Deadly)

NPC Generator:

  • Race: select (All PHB races + popular custom options)
  • Class: select (All PHB classes)
  • Alignment: select (9 alignments, or "any")
  • Personality traits: multi-toggle (Noble, Criminal, Religious, Scholarly, Mercantile, Wanderer, etc.)
  • Tone: select (Serious / Lighthearted / Mysterious / Ominous)

Quest Hooks:

  • Setting: select (Fantasy / Horror / Intrigue / Exploration / Social)
  • Tone: select (Epic / Grounded / Comedic / Dark)
  • Difficulty: select (Low / Medium / High)
  • Seed: textarea (optional — user can give a starting prompt or leave blank)

6. AI Prompt Strategy

General Principles

  • JSON output required from all LLM calls — parse with zod on the client
  • System prompt sets D&D 5e rules context, tone, and output format
  • User prompt built dynamically from form inputs
  • Model: default to gpt-4o for quality; allow override via env var LLM_MODEL_FALLBACK

Encounter Generator Prompt

System: You are a D&D 5e expert. Generate balanced, thematic encounters.
Return JSON: { title, description, monsters: [{ name, cr, count, terrain_behavior }], loot, tactics, notes }

User: Generate a {difficulty} encounter for a party of {partySize} at CR {crRange}.
Terrain: {terrain}. Monster types preferred: {monsterTypes}.

NPC Generator Prompt

System: You are a D&D 5e expert. Generate vivid, usable NPCs with personality.
Return JSON: { name, race, class, appearance, personality, motivation, quirk, secret, hooks: [string] }

User: Generate a {tone} NPC: {race} {class}, alignment {alignment}.
Personality traits: {traits}. Make them memorable and ready-to-use at a table.

Quest Hook Generator Prompt

System: You are a D&D 5e expert. Generate creative quest hooks that inspire.
Return JSON: { title, premise, hook, npcs: [string], locations: [string], rewards, complications }

User: Generate a {difficulty} quest in a {setting} setting, {tone} tone.
{foptional seed prompt}

Prompt Best Practices

  • Always include: "Return valid JSON only. No markdown code blocks. No explanation."
  • Temperature: 0.8 (creative but not chaotic)
  • Max tokens: 1024 (short, actionable outputs — not novellas)
  • Retry once on parse failure before surfacing error to user

7. Environment Variables

# LLM Proxy (from vault: sk-lp-*)
LLM_API_KEY=sk-lp-xxxxxxxxxxxxxxxxxxxxxxxxxxxxx
LLM_BASE_URL=https://llm.molberg.cloud/v1

# Optional: override default model (gpt-4o)
LLM_MODEL=gpt-4o
LLM_MODEL_FALLBACK=gpt-4o-mini

# MongoDB (optional for MVP — omit for stateless)
# MONGODB_URI=mongodb://10.0.0.120:27017/dungeonmaster

Where to store: .env.local (never committed). On Coolify, add as build/runtime environment variables in the app settings.


8. Security Considerations

Concern Mitigation
API key exposure Stored in Coolify env vars, never in source code, never in .env.local on the server
LLM prompt injection User inputs fed as structured fields, not raw string interpolation into system prompt
Server-side AI calls only All LLM calls go through server actions — API key never touches the client
No auth abuse No auth = no broken auth, no session hijacking, no credential sprawl
Content safety System prompts include D&D-appropriate content guardrails; LLM Proxy adds its own
MongoDB injection Use official MongoDB driver, no raw query interpolation (only an issue if history is added)
Rate limiting Next.js API routes not exposed; rate limiting can be added later via middleware if needed
CORS No cross-origin API exposure; server actions are Same-Origin
Git repos All repos private (Zebratic GitHub account)

9. Deployment Plan (Coolify)

  1. Create private GitHub repo dungeonmaster-tools
  2. Push initial scaffold
  3. In Coolify UI: New Deployment → connect GitHub repo → branch main
  4. Set environment variables (LLM key, optional MongoDB URI)
  5. Set subdomain: dungeonmaster.xmr.network
  6. Coolify auto-builds Docker image and deploys
  7. Future updates: git push → auto-deploy

Dockerfile: Multi-stage — node:20-alpine build stage → minimal production stage. No PM2 needed; Next.js production mode handles clustering.


10. MVP Scope (What to Build First)

Phase 1 — Core (Ship Fast)

  • Next.js scaffold with Tailwind + shadcn/ui
  • Dark fantasy theme (Cinzel font, dark palette, subtle fantasy accents)
  • Encounter Generator (form + server action + LLM call)
  • Deploy to Coolify

Phase 2 — Expand

  • NPC Generator
  • Quest Hooks Generator
  • Mobile nav / responsive polish

Phase 3 — Nice to Have

  • MongoDB history (save generated content)
  • Copy-to-clipboard / share buttons
  • Regenerate with same seed
  • Custom model selector (user picks model)