jackspace/claudeskillz/better-chatbot

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Supplies the project-specific conventions, architecture, and contribution guidelines for the better-chatbot open-source AI chat platform (github.com/cgoinglove/better-chatbot; Next.js 15, Vercel AI SDK 5, Better Auth, Drizzle ORM, PostgreSQL). Covers the API architecture, the three- tier tool system (MCP, Workflow, Default), server action validators and the safe() wrapper, database repository patterns, compound component design, DAG workflow builder internals, Playwright E2E test setup, and principles such as progressive enhancement, defensive programming, and streaming-first, plus templates for adding tools, API routes, and repositories. Use when working in the better-chatbot repository, contributing features or fixes, adding API routes or database queries, implementing tools and workflows, building UI components, or integrating multiple AI providers.

Install

npx vskill@latest install jackspace/claudeskillz/better-chatbot

SKILL.md

better-chatbot Contribution & Standards Skill

Status: Production Ready Last Updated: 2025-11-04 (v2.1.0 - Added extension points + UX patterns) Dependencies: None (references better-chatbot project) Latest Versions: Next.js 15.3.2, Vercel AI SDK 5.0.82, Better Auth 1.3.34, Drizzle ORM 0.41.0


Overview

better-chatbot is an open-source AI chatbot platform for individuals and teams, built with Next.js 15 and Vercel AI SDK v5. It combines multi-model AI support (OpenAI, Anthropic, Google, xAI, Ollama, OpenRouter) with advanced features like MCP (Model Context Protocol) tool integration, visual workflow builder, realtime voice assistant, and team collaboration.

This skill teaches Claude the project-specific conventions and patterns used in better-chatbot to ensure contributions follow established standards and avoid common pitfalls.


Project Architecture

Directory Structure
better-chatbot/
├── src/
│ ├── app/ # Next.js App Router + API routes
│ │ ├── api/[resource]/ # RESTful API organized by domain
│ │ ├── (auth)/ # Auth route group
│ │ ├── (chat)/ # Chat UI route group
│ │ └── store/ # Zustand stores
│ ├── components/ # UI components by domain
│ │ ├── layouts/
│ │ ├── agent/
│ │ ├── chat/
│ │ └── export/
│ ├── lib/ # Core logic and utilities
│ │ ├── action-utils.ts # Server action validators (CRITICAL)
│ │ ├── ai/ # AI integration (models, tools, MCP, speech)
│ │ ├── db/ # Database (Drizzle ORM + repositories)
│ │ ├── validations/ # Zod schemas
│ │ └── [domain]/ # Domain-specific helpers
│ ├── hooks/ # Custom React hooks
│ │ ├── queries/ # Data fetching hooks
│ │ └── use-*.ts
│ └── types/ # TypeScript types by domain
├── tests/ # E2E tests (Playwright)
├── docs/ # Setup guides and tips
├── docker/ # Docker configs
└── drizzle/ # Database migrations

API Architecture & Design Patterns

Route Structure Philosophy

Convention: RESTful resources with Next.js App Router conventions

/api/[resource]/route.ts → GET/POST collection endpoints
/api/[resource]/[id]/route.ts → GET/PUT/DELETE item endpoints
/api/[resource]/actions.ts → Server actions (mutations)
Standard Route Handler Pattern

Location: src/app/api/

Template structure:

typescript
export async function POST(request: Request) {
try {
// 1. Parse and validate request body with Zod
const json = await request.json();
const parsed = zodSchema.parse(json);
// 2. Check authentication
const session = await getSession();
if (!session?.user.id) return new Response("Unauthorized", { status: 401 });
// 3. Check authorization (ownership/permissions)
if (resource.userId !== session.user.id) return new Response("Forbidden", { status: 403 });
// 4. Load/compose dependencies (tools, context, etc.)
const tools = await loadMcpTools({ mentions, allowedMcpServers });
// 5. Execute with streaming if applicable
const stream = createUIMessageStream({ execute: async ({ writer }) => { ... } });
// 6. Return response
return createUIMessageStreamResponse({ stream });
} catch (error) {
logger.error(error);
return Response.json({ message: error.message }, { status: 500 });
}
}
Shared Business Logic Pattern

Key Insight: Extract complex orchestration logic into shared utilities

Example: src/app/api/chat/shared.chat.ts

This file demonstrates how to handle:

  • Tool loading (loadMcpTools, loadWorkFlowTools, loadAppDefaultTools)
  • Filtering and composition (filterMCPToolsByMentions, excludeToolExecution)
  • System prompt building (mergeSystemPrompt)
  • Manual tool execution handling

Pattern:

typescript
// Shared utility function
export const loadMcpTools = (opt?) =>
safe(() => mcpClientsManager.tools())
.map((tools) => {
if (opt?.mentions?.length) {
return filterMCPToolsByMentions(tools, opt.mentions);
}
return filterMCPToolsByAllowedMCPServers(tools, opt?.allowedMcpServers);
})
.orElse({} as Record<string, VercelAIMcpTool>);
// Used in multiple routes
// - /api/chat/route.ts
// - /api/chat/temporary/route.ts
// - /api/workflow/[id]/execute/route.ts

Why: DRY principle, single source of truth, consistent behavior

Defensive Programming with safe()

Library: ts-safe for functional error handling

Philosophy: Never crash the chat - degrade features gracefully

typescript
// Returns empty object on failure, chat continues
const MCP_TOOLS = await safe()
.map(errorIf(() => !isToolCallAllowed && "Not allowed"))
.map(() => loadMcpTools({ mentions, allowedMcpServers }))
.orElse({}); // Graceful fallback
Streaming-First Architecture

Pattern: Use Vercel AI SDK streaming utilities

typescript
// In route handler
const stream = createUIMessageStream({
execute: async ({ writer }) => {
// Stream intermediate results
writer.write({ type: "text", content: "Processing..." });
// Execute with streaming
const result = await streamText({
model,
messages,
tools,
onChunk: (chunk) => writer.write({ type: "text-delta", delta: chunk })
});
return { output: result };
}
});
return createUIMessageStreamResponse({ stream });

Why: Live feedback, better UX, handles long-running operations


Tool System Deep Dive

Three-Tier Tool Architecture

Design Goal: Balance extensibility (MCP), composability (workflows), and batteries-included (default tools)

Tier 1: MCP Tools (External)
↓ Can be used in
Tier 2: Workflow Tools (User-Created)
↓ Can be used in
Tier 3: Default Tools (Built-In)
Tier 1: MCP Tools (External Integrations)

Location: src/lib/ai/mcp/

Philosophy: Model Context Protocol servers become first-class tools

Manager Pattern:

typescript
// mcp-manager.ts - Singleton for all MCP clients
export const mcpClientsManager = globalThis.__mcpClientsManager__;
// API:
mcpClientsManager.init() // Initialize configured servers
mcpClientsManager.getClients() // Get connected clients
mcpClientsManager.tools() // Get all tools as Vercel AI SDK tools
mcpClientsManager.toolCall(serverId, toolName, args) // Execute tool

Why Global Singleton?

  • Next.js dev hot-reloading → reconnecting MCP servers on every change is expensive
  • Persists across HMR updates
  • Production: only one instance needed

Tool Wrapping:

typescript
// MCP tools are tagged with metadata for filtering
type VercelAIMcpTool = Tool & {
_mcpServerId: string;
_originToolName: string;
_toolName: string; // Transformed for AI SDK
};
// Branded type for runtime checking
VercelAIMcpToolTag.create(tool)
Tier 2: Workflow Tools (Visual Composition)

Location: src/lib/ai/workflow/

Philosophy: Visual workflows become callable tools via @workflow_name

Node Types:

typescript
enum NodeKind {
Input = "input", // Entry point
LLM = "llm", // AI reasoning
Tool = "tool", // Call MCP/default tools
Http = "http", // HTTP requests
Template = "template",// Text processing
Condition = "condition", // Branching logic
Output = "output", // Exit point
}

Execution with Streaming:

typescript
// Workflows stream intermediate results
executor.subscribe((e) => {
if (e.eventType == "NODE_START") {
dataStream.write({
type: "tool-output-available",
toolCallId,
output: { status: "running", node: e.nodeId }
});
}
if (e.eventType == "NODE_END") {
dataStream.write({
type: "tool-output-available",
toolCallId,
output: { status: "complete", result: e.result }
});
}
});

Key Feature: Live progress updates in chat UI

Tier 3: Default Tools (Built-In Capabilities)

Location: src/lib/ai/tools/

Categories:

typescript
export const APP_DEFAULT_TOOL_KIT = {
[AppDefaultToolkit.Visualization]: {
CreatePieChart, CreateBarChart, CreateLineChart,
CreateTable, CreateTimeline
},
[AppDefaultToolkit.WebSearch]: {
WebSearch, WebContent
},
[AppDefaultToolkit.Http]: {
Http
},
[AppDefaultToolkit.Code]: {
JavascriptExecution, PythonExecution
},
};

Tool Implementation Pattern:

typescript
// Execution returns "Success", rendering happens client-side
export const createTableTool = createTool({
description: "Create an interactive table...",
inputSchema: z.object({
title: z.string(),
columns: z.array(...),
data: z.array(...)
}),
execute: async () => "Success"
});
// Client-side rendering in components/tool-invocation/
export function InteractiveTable({ part }) {
const args = part.input;
return <DataTable columns={args.columns} data={args.data} />;
}

Why Separation?

  • Server: Pure data/business logic
  • Client: Rich visualization/interaction
  • Easier testing, better performance
Tool Lifecycle
1. Request → /api/chat/route.ts
2. Parse mentions (@tool, @workflow, @agent)
3. Load tools based on mentions/permissions:
- loadMcpTools() → filters by mentions or allowedMcpServers
- loadWorkFlowTools() → converts workflows to tools
- loadAppDefaultTools() → filters default toolkits
4. Merge all tools into single Record<string, Tool>
5. Handle toolChoice mode:
- "manual" → LLM proposes, user confirms
- "auto" → full execution
- "none" → no tools loaded
6. Pass tools to streamText()
7. Stream results back
Convention-Based Extension

Adding a new tool type is simple:

  1. Add enum to AppDefaultToolkit
  2. Implement tool with createTool()
  3. Add to APP_DEFAULT_TOOL_KIT
  4. Tool automatically available via @toolname

Component & Design Philosophy

Organization by Feature

Location: src/components/

components/
├── ui/ → shadcn/ui primitives
├── layouts/ → App structure
├── agent/ → Agent-specific
├── workflow/ → Workflow editor
├── tool-invocation/ → Tool result rendering
└── *.tsx → Shared components

Principle: Group by feature, not by type

Compound Component Pattern

Example: message.tsx + message-parts.tsx

Philosophy: Break complex components into composable parts

typescript
// message.tsx exports multiple related components
export function PreviewMessage({ message }) { ... }
export function ErrorMessage({ error }) { ... }
// message-parts.tsx handles polymorphic content
export function MessageParts({ parts }) {
return parts.map(part => {
if (isToolUIPart(part)) return <ToolInvocation part={part} />;
if (part.type === 'text') return <Markdown text={part.text} />;
// ... other types
});
}
Client Component Wrapper Pattern

Example: chat-bot.tsx

Structure:

typescript
export default function ChatBot({ threadId, initialMessages }) {
// 1. State management (Zustand)
const [model, toolChoice] = appStore(useShallow(state => [...]));
// 2. Vercel AI SDK hook
const { messages, append, status } = useChat({
id: threadId,
initialMessages,
body: { chatModel: model, toolChoice },
});
// 3. Render orchestration
return (
<>
<ChatGreeting />
<MessageList messages={messages} />
<PromptInput onSubmit={append} />
</>
);
}

Why: Top-level orchestrates, delegates rendering to specialized components

Tool Result Rendering Separation

Key Architecture Decision:

  • Tool execution lives in lib/ai/tools/
  • Tool rendering lives in components/tool-invocation/

This is the start of the file. Read the full SKILL.md on GitHub.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

Repository stars
14
Repository forks
5
7-day trend score
14

Stars and forks are for the whole GitHub repository, not this skill alone. Refreshed 13 Apr 2026, 6 months ago.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/jackspace/claudeskillz/better-chatbot/badge)](https://verified-skill.com/skills/jackspace/claudeskillz/better-chatbot)

Something wrong with this skill or its page? Tell us.