Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
T

trpc-cli

> 开发工具
Open source

Turn a tRPC router into a type-safe, fully-functional, documented CLI

370 stars0 likes0 views
WebsiteGitHub

About

Turn a tRPC router into a type-safe, fully-functional, documented CLI

trpc-cli

Build production-quality command-line tools in minutes, not days

trpc-cli transforms a tRPC (or oRPC) router into a professional-grade CLI with zero boilerplate. Get end-to-end type safety, input validation, auto-generated help documentation, and command completion for free.

  • ✅ Get all of trpc's type safety and DX building a CLI
  • ✅ Automatic positional arguments and options via zod input types (or arktype, or valibot)
  • ✅ Easily add subcommands via nested trpc routers
  • ✅ Rich helptext out of the box
  • ✅ Exactly one dependency: commander
  • ✅ Automatic input prompts
  • ✅ Automatic shell autocompletions
  • ✅ Use advanced tRPC features like context and middleware in your CLI
  • ✅ Build multimodal applications - use the same router for a CLI and an HTTP server, and more
  • ✅ oRPC support
  • ✅ Standalone mode (experimental) - build CLIs without @trpc/server or @orpc/server
  • ✅ No configuration required. Run a plain module of exported functions with npx trpc-cli ./commands.ts

Contents

  • Contents
  • Motivation
  • Installation
  • Quick Start
    • Basic Usage
  • Core Concepts
    • Input Types & CLI Arguments
    • Command Configuration
  • Validators
    • zod
    • arktype
    • valibot
    • effect
    • typebox
    • CLI from a plain TypeScript module — Experimental
  • Examples
    • Calculator Example
    • Migrator Example
  • Other Features
    • tRPC v10 vs v11
    • oRPC
    • Standalone Mode (No tRPC/oRPC Required) — Experimental
    • Output and Lifecycle
    • How the CLI name is resolved
    • Testing your CLI
    • CLI Context
    • Programmatic Usage
    • Input Prompts
    • Completions
    • .toJSON()
    • deepHelp(program)
    • Running a file directly
  • Reference
    • API docs
    • Features and Limitations
    • Out of scope
  • Disclaimer
  • Contributing
    • Implementation and dependencies
    • Testing

Motivation

tRPC offers best-in-class type-safety and DX for building "procedures" that validate their inputs, and abide by their own contracts. This library gives you all those DX benefits, and allows mapping the procedures directly to a CLI. This offers the easiest way to build a CLI while mapping parsed options into strongly-typed inputs, and automatically outputs --help documentation that's always up-to-date.

This isn't just the easiest and safest way to build a CLI, but you also get all the benefits of tRPC (and zod). For inputs, you can use zod regex types, transforms, refinements, and those will map directly into useful help-text for CLI users, and corresponding type correctness when maintaining your CLI program. You can also use tRPC context and middleware functionality just like you could if you were building a server. And as an added bonus, it becomes trivially easy to turn your CLI program into a fully-functional HTTP server. Or, you could add a "programmatic usage" to your library, just by wrapping your server with the built-in createCaller function from tRPC. This would all, of course, have runtime and compile-time type safety.

Installation

bash
npm install trpc-cli @trpc/server zod

Quick Start

Basic Usage

The fastest way to get going is to write a normal tRPC router and turn it into a fully-functional CLI by passing it to createCli:

typescript
import {initTRPC} from '@trpc/server'
import {createCli} from 'trpc-cli'
import {z} from 'zod'

const t = initTRPC.create()

const router = t.router({
  add: t.procedure
    .input(z.object({left: z.number(), right: z.number()}))
    .query(({input}) => input.left + input.right),
})

createCli({router}).run()

And that's it! Your tRPC router is now a CLI program with help text and input validation. You can run it with node yourscript add --left 2 --right 3.

Docs here if you're not familiar with tRPC.

Core Concepts

Input Types & CLI Arguments

CLI positional arguments and options are derived from each procedure's input type. Inputs use validator types (zod, arktype, valibot, etc.) to be mapped to CLI commands.

Positional Arguments

Positional arguments passed to the CLI can be declared with types representing strings, numbers or booleans:

typescript
t.router({
  double: t.procedure
    .input(z.number()) //
    .query(({input}) => input * 2),
})

You can also use anything that accepts string, number, or boolean inputs, like z.enum(['up', 'down']), z.number().int(), z.literal(123), z.string().regex(/^\w+$/) etc.

Multiple positional arguments can use a z.tuple(...) input type:

typescript
t.router({
  add: t.procedure
    .input(z.tuple([z.number(), z.number()]))
    .query(({input}) => input[0] + input[1]),
})

Which is invoked like path/to/cli add 2 3 (outputting 5).

Note: positional arguments can use .optional() or .nullish(), but not .nullable().

Note: positional arguments can be named using .describe('name of parameter'), but names should not include any special characters.

Note: positional arguments are parsed based on the expected target type. Booleans must be written as true or false, spelled out. In most cases, though, you'd be better off using options for boolean inputs.

Array/spread parameters can use an array input type:

typescript
t.router({
  lint: t.procedure
    .input(z.array(z.string()).describe('file paths to lint'))
    .mutation(({input}) => {
      lintFiles(input.map(file => path.join(process.cwd(), file)))
    }),
})

Which is invoked like path/to/mycli lint file1 file2 file3 file4.

Array inputs can also be used with options by nesting them in a tuple.

typescript
t.router({
  lint: t.procedure
    .input(
      z.tuple([
        z.array(z.string()).describe('file paths to lint'),
        z.object({maxWarnings: z.number().default(10)}),
      ]),
    )
    .mutation(({input}) => {
      const result = lintFiles(
        input.files.map(file => path.join(process.cwd(), file)),
      )
      if (result.warnings.length > input.maxWarnings) {
        throw new Error(`Too many warnings: ${result.warnings.length}`)
      }
    }),
})

Which could be invoked with any of:

  • mycli lint file1 file2 file3 file4 --max-warnings 10
  • mycli lint file1 file2 file3 file4 --maxWarnings=10
  • mycli lint --maxWarnings=10 file1 file2 file3 file4
  • mycli lint --maxWarnings 10 file1 file2 file3 file4

Options

z.object(...) inputs become options (passed with --foo bar or --foo=bar) syntax. Values are accepted in --kebab-case, and are parsed like in most CLI programs:

Strings:

  • z.object({foo: z.string()}) will map:
    • --foo bar or --foo=bar to {foo: 'bar'}

Booleans:

  • z.object({foo: z.boolean()}) or z.object({foo: z.boolean().default(false)}) will map:

    • no option supplied to {foo: false}
    • --foo {foo: true}
  • z.object({foo: z.boolean().default(true)}) will map:

    • no option supplied to {foo: true}
    • --foo false or --foo=false to {foo: false}
  • z.object({foo: z.boolean().optional()}) will map:

    • no option supplied to {} (foo is undefined)
    • --foo to {foo: true}
    • --foo false to {foo: false}

Negated options can be useful for default-true booleans:

  • z.object({foo: z.boolean().default(true).meta({negatable: true})}) will map:
    • no option supplied to {foo: true}
    • --no-foo to {foo: false}
    • --foo false to {foo: false}

(Note: you can set booleans to negatable-by-default by setting negateBooleans: true on the procedure's meta)

Numbers:

  • z.object({foo: z.number()}) will map:
    • --foo 1 or --foo=1 to {foo: 1}

Other types:

  • z.object({ foo: z.object({ bar: z.number() }) }) will parse inputs as JSON:
    • --foo '{"bar": 1}' maps to {foo: {bar: 1}}

Multi-word options:

  • z.object({ multiWord: z.string() }) will map:
    • --multi-word foo to {multiWord: 'foo'}

Unions and intersections should also work as expected, but make sure to test them thoroughly, especially if they are deeply-nested.

Option aliases

If you're using zod v4, or any other standard-schema library that has a similar meta functionality, you can set aliases for options with it:

typescript
const router = t.router({
  deleteAll: t.procedure
    .input(
      z.object({
        force: z.boolean().meta({alias: 'f'}),
      }),
    )
    .mutation(async () => ___),
})

If you are on an old version of zod, or another library, set aliases at the procedure level:

typescript
const router = t.router({
  deleteAll: t.procedure
    .meta({aliases: {options: {force: 'f'}}})
    .input(
      z.object({
        force: z.boolean(),
      }),
    )
    .mutation(async () => ___),
})

Combining Positional Arguments and Options

To use positional arguments and options, there are two approaches:

1) Using input schema metadata (recommended)

Use z.string().meta({positional: true}). This is available on zod v4, and arktype via type('string').configure({positional: true}):

typescript
t.router({
  copy: t.procedure
    .input(
      z.object({
        source: z.string().meta({positional: true}),
        target: z.string().meta({positional: true}),
        mkdirp: z
          .boolean()
          .optional()
          .describe("Ensure target's parent directory exists before copying"),
      }),
    )
    .mutation(async ({input: [source, target, opts]}) => {
      if (opts.mkdirp) {
        await fs.mkdir(path.dirname(target, {recursive: true}))
      }
      await fs.copyFile(source, target)
    }),
})

2) Using a tuple with an object at the end

Use this if you're on an old version of zod, or using a library which doesn't support meta:

typescript
t.router({
  copy: t.procedure
    .input(
      z.tuple([
        z.string().describe('source'),
        z.string().describe('target'),
        z.object({
          mkdirp: z
            .boolean()
            .optional()
            .describe("Ensure target's parent directory exists before copying"),
        }),
      ]),
    )
    .mutation(async ({input: [source, target, opts]}) => {
      if (opts.mkdirp) {
        await fs.mkdir(path.dirname(target, {recursive: true}))
      }
      await fs.copyFile(source, target)
    }),
})

You might use the above with a command like:

path/to/cli copy a.txt b.txt --mkdirp

Note: when using a tuple, object types for options must appear last in the .input(...) tuple, when being used with positional arguments. So z.tuple([z.string(), z.object({mkdirp: z.boolean()}), z.string()]) would not be allowed (inputs would have to be passed as JSON).

Command Configuration

You can change the behaviour of the command generated for a given procedure by using trpc's meta feature.

Basic Meta Properties

Use description, usage and examples to add corresponding help information to your CLI:

typescript
const router = t.router({
  install: t.procedure
    .meta({
      description: 'Installs dependencies',
      // usage: 'mycli install',

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

TypeScriptclitprctypescript

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具