---
title: "Write your own csdx plugin"
url: "https://developers.contentstack.com/guides/write-your-own-csdx-plugin"
type: "guide"
level: "advanced"
intent: "build"
outcome: "You have a working, tested csdx plugin with a stack:health command, linked locally and ready to publish to npm."
prerequisites:
  - "Node.js 22 or later"
  - "The Contentstack CLI 2.x installed globally, with a region set and csdx auth:login done"
  - "Working knowledge of TypeScript and npm packages"
  - "A stack you can read, ideally a test stack"
tags:
  - "cli"
  - "automation"
  - "sdk"
authors:
  - "Tim Benniks"
published: "2026-12-02T09:00:00.000Z"
updated: "2026-11-15T10:56:32.926Z"
---

# Write your own csdx plugin

- **Authors:** Tim Benniks
- **Published:** 2026-12-02T09:00:00.000Z
- **Updated:** 2026-11-15T10:56:32.926Z
- **Level:** Advanced
- **Intent:** Build
- **Tags:** cli, automation, sdk

---

Every csdx command is an oclif plugin, including the official ones. That means you can package any script you keep running against Contentstack as a real command, with flags, help text, the user's existing login and region, and a one-line install. If you want the background on how the CLI loads plugins, read [Every csdx command is a plugin](/blog/every-csdx-command-is-a-plugin) first.

In this guide you build csdx stack:health. It reads every content type on a branch and prints a table with entry counts, unpublished entries, entries nobody touched in a year, and entries that are missing a value in a required field. It only reads, so you can run it against any stack.

## What you'll learn

- How a csdx plugin is structured and where the CLI looks for commands


- How to extend the Contentstack base Command class


- How to get an authenticated Management API client from the CLI session or a token alias


- How to print a table that supports sorting, filtering and CSV


- How to link, test and publish the plugin



## How the pieces fit together

A plugin is an npm package. Its package.json has an oclif section that points at a folder of compiled commands. The file path decides the command ID, so lib/commands/stack/health.js becomes csdx stack:health.

flowchart LR  CLI["csdx (oclif core)"] --> P["your plugin<br/>oclif.commands = ./lib/commands"]  P --> C["stack/health.js<br/>extends Command"]  C --> U["@contentstack/cli-utilities<br/>managementSDKClient, flags, cliux"]  U --> CMA["Content Management API<br/>this.cmaHost"]Two packages do the heavy lifting:

- @contentstack/cli-command exports the base Command. It extends the oclif command with this.region, this.cmaHost, this.cdaHost, this.email and this.getToken(alias).


- @contentstack/cli-utilities re-exports oclif's flags and Args, and adds managementSDKClient, cliux, CLITable, isAuthenticated and the Management SDK types.



Import from these two packages, not from @oclif/core directly. That keeps your plugin on the same oclif version as the CLI.

## Scaffold the plugin

Use the oclif generator, as the Contentstack docs recommend:

```bash
npx oclif generate csdx-plugin-stack-health
cd csdx-plugin-stack-health
npm install @contentstack/cli-command@~2.0.2 @contentstack/cli-utilities@~2.0.2
```

The generator asks for a module type, package name, binary name and a few more details. This guide uses CommonJS, which matches how the official plugins compile.

Then open package.json and set the oclif section. bin must be csdx so help output shows the right command, and commands must point at the compiled output, not at src:

```json
{
  "oclif": {
    "bin": "csdx",
    "commands": "./lib/commands",
    "topicSeparator": ":",
    "topics": {
      "stack": { "description": "Inspect a stack" }
    }
  },
  "files": ["/lib", "/oclif.manifest.json"],
  "scripts": {
    "build": "tsc -b",
    "prepack": "tsc -b && oclif manifest",
    "postpack": "rm -f oclif.manifest.json",
    "test": "mocha --require ts-node/register \"test/**/*.test.ts\""
  }
}
```

Make sure outDir in tsconfig.json matches. This is the config used for this guide:

```json
{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es2022",
    "rootDir": "src",
    "outDir": "lib",
    "strict": true,
    "esModuleInterop": true,
    "skipLibCheck": true
  },
  "include": ["src"]
}
```

Delete the example hello command the generator created. You do not want it to show up in csdx --help.

## Keep the report logic separate

Put the checks in a plain function with no CLI or network code. That makes it trivial to test.

```typescript
// src/health.ts
export type FieldSchema = { uid: string; mandatory?: boolean }

export type EntryLike = {
  updated_at?: string
  publish_details?: unknown[]
  [field: string]: unknown
}

export type HealthRow = {
  content_type: string
  entries: number
  unpublished: number
  stale: number
  missing_required: number
}

const isEmpty = (value: unknown) =>
  value === undefined || value === null || value === '' || (Array.isArray(value) && value.length === 0)

export function summarize(
  contentTypeUid: string,
  schema: FieldSchema[],
  entries: EntryLike[],
  staleBefore: Date,
): HealthRow {
  const required = schema.filter((field) => field.mandatory).map((field) => field.uid)

  return {
    content_type: contentTypeUid,
    entries: entries.length,
    unpublished: entries.filter((entry) => !entry.publish_details?.length).length,
    stale: entries.filter((entry) => entry.updated_at && new Date(entry.updated_at) < staleBefore).length,
    missing_required: entries.filter((entry) => required.some((uid) => isEmpty(entry[uid]))).length,
  }
}
```

The "missing required" check finds a real problem. Contentstack enforces required fields when an entry is saved, so a gap usually means someone made a field required after entries already existed. Those entries fail validation the next time an editor opens and saves them.

## Write the command

Create src/commands/stack/health.ts. This is the whole command:

```typescript
import { Command } from '@contentstack/cli-command'
import {
  CLITable,
  ContentstackClient,
  ManagementStack,
  TableFlags,
  cliux,
  flags,
  isAuthenticated,
  managementSDKClient,
} from '@contentstack/cli-utilities'
import { EntryLike, FieldSchema, HealthRow, summarize } from '../../health'

const PAGE_SIZE = 100

export default class StackHealth extends Command {
  static description = 'Report entry counts, unpublished, stale and incomplete entries per content type (read-only)'

  static examples = [
    '$ csdx stack:health -k blt0123456789abcdef',
    '$ csdx stack:health -a my-token --branch development --stale-days 180',
    '$ csdx stack:health -a my-token --sort=-stale --csv',
  ]

  static flags = {
    'stack-api-key': flags.string({ char: 'k', description: 'API key of the stack', exclusive: ['alias'] }),
    alias: flags.string({ char: 'a', description: 'Alias of a management token added with csdx auth:tokens:add' }),
    branch: flags.string({ description: 'Branch to inspect', default: 'main' }),
    'stale-days': flags.integer({ description: 'Days without an update before an entry counts as stale', default: 365 }),
    ...CLITable.getTableFlags(),
  }

  async run(): Promise<void> {
    const { flags } = await this.parse(StackHealth)
    const stack = await this.getStack(flags.alias, flags['stack-api-key'], flags.branch)
    const staleBefore = new Date(Date.now() - flags['stale-days'] * 24 * 60 * 60 * 1000)

    const contentTypes = await this.fetchAll((skip) =>
      stack.contentType().query({ include_count: true, limit: PAGE_SIZE, skip }).find(),
    )

    const rows: HealthRow[] = []
    for (const contentType of contentTypes) {
      const entries = await this.fetchAll<EntryLike>((skip) =>
        stack
          .contentType(contentType.uid)
          .entry()
          .query({ include_count: true, include_publish_details: true, limit: PAGE_SIZE, skip })
          .find(),
      )
      rows.push(summarize(contentType.uid, contentType.schema as FieldSchema[], entries, staleBefore))
    }

    cliux.table(
      [
        { value: 'content_type', alias: 'Content type' },
        { value: 'entries', alias: 'Entries' },
        { value: 'unpublished', alias: 'Unpublished' },
        { value: 'stale', alias: `Stale (${flags['stale-days']}d)` },
        { value: 'missing_required', alias: 'Missing required' },
      ],
      rows,
      flags as TableFlags,
    )

    const total = rows.reduce((sum, row) => sum + row.entries, 0)
    this.log(`\n${rows.length} content types, ${total} entries on branch "${flags.branch}".`)
  }

  private async getStack(alias: string | undefined, apiKey: string | undefined, branch: string): Promise<ManagementStack> {
    if (alias) {
      const token = this.getToken(alias)
      const client: ContentstackClient = await managementSDKClient({
        host: this.cmaHost,
        management_token: token.token,
      })
      return client.stack({ api_key: token.apiKey, management_token: token.token, branch_uid: branch })
    }

    if (!apiKey) this.error('Pass --stack-api-key or --alias.', { exit: 2 })
    if (!isAuthenticated()) this.error('You are not logged in. Run csdx auth:login first.', { exit: 2 })

    const client: ContentstackClient = await managementSDKClient({ host: this.cmaHost })
    return client.stack({ api_key: apiKey, branch_uid: branch })
  }

  private async fetchAll<T>(page: (skip: number) => Promise<{ items: T[]; count: number }>): Promise<T[]> {
    const items: T[] = []
    let count = Infinity
    while (items.length < count) {
      const result = await page(items.length)
      items.push(...result.items)
      count = result.count
      if (result.items.length === 0) break
    }
    return items
  }
}
```

A few things in this command are worth calling out:

- this.cmaHost comes from the region the user set with csdx config:set:region. Never hard-code api.contentstack.io, or your plugin breaks for every team outside the default region.


- managementSDKClient returns a configured @contentstack/management client. It applies the user's proxy settings and retries 429 responses, so you do not need your own rate limit handling for a report like this.


- CLITable.getTableFlags() adds --columns, --sort, --filter, --csv and --no-truncate, and cliux.table applies them. You get the same table behavior as cm:stacks:audit for free.


- The flags -k, -a and --branch follow the naming the official plugins use. People already know them, so keep them.



## Where people get confused about auth

The command supports two ways in, and they behave differently.

Session auth is what you get after csdx auth:login. When you call managementSDKClient without a management token, the client uses the session, including basic auth tokens and OAuth access tokens that it refreshes for you. The user's role decides what the command can read.

Token aliases come from csdx auth:tokens:add --management. this.getToken(alias) returns the saved token with its token and apiKey, so the user does not have to pass the stack API key separately. A management token is scoped to a stack and to the branches it was created for, which makes it the better fit for CI.

If the user passes a delivery token alias by mistake, the Management API rejects the requests. A friendly check on token.type is a good first improvement once the basics work.

## Link and run it locally

Build, generate the manifest, and link the folder into your global csdx:

```bash
npm run build
npx oclif manifest
csdx plugins:link .
csdx stack:health --help
csdx stack:health -k <stack-api-key> --branch main --sort=-unpublished
```

You see a table with one row per content type, followed by a summary line with the number of content types and entries. If csdx says the command does not exist, check that lib/commands/stack/health.js exists and that oclif.commands points at ./lib/commands.

Linking does not rebuild anything. After every change, run npm run build and npx oclif manifest again. A linked plugin also overrides any user-installed or core command with the same ID, which is another reason to keep your commands under their own topic.

When you are done, remove the link with csdx plugins:uninstall csdx-plugin-stack-health.

## Test without a stack

oclif's test package, @oclif/test version 4, exports runCommand, captureOutput and runHook. The older chained test.stdout().command() style is gone. Test the report logic directly and use runCommand for flag handling:

```typescript
// test/health.test.ts
import { expect } from 'chai'
import { runCommand } from '@oclif/test'
import { summarize } from '../src/health'

describe('summarize', () => {
  it('counts unpublished, stale and incomplete entries', () => {
    const row = summarize(
      'article',
      [{ uid: 'title', mandatory: true }, { uid: 'summary', mandatory: true }],
      [
        { title: 'Fresh', summary: 'ok', updated_at: '2026-06-01', publish_details: [{ environment: 'production' }] },
        { title: 'Old draft', summary: '', updated_at: '2025-03-01', publish_details: [] },
      ],
      new Date('2026-01-01'),
    )

    expect(row).to.deep.equal({ content_type: 'article', entries: 2, unpublished: 1, stale: 1, missing_required: 1 })
  })
})

describe('stack:health', () => {
  it('asks for a stack when no flags are passed', async () => {
    const { error } = await runCommand('stack:health')
    expect(error?.message).to.contain('Pass --stack-api-key or --alias')
  })
})
```

Install the test dependencies with npm install -D @oclif/test mocha chai@4 @types/mocha @types/chai ts-node and run npm test. Neither test calls the API: the second one fails on the missing flags before the command reads the region or creates a client.

## Publish and install

Publishing is a normal npm release. The prepack script compiles the code and writes oclif.manifest.json, which the CLI uses to find commands without loading every file:

```bash
npm publish
```

Anyone on CLI 2.x can then install it:

```bash
csdx plugins:install csdx-plugin-stack-health
csdx stack:health -a my-token
```

Updates go through csdx plugins:update, and csdx plugins shows the installed version.

## Limits to remember

- The report reads entries in the stack's master locale. Add a locale query parameter and a --locale flag if you need other locales.


- The required field check looks at top-level fields only. Required fields inside groups, global fields and modular blocks need a recursive walk of the schema.


- Every content type costs at least one request, plus one per 100 entries. On very large stacks, run it against a management token in CI rather than on every commit.


- Stale is based on updated_at, so an entry that was published but never edited still counts as stale.



## Key takeaways

- A csdx plugin is an npm package with an oclif section whose commands path points at compiled output.


- Extend Command from @contentstack/cli-command and import flags, cliux and managementSDKClient from @contentstack/cli-utilities.


- Use this.cmaHost and managementSDKClient({ host: this.cmaHost }) so your command respects the user's region, login and proxy.


- Support both -k with session auth and -a with a management token alias, the same way official plugins do.


- Rebuild and run npx oclif manifest before every csdx plugins:link test, and namespace your commands under their own topic.



## Next steps

- Read [Every csdx command is a plugin](/blog/every-csdx-command-is-a-plugin) for the list of bundled and opt-in plugins you can learn from.


- Pair the health report with [Safe content model changes with branches and aliases](/guides/safe-content-model-changes-with-branches-and-aliases) to check a branch before you merge it.


- Run the command in CI next to your deploys, as in [Deploy from CI with the Launch CLI and API](/guides/deploy-from-ci-with-the-launch-cli-and-api).





---

## Do this with AI

Install the dx-cli skill from [Contentstack agent skills](https://github.com/contentstack/contentstack-agent-skills). Then ask your agent:

> Scaffold a read-only csdx plugin command that counts entries per content type and lists unpublished ones, with a unit test, and no calls that write to the stack.

New to this? [Set up your AI workbench](/guides/set-up-your-ai-workbench-for-contentstack) first.




---

## Frequently asked questions

### Which base class should a csdx command extend?

Extend Command from @contentstack/cli-command. It adds the region hosts, the logged-in email and saved token lookups on top of the oclif command class.

### How does my plugin reuse the user's csdx login?

Call managementSDKClient from @contentstack/cli-utilities with host set to this.cmaHost. Without a management token it uses the session from csdx auth:login, including OAuth refresh.

### Why does csdx not see my new command after linking?

Linking does not compile anything. Run the TypeScript build and npx oclif manifest again, then check that oclif.commands in package.json points to the compiled folder.

### Can I name my command anything?

Yes, but put it under its own topic, like stack:health. A linked plugin overrides any core command with the same ID, so avoid reusing names such as cm:stacks:export.

