/ai agents
/cli reference

NitroStack CLI Reference - For AI Code Editors

Comprehensive CLI reference for AI agents working with NitroStack v3.0


Installation

# Global install (recommended for end users)
npm install -g nitrostack

# Or use npx (no installation)
npx nitrostack --version

Commands Overview

nitrostack init <project-name>             # Create new project
nitrostack dev [--port <number>]           # Start development mode
nitrostack build                            # Build for production
nitrostack generate <type> <name> [opts]   # Generate code
nitrostack --version                        # Show version
nitrostack --help                           # Show help

1. Initialize Project

# Basic initialization
nitrostack init my-project

# With specific template
nitrostack init my-project --template typescript-starter
nitrostack init my-ecommerce --template typescript-auth

Available Templates

  1. typescript-starter (Simple & Educational)

    • Single calculator module
    • No authentication
    • No database
    • Perfect for learning basics
    • Tools, resources, prompts, widgets, health checks
  2. typescript-auth (Full-Featured E-commerce)

    • JWT, API Keys, OAuth 2.1 authentication
    • SQLite database with seed data
    • 5 feature modules (auth, products, cart, orders, addresses)
    • 20+ UI widgets
    • Guards, caching, rate limiting
    • Production-ready structure

What init Does

  1. āœ… Copies template files
  2. āœ… Installs npm dependencies (MCP server)
  3. āœ… Installs widget dependencies (src/widgets/)
  4. āœ… Creates .env from .env.example
  5. āœ… Project is ready to run (npm run dev will build on first run)

After Init

cd my-project

# For typescript-auth template: setup database
npm run setup-db

# Start development
npm run dev

2. Development Mode

# Start all services
nitrostack dev

# Custom port for Studio
nitrostack dev --port 3002

What It Starts

  1. MCP Server (stdio mode)

    • Communicates via stdin/stdout
    • Follows MCP protocol spec
    • Hot reload on code changes
  2. Studio (port 3000, or custom)

    • Visual development interface
    • Test tools manually
    • AI chat (OpenAI/Gemini)
    • Widget preview
    • Resources browser
    • Prompts testing
    • Health checks dashboard
    • OAuth 2.1 config
    • Connection monitoring
  3. Widget Dev Server (port 3001)

    • Next.js dev server
    • Hot module replacement
    • Serves UI widgets
    • Fast refresh

Studio Features

TabPurpose
ToolsExecute tools, see widget previews, examples
AI ChatChat with LLM using your tools
ResourcesBrowse resources, view UI widgets
PromptsTest prompt templates
HealthMonitor health checks
OAuth 2.1Configure OAuth endpoints
PingTest MCP connection

URLs

  • Studio UI: http://localhost:3000
  • Widget Dev: http://localhost:3001
  • MCP Server: stdio (no HTTP)

Hot Reload

Changes auto-reload:

  • āœ… TypeScript files (src/**/*.ts)
  • āœ… Widget files (src/widgets/app/**/*)
  • āœ… No manual restart needed

3. Build Project

nitrostack build

Build Process

The nitrostack build command:

  1. Builds Widgets First (if present)

    • Input: src/widgets/
    • Output: src/widgets/.next/
    • Production optimized
    • Static assets bundled
  2. Compiles TypeScript

    • Input: src/**/*.ts
    • Output: dist/**/*.js
    • ES modules format
    • Source maps included
  3. Auto-Detects Project Structure

    • Checks for src/widgets/package.json
    • Installs widget dependencies if needed
    • Handles everything automatically

Output Structure

dist/
ā”œā”€ā”€ index.js               # Entry point
ā”œā”€ā”€ app.module.js
ā”œā”€ā”€ modules/
│   ā”œā”€ā”€ auth/
│   ā”œā”€ā”€ products/
│   └── ...
└── ... (all compiled code)

src/widgets/.next/         # Built widgets

Run Production Build

# After build - use npm script (recommended)
npm start

# Or run directly
node dist/index.js

# Or use CLI
nitrostack start

The nitrostack start command:

  • Runs the compiled dist/index.js
  • Starts widget production server (if built)
  • Sets NODE_ENV=production
  • Handles all process orchestration

4. Generate Code

Generate Module

nitrostack generate module payments

Creates:

src/modules/payments/
ā”œā”€ā”€ payments.module.ts       # @Module definition
ā”œā”€ā”€ payments.tools.ts        # @Tool definitions
ā”œā”€ā”€ payments.resources.ts    # @Resource definitions
ā”œā”€ā”€ payments.prompts.ts      # @Prompt definitions
└── payments.service.ts      # @Injectable service

Generated module includes:

  • Boilerplate decorator setup
  • Example tool with Zod schema
  • Example resource
  • Example prompt
  • Injectable service with DI
  • Ready to import in app.module.ts

Generate Tool

nitrostack generate tool process-payment --module payments
  • Adds tool to src/modules/payments/payments.tools.ts
  • Includes:
    • @Tool decorator
    • Zod input schema
    • Example request/response
    • @Widget placeholder
    • Execution context

Generate Resource

nitrostack generate resource payment-schema --module payments
  • Adds resource to src/modules/payments/payments.resources.ts
  • Includes URI pattern, mime type, examples

Generate Prompt

nitrostack generate prompt payment-help --module payments
  • Adds prompt to src/modules/payments/payments.prompts.ts
  • Includes arguments, message template

Generate Guard

nitrostack generate guard admin

Creates src/guards/admin.guard.ts:

@Injectable()
export class AdminGuard implements Guard {
  async canActivate(context: ExecutionContext): Promise<boolean> {
    // Your authorization logic
  }
}

Usage:

@Tool({ name: 'admin_tool' })
@UseGuards(AdminGuard)
async adminTool(input: any, ctx: ExecutionContext) {}

Generate Middleware

nitrostack generate middleware logging

Creates src/middleware/logging.middleware.ts:

@Middleware()
export class LoggingMiddleware implements MiddlewareInterface {
  async use(context: ExecutionContext, next: () => Promise<any>) {
    // Before
    const result = await next();
    // After
    return result;
  }
}

Generate Interceptor

nitrostack generate interceptor transform

Creates src/interceptors/transform.interceptor.ts:

@Interceptor()
export class TransformInterceptor implements InterceptorInterface {
  async intercept(context: ExecutionContext, next: () => Promise<any>) {
    const result = await next();
    return { success: true, data: result };
  }
}

Generate Pipe

nitrostack generate pipe validation

Creates src/pipes/validation.pipe.ts:

@Pipe()
export class ValidationPipe implements PipeInterface {
  async transform(value: any, metadata: any): Promise<any> {
    // Transform/validate value
    return value;
  }
}

Generate Types

# Generate TypeScript types from tool schemas
nitrostack generate types

# Custom output path
nitrostack generate types --output src/widgets/types/generated.ts

What It Does:

  1. Scans all *.tools.ts files
  2. Extracts Zod schemas from @Tool decorators
  3. Converts to TypeScript interfaces
  4. Outputs to src/widgets/types/tool-data.ts (default)

Example Input (tool):

@Tool({
  name: 'get_product',
  inputSchema: z.object({
    product_id: z.string()
  })
})
async getProduct(input: any) {
  return { id: input.product_id, name: 'Product', price: 99 };
}

Example Output (generated types):

// Auto-generated by NitroStack CLI
export interface GetProductInput {
  product_id: string;
}

export interface GetProductOutput {
  id: string;
  name: string;
  price: number;
}

Usage in Widgets:

import { GetProductOutput } from '../../types/tool-data';

export default function ProductCard({ data }: { data: GetProductOutput }) {
  return <div>{data.name} - ${data.price}</div>;
}

When to Run:

  • After adding new tools
  • After modifying tool schemas
  • Before building widgets
  • As part of CI/CD pipeline

Configuration

Project Configuration (nitrostack.config.ts)

export default {
  server: {
    name: 'my-server',
    version: '1.0.0',
    description: 'My MCP server'
  },
  studio: {
    port: 3000,
    enabled: true
  },
  widgets: {
    port: 3001,
    devServer: true
  },
  logging: {
    level: 'info',        // debug | info | warn | error
    file: 'logs/server.log'
  }
};

Environment Variables (.env)

# Node Environment
NODE_ENV=development

# JWT (if using typescript-auth template)
JWT_SECRET=your-super-secret-jwt-key-change-this-in-production

# OAuth 2.1 (if using typescript-auth template)
OAUTH_CLIENT_ID=your-client-id
OAUTH_CLIENT_SECRET=your-client-secret
OAUTH_REDIRECT_URI=http://localhost:3000/callback

# Database (if using typescript-auth template)
DATABASE_PATH=./data/ecommerce.db

# Server
PORT=3000

# Gemini API (for Studio chat)
GEMINI_API_KEY=your-gemini-key

Common Workflows

1. Create New Project (Starter Template)

# Install CLI
npm install -g nitrostack

# Initialize project
nitrostack init my-calculator --template typescript-starter
cd my-calculator

# Start development
npm run dev

# Open Studio
# http://localhost:3000

2. Create New Project (Auth Template)

# Install CLI
npm install -g nitrostack

# Initialize project
nitrostack init my-shop --template typescript-auth
cd my-shop

# Setup database
npm run setup-db

# Start development
npm run dev

# Open Studio and login
# http://localhost:3000

3. Add New Feature Module

# Generate module
nitrostack generate module payments

# Add to app.module.ts imports
# imports: [ConfigModule.forRoot(), PaymentsModule]

# Generate tools
nitrostack generate tool create-payment --module payments
nitrostack generate tool get-payment --module payments

# Generate types for widgets
nitrostack generate types

# Create widget
mkdir -p src/widgets/app/payment-success
# Create page.tsx in that directory

# Test in Studio
npm run dev

4. Development Cycle

# Start dev server (auto-detects and builds everything)
npm run dev

# The CLI automatically:
# - Installs dependencies (if needed)
# - Builds widgets (on first run)
# - Starts TypeScript watch mode
# - Starts Studio
# - Starts widget dev server
# - Hot reloads everything

# Edit code (auto-reloads)
# - Edit src/modules/**/*.ts (MCP server hot reloads)
# - Edit src/widgets/app/**/* (Widget dev server hot reloads)

# Test in Studio
# - Execute tools manually
# - Test with AI chat
# - Preview widgets

# Add widget dependencies
npm run widget add <package-name>

# Generate types for widgets
nitrostack generate types

# Build for production
npm run build

# Test production build
npm start

5. Deploy to Production

# Build project
nitrostack build

# Copy to server
scp -r dist/ user@server:/app/
scp -r src/widgets/.next/ user@server:/app/widgets/
scp package.json user@server:/app/
scp .env.production user@server:/app/.env

# On server
cd /app
npm install --production
node dist/index.js

Troubleshooting

CLI Not Found

# Install globally
npm install -g nitrostack

# Or use npx
npx nitrostack init my-project

Port Already in Use

# Use custom port
nitrostack dev --port 3002

# Or kill process on port
lsof -ti:3000 | xargs kill -9
lsof -ti:3001 | xargs kill -9

Build Errors

# Clean and rebuild
rm -rf dist
rm -rf src/widgets/.next
npm run build

# Check TypeScript errors
npx tsc --noEmit

Module Not Found: nitrostack

# Reinstall dependencies
rm -rf node_modules package-lock.json
npm install

Widgets Not Loading

# The CLI handles widgets automatically, but if you need to debug:

# Install widget dependencies
npm run widget install

# Check widget dev server
curl http://localhost:3001

# Or restart dev mode (rebuilds everything)
npm run dev

Database Errors (typescript-auth)

# Reset database
npm run reset-db

# Check database exists
ls -la data/ecommerce.db

Studio Not Connecting

# Check MCP server is running
ps aux | grep node

# Check logs
tail -f logs/server.log

# Restart
npm run dev

Quick Reference Card

Commands

CommandDescription
nitrostack init <name>Create new project
nitrostack init <name> --template <type>Create with specific template
nitrostack devStart dev mode (server + Studio + widgets)
nitrostack dev --port <n>Start with custom Studio port
nitrostack buildBuild for production
nitrostack generate module <name>Generate module
nitrostack generate tool <name> --module <m>Generate tool
nitrostack generate resource <name> --module <m>Generate resource
nitrostack generate prompt <name> --module <m>Generate prompt
nitrostack generate guard <name>Generate guard
nitrostack generate middleware <name>Generate middleware
nitrostack generate interceptor <name>Generate interceptor
nitrostack generate pipe <name>Generate pipe
nitrostack generate typesGenerate TypeScript types
nitrostack --versionShow version
nitrostack --helpShow help

Project Scripts

ScriptDescription
npm run devStart development (MCP server + Studio + widgets, auto-build)
npm run buildBuild MCP server + widgets for production
npm startRun production server
npm run widget <cmd>Run npm command in widgets directory
npm run setup-dbInitialize database (auth template only)
npm run reset-dbReset database (auth template only)

Note: Old scripts like widgets:dev, widgets:build, widgets:install, server:dev, dev:build are no longer needed. The CLI handles everything automatically!

Studio URLs

URLPurpose
http://localhost:3000Studio UI
http://localhost:3000/chatAI Chat
http://localhost:3001Widget dev server

Key Concepts for AI Agents

1. Templates

  • typescript-starter: Learn basics, no auth, no DB
  • typescript-auth: Full-featured, production-ready

2. Development Flow

  • init → setup-db (if auth) → dev → test in Studio → build

3. Code Generation

  • Generate module first
  • Then generate tools/resources/prompts
  • Always run generate types after schema changes

4. Studio is Your Friend

  • Test tools before writing widgets
  • Use chat to verify AI integration
  • Check health, resources, prompts

5. Widget Development

  • Widgets live in src/widgets/app/
  • Link with @Widget('widget-name')
  • Generate types for type safety
  • Hot reload enabled

That's the complete NitroStack CLI reference!

Use nitrostack --help for more details or check /docs for SDK documentation.