Backgen

io.github.IbrahimKhaled19由 GitHub 账号 IbrahimKhaled19 发布v1.14.0更新于 Oct 24, 2026

Generate Express.js backend projects with ORMs, auth, payments, and DevOps

概览

AI 生成的概览

BackGen 的本地 MCP 服务器让 AI 助手按所选 ORM、插件和 CRUD 资源来搭建和修改 Express.js 后端项目。

可以做什么
按所选 ORM、预设和插件搭建新的后端项目,并列出可用预设、插件或读取清单中的项目元数据(init_project、list_presets、list_plugins、project_info)。添加或移除 JWT、Clerk、Stripe、S3、限流及 DevOps 等插件(add_plugin、remove_plugin)。生成带字段、关联、校验和 Swagger 文档的 CRUD 资源模块,以及种子文件和测试工厂(generate_resource、generate_seed、generate_factory)。检查现有 BackGen 项目的配置问题(doctor)。
适用场景
适合让助手快速初始化 Express.js 与 TypeScript 后端、添加认证、支付、存储或 CI 插件,或在已有 BackGen 项目中生成 CRUD 模块和种子数据,而无需自己输入 CLI 命令。
运行要求
作为本地 stdio 进程在桌面运行,可通过 npx 加包名和 mcp 参数启动,或使用 backgen mcp 命令。需要 Node.js(doctor 检查版本不低于 18)和 npm。未声明认证、环境变量或请求头。
安装前请注意
这些工具会向项目写入文件:创建项目、安装插件(会添加 npm 依赖和环境变量)、生成模块以及移除插件文件。插件安装和生成的代码可能涉及 Stripe、Clerk、AWS S3 等第三方服务,之后需要各自的凭据。运行前请检查生成的改动。

安装

在 SourceWeft 中

  1. 打开 控制台中的 Backgen,将其添加到工作区。
  2. 为需要使用其工具的对话启用该服务。

Desktop only,通过 STDIO。 STDIO 服务会启动本地进程,因此需要 SourceWeft 桌面宿主。

其他 MCP 客户端

参照 仓库 中的启动说明。

README

BackGen

[CI] [npm version] [License: MIT]

[npm downloads] [GitHub stars]

🤖 AI-Ready

[BackGen MCP server] [BackGen MCP server]

BackGen ships a built-in MCP (Model Context Protocol) server that AI assistants (Claude, Cursor, GitHub Copilot, VS Code) can use to scaffold projects on your behalf.

Run via CLI:

bash
backgen mcp

Or configure your AI tool's MCP client:

json
{  "mcpServers": {    "backgen": {      "command": "npx",      "args": ["-y", "@ibrahimkhaled19/backgen", "mcp"]    }  }}

Available MCP tools:

ToolDescription
init_projectScaffold a new production-ready backend project with chosen ORM, preset, and plugins
add_pluginInstall a plugin (jwt, clerk, stripe, s3, ratelimit, ci-github, dependabot, codeql, docker-registry, release)
remove_pluginRemove a previously installed plugin
generate_resourceGenerate a CRUD resource with fields, relations, validation, and Swagger
generate_seedGenerate a database seed file for a resource
generate_factoryGenerate a test factory for a resource
doctorValidate an existing BackGen project for configuration issues
list_pluginsList all available plugins with descriptions
list_presetsList all available domain presets
project_infoShow project metadata from the manifest

Then just ask: "Scaffold a SaaS backend with Prisma, JWT auth, and Stripe payments"


[BackGen CLI generating Express.js backend with Prisma, Drizzle, and Mongoose — Swagger docs, Docker, auth, and multi-tenant SaaS preset] > Generate production-ready backend foundations so developers can focus on business logic, not boilerplate.

BackGen is a CLI tool that generates complete Express.js backend projects on Prisma, Drizzle, or Mongoose — with authentication, multi-tenant infrastructure, production hardening, Docker, and testing — all working out of the box.

bash
npx @ibrahimkhaled19/backgen init my-api --orm drizzlecd my-apinpm run dev

Swagger docs at http://localhost:3000/docs in under 60 seconds. Pick your ORM, keep everything else.


Features

  • Express + TypeScript — strict mode, ESLint 9 (flat config), Vitest
  • Multi-ORM — Prisma, Drizzle, or Mongoose. Pick at init time, switch later via the manifest
  • SaaS-ready — saas-core preset ships Organizations, Memberships, Invitations, RBAC, tenant-scoped queries
  • Hardened by default — helmet, strict CORS, request ID, request timeout, xss + mongo-sanitize, graceful shutdown, /health + /ready, error envelope
  • Plugin System — JWT, Clerk, Stripe, S3, ratelimit via backgen add
  • Resource Generator — CRUD modules with relations, validation, Swagger
  • Domain Presets — saas-core, healthcare, SaaS, ecommerce, CRM, LMS — full domain in one command
  • Seed & Factory Generators — development data and test factories
  • Docker — multi-stage Dockerfile + docker-compose
  • Swagger/OpenAPI — auto-generated API documentation
  • Manifest — .backgenrc.json tracks ORM, plugins, versions, and ownership for upgrade/rollback

Quick Start

bash
# Install globallynpm install -g @ibrahimkhaled19/backgen
# Create a project (pick your ORM)backgen init my-api --orm prismabackgen init my-api --orm drizzlebackgen init my-api --orm mongoose
# Create a full multi-tenant domainbackgen init my-saas --preset saas-core --defaults
# Add authenticationbackgen add jwtbackgen add clerk
# Add production hardeningbackgen add ratelimit
# Generate a resourcebackgen generate resource Product name:string price:number stock:number
# Start developingcd my-apinpm run dev

Commands

backgen init [name]

Generate a new backend project.

bash
backgen init my-api                              # interactive ORM pickerbackgen init my-api --orm prisma                 # explicit ORMbackgen init my-api --orm drizzle --defaults     # Drizzle, non-interactivebackgen init my-api --orm mongoose --skip-installbackgen init my-api --preset saas-core --defaults   # full multi-tenant domainbackgen init my-api --preset healthcare            # healthcare domain

Output:

  • Express app with TypeScript strict mode
  • ORM-specific data layer (Prisma / Drizzle / Mongoose)
  • Environment validation (Zod)
  • Swagger/OpenAPI documentation
  • Docker + docker-compose
  • Hardened by default: helmet, CORS, request ID, timeout, xss + mongo-sanitize, graceful shutdown, health checks
  • ESLint 9 + Vitest
  • .backgenrc.json manifest (records project.orm + plugins)

No auth by default — choose your auth provider with backgen add.


backgen add [plugin]

Install a plugin. Interactive multi-select if no argument.

bash
backgen add                 # interactive multi-selectbackgen add jwt             # JWT authenticationbackgen add clerk           # Clerk auth-as-a-servicebackgen add stripe          # Stripe paymentsbackgen add s3              # AWS S3 storagebackgen add ratelimit       # Per-IP / per-user rate limitingbackgen add devops          # Install all devops plugins at once

Available Plugins:

PluginCategoryDescription
jwtauthJWT authentication with refresh tokens
clerkauthClerk auth-as-a-service (conflicts with jwt)
stripepaymentStripe checkout, webhooks, customers
s3storageAWS S3 upload, download, presigned URLs
ratelimitproductionPer-IP rate limiting with Redis-ready store
ci-githubdevopsGitHub Actions CI pipeline (lint, typecheck, test, build, optional deploy)
dependabotdevopsAutomated dependency updates via Dependabot
codeqldevopsCodeQL security analysis on push and schedule
docker-registrydevopsDocker image build and publish to GHCR
releasedevopsSemantic release with npm publish and GitHub releases

Conflict detection: jwt and clerk cannot be installed together.


Domain Presets

Generate a complete domain in one command. Each preset creates multiple resources with relations, auto-installs JWT auth, and wires everything together.

bash
backgen init my-api --preset healthcarebackgen init my-api --preset saas --defaults

healthcare

Patient, Doctor, Appointment, Prescription, MedicalRecord — appointments between patients and doctors, prescriptions linked to patients, medical records per patient.

saas

Organization, Team, Membership, Subscription, Invoice — organizations with teams and memberships, subscriptions with invoices.

ecommerce

Category, Product, Cart, Order, OrderItem, Payment — products in categories, carts with items, orders with line items and payments.

crm

Contact, Company, Deal, Activity — companies with contacts, deals tracked through pipeline, activity logging.

lms

Course, Lesson, Enrollment, Progress, Certificate — courses with lessons, student enrollments, progress tracking, certificates.


backgen remove [plugin]

Remove a plugin. Interactive multi-select if no argument. Supports devops shorthand to remove all devops plugins.

bash
backgen remove              # interactive multi-selectbackgen remove stripe       # remove specific pluginbackgen remove devops       # remove all devops plugins

backgen generate resource <name> [fields...]

Generate a CRUD resource module.

bash
# Interactivebackgen generate resource Product
# Non-interactivebackgen generate resource Product name:string price:number stock:number
# With relationsbackgen generate resource Appointment date:datetime status:string \  --relations "doctor:Doctor,patient:Patient"
# With --fields flagbackgen generate resource Product --fields "name:string,price:number"

Generated files:

src/modules/product/  product.controller.ts    # CRUD endpoints  product.service.ts       # business logic  product.repository.ts    # database operations  product.validation.ts    # Zod schemas  product.types.ts         # TypeScript interfaces  product.routes.ts        # route definitions + Swagger  product.test.ts          # test placeholder

Field types: string, number, boolean, date, datetime

Relations: doctor:Doctor (belongsTo), patients:Patient (hasMany)


backgen generate seed <resource>

Generate seed data for development.

bash
backgen generate seed Product --count 10

Output: prisma/seeds/product.ts (Prisma), db/seeds/product.ts (Drizzle), or seeds/product.ts (Mongoose)


backgen generate factory <resource>

Generate a test factory.

bash
backgen generate factory Product

Output: src/factories/product.factory.ts

Usage:

ts
import { createProduct } from "./factories/product.factory.js";const product = await createProduct({ name: "Widget" });

backgen generate route [name]

Generate a custom route module with a complete controller, service, validation, types, and route file -- including Swagger annotations. Routes are automatically registered in app.ts with the REGISTER_ROUTES marker.

Use this when you need a custom endpoint that doesn't fit the CRUD pattern (e.g., dashboards, reports, webhooks, custom actions). For standard CRUD, use generate resource instead.

bash
backgen generate route                  # interactive promptbackgen generate route reports          # generate a /api/reports modulebackgen generate route webhooks         # generate a /api/webhooks module

Generated files:

src/modules/reports/  reports.controller.ts    # request handlers  reports.service.ts       # business logic  reports.validation.ts    # Zod schemas  reports.types.ts         # TypeScript interfaces  reports.routes.ts        # route definitions + Swagger

Key differences from generate resource:

  • No database model, repository, or test file
  • No field specification required
  • Pure controller/service pattern for custom endpoints
  • Mounted at /api/<name> with full Swagger docs

backgen generate migration [name]

Generate a database migration (ORM-aware).

bash
backgen generate migration add-product-table   # runs prisma migrate dev / drizzle-kit generate / no-op for Mongoose

backgen sync

Reconcile .backgenrc.json with the project. Regenerates missing plugin files.

bash
backgen sync

backgen mcp

Start BackGen as an MCP server over stdio. Used by AI assistants (Claude, Cursor, VS Code) to scaffold projects programmatically.

bash
backgen mcp

This is the same server exposed via the npx @ibrahimkhaled19/backgen backgen-mcp binary. It registers all 10 MCP tools listed in the AI-Ready section.


backgen health

Show system health information.

bash
backgen health

Displays:

  • Node.js version
  • Platform and architecture
  • BackGen version

backgen doctor

Check project health with ownership integrity diagnostics.

bash
backgen doctor              # health check + ownership auditbackgen doctor --fix        # auto-fix missing manifest entries

Checks:

  • Node.js version (>= 18)
  • npm availability
  • .env file
  • DATABASE_URL
  • Prisma schema / Drizzle config / Mongoose connection
  • Dependencies
  • Package manager version
  • File integrity — all manifest-tracked files exist on disk
  • Ownership integrity — framework vs user file classification

backgen upgrade

Upgrade a generated project to the latest template version. Creates a backup, then applies pending migrations sequentially.

bash
backgen upgrade              # show pending migrations, prompt before applyingbackgen upgrade --yes        # skip confirmation, apply all pending

What happens:

  • Reads current generatedVersion from .backgenrc.json
  • Loads pending core + plugin migrations
  • Creates backup in .backgen/backups/pre-<version>/
  • Applies migrations in order (semver-sorted)
  • Updates ownership register + generatedVersion in manifest

backgen rollback

Restore a project to its pre-upgrade state from the most recent backup.

bash
backgen rollback              # show latest backup, prompt before restoringbackgen rollback --yes        # skip confirmation

What happens:

  • Lists available backups in .backgen/backups/
  • Restores the most recent backup (all tracked files + manifest)
  • Project returns to exact pre-upgrade state

backgen rotate-secrets

Rotate JWT secrets in the project's .env file. Generates cryptographically secure 256-bit random hex values for JWT_SECRET and JWT_REFRESH_SECRET, backs up the current .env to .env.backup, and writes new values.

All existing tokens are immediately invalidated on next server restart -- users must re-login.

bash
backgen rotate-secrets

What happens:

  • Generates two 256-bit random hex secrets via crypto.randomBytes
  • Old .env saved to .env.backup
  • Previous values preserved as comments in the new .env
  • Print summary of changes

Plugin System

Every plugin implements the BackGenPlugin interface:

ts
interface BackGenPlugin {  name: string;  category: string;  description: string;  version: string;
  dependencies?: string[];  devDependencies?: string[];  requires?: string[];  conflicts?: string[];
  env?: Record<string, string>;  templates: string[];  migrations?: PluginMigration[];   // versioned plugin migration scripts
  install(ctx: InstallContext): Promise<void>;  uninstall?(ctx: InstallContext): Promise<void>;}

Plugins can:

  • Install npm dependencies
  • Inject environment variables
  • Register routes in app.ts
  • Replace existing middleware
  • Add database models (Prisma / Drizzle / Mongoose)
  • Carry versioned migrations for own upgrades

Project Manifest

.backgenrc.json tracks plugins, versions, generated version, and file ownership:

json
{  "version": "1.0.0",  "generatedVersion": "1.9.0",  "project": {    "name": "my-api",    "framework": "express",    "database": "postgresql",    "orm": "prisma",    "preset": "saas-core"  },  "plugins": {    "jwt": {      "version": "1.0.0",      "installedAt": "2026-06-01",      "source": "core"    }  },  "files": {    "src/app.ts": { "owner": "shared", "version": "1.9.0" },    "src/server.ts": { "owner": "framework", "version": "1.9.0" },    "src/config/env.ts": { "owner": "framework-editable", "version": "1.9.0" },    "prisma/schema.prisma": { "owner": "user" },    "src/modules/user/user.service.ts": { "owner": "user" },    "docker-compose.yml": { "owner": "shared", "version": "1.9.0" }  }}

Ownership levels:

LevelDescriptionUpgrade behavior
frameworkBackGen owns fullySafe to overwrite
framework-editableGenerated but user may customizeSmart merge via migration
sharedGenerated skeleton, user extends (e.g. docker-compose)Migration-aware update
userUser owns entirelyNever touched

Generated Project Structure

my-api/├── prisma/                       # Prisma ORM only│   ├── schema.prisma│   └── seeds/├── src/db/                       # Drizzle ORM only│   ├── schema/│   │   └── index.ts│   └── seeds/├── src/models/                   # Mongoose ORM only│   └── seeds/├── src/│   ├── app.ts                    # Express app setup│   ├── server.ts                 # Server entry point│   ├── config/│   │   ├── env.ts                # Zod env validation│   │   ├── database.ts           # Prisma client / Drizzle db / Mongoose connection│   │   └── swagger.ts            # Swagger config│   ├── middleware/│   │   ├── auth.ts               # JWT/Clerk auth│   │   ├── validate.ts           # Zod validation│   │   ├── error.ts              # Global error handler│   │   └── logger.ts             # Request logging│   ├── modules/│   │   ├── auth/                 # Auth module (if jwt installed)│   │   ├── stripe/               # Stripe module (if installed)│   │   └── <resource>/           # Generated resources│   ├── services/│   │   └── logger.service.ts     # Winston logger│   ├── utils/│   │   ├── api-error.ts          # Error class│   │   ├── async-handler.ts      # Async wrapper│   │   └── response.ts           # Response formatters│   └── factories/                # Test factories├── .env.example├── .backgenrc.json               # Manifest├── Dockerfile├── docker-compose.yml├── package.json└── tsconfig.json

Development

bash
# Clonegit clone https://github.com/your-username/backgen.gitcd backgen
# Installnpm install
# Buildnpm run build
# Testnpm run test
# Lintnpm run lint

Test Suite

277+ tests covering:

  • CLI help and version
  • Init: project structure, configs, manifest (all 3 ORMs)
  • Init with domain presets: preset-specific resources and relations
  • Init with saas-core preset: multi-tenant organizations, memberships, RBAC
  • Add plugin: files, routes, env vars, manifest (V4.6 plugin suite)
  • Generate resource: module files, ORM model, routes, validation
  • Generate with relations: foreign keys, ORM includes
  • Seed and factory generators (all 3 ORMs)
  • Drizzle: schema generation, client setup, codegen
  • Mongoose: model generation, schema definition, connection
  • Remove plugin: file + dependency + manifest cleanup
  • Sync: file restoration
  • Doctor: health checks, ownership integrity
  • Upgrade: migration engine, pending detection, backup creation
  • Rollback: backup listing, file restoration, manifest recovery
  • Error handling: unknown plugin, non-empty directory

Tech Stack

LayerTechnology
CLICommander.js
PromptsInquirer.js
TemplatesHandlebars
SpinnerOra
ColorsChalk
TestingVitest
LintingESLint 9 (flat config)
LanguageTypeScript (strict)

Generated Projects

LayerTechnology
FrameworkExpress.js
LanguageTypeScript (strict)
DatabasePostgreSQL
ORMPrisma / Drizzle / Mongoose
ValidationZod
AuthJWT or Clerk
PaymentsStripe
StorageAWS S3
DocsSwagger/OpenAPI
LoggingWinston + Morgan
TestingVitest
DeploymentDocker

BackGen vs Alternatives

ToolORM ChoiceAuthPlugin SystemPresetsUpgrade EngineDocs Site
BackGenPrisma, Drizzle, MongooseJWT, Clerk◈ 7+ plugins5 domains◈ Backup + rollback—
NestJS CLINo (fixed NestJS)Built-in◈ Modules——◈
Express GeneratorNo (fixed plain JS)—————
T3 StackPrismaNextAuth———◈
AdonisJSLucid ORMBuilt-in◈ Ace——◈
LoopBackBuilt-inBuilt-in◈——◈

Key differentiators:

  • ◈ ORM-switchable — change Prisma ↔ Drizzle ↔ Mongoose via manifest, not rewrite
  • ◈ Domain presets — healthcare, SaaS, ecommerce, CRM, LMS in one command
  • ◈ Upgrade engine — versioned migrations + backup + rollback for generated projects
  • ◈ Multi-ORM from day one — not locked into one data layer

Roadmap

VersionFocusStatus
V1FoundationDone
V2Plugin SystemDone
V3Resource GeneratorDone
V4Domain PresetsDone
V4.5SaaS EssentialsDone
V4.6Production HardeningDone
V4.6.1Base Hardening Default-OnDone
V5Multi-ORM (Prisma, Drizzle, Mongoose)Done
V6DevOps & InfrastructureDone
V6.1Ownership Tracking & Doctor --fixDone
V6.2Upgrade Engine & Migration RunnerDone
V6.3Backups & RollbackDone
V6.4Plugin MigrationsDone
V7Upgrade Polish & DiffingIn Progress
V8Schema-First DevelopmentPlanned
V9Enterprise FeaturesPlanned
V10Plugin Authoring SDKPlanned
V11MarketplacePlanned
V12AI Context LayerPlanned

See docs/ROADMAP.md for details.


License

MIT

来源:README.md,提交 51227a8

工具

0
SourceWeft 尚未在沙箱中启动过该软件包,因此其工具未知。

版本历史

1
  1. v1.14.0最新Sep 16, 2026

评分

已满足适用检查项的 50%

该评分衡量此收录条目的完整程度,依据注册中心条目、端点与公开来源计算得出。它不是对服务器本身的评价,也不表示服务器安全或当前可用:可连通性是带日期的检查结果,评分也不包含安装量或用户评价。

  • 近 30 天内可连通25 分

    请保持端点能够响应 MCP 握手;SourceWeft 每 30 天探测一次。

  • 已声明认证方式10 分

    请在注册中心条目中声明凭据请求头,或保持端点能够响应探测,以便判定其认证方式。

  • 已列出工具15 分

    请让服务器在无凭据时响应 tools/list,或发布可在沙箱中无凭据启动的软件包。

  • 描述必需15 分
  • 图标10 分
  • 文档15 分
  • 许可证10 分