# CLI reference (/docs/reference/api/cli)

<div class="prose">

The `hypequery` CLI provides commands for scaffolding, generating types, and running development servers. Remote ClickHouse workflows use credentials collected during `init` or supplied through the `CLICKHOUSE_*` environment variables below. The `chdb` driver runs on [embedded ClickHouse](/docs/chdb) and needs no server credentials.

## Which command should I use? [#which-command-should-i-use]

Use the CLI commands for different jobs:

| Command | Use it when | What it does |
| --- | --- | --- |
| `hypequery generate` | You already have a project and need fresh schema types | Connects to ClickHouse and regenerates your TypeScript schema file |
| `hypequery init` | You want the CLI to scaffold an `analytics/` folder for you | Writes starter files like `client.ts`, `schema.ts`, and `queries.ts` |
| `hypequery dev` | You already have queries and want a local runtime server | Runs the local `@hypequery/serve` dev server with docs and hot reload |

The most common confusion is between `init` and `generate`:

- `init` scaffolds a project structure
- `generate` refreshes schema types from your current ClickHouse database

If you have already created your analytics folder and only need updated types, run `hypequery generate`.

## Installation [#installation]

**No installation required!** Run commands directly with `npx`:

<CodeBlock>
```bash
npx @hypequery/cli init
npx @hypequery/cli dev
```
</CodeBlock>

For frequent use, install as a dev dependency:

<CodeBlock>
```bash
npm install -D @hypequery/cli
# or
pnpm add -D @hypequery/cli
```
</CodeBlock>

Then use the shorter `hypequery` command:

<CodeBlock>
```bash
npx hypequery init
npx hypequery dev
```
</CodeBlock>

### TypeScript support [#typescript-support]

`hypequery dev` can load `.ts` and `.tsx` query files directly. The CLI bundles your entry file in-process before importing it, so no separate TypeScript runtime is required. If you already compile to JavaScript, you can still target the generated `.js` file instead.

## Commands at a glance [#commands-at-a-glance]

| Command | Purpose |
| --- | --- |
| `hypequery init` | Scaffold the `analytics/` folder, configure the selected database driver, and optionally create an example query or dataset |
| `hypequery dev [file]` | Run the local dev server backed by `@hypequery/serve` with hot reload |
| `hypequery generate` | Rebuild `analytics/schema.ts` from your current ClickHouse schema |
| `hypequery generate:types` | Alias for `hypequery generate` |
| `hypequery generate:datasets` | Generate dataset (semantic layer) definitions from your ClickHouse schema |
| `hypequery generate:manifest <api>` | Write the route manifest React hooks use to call a TypeScript API |
| `hypequery generate:client [contract]` | Generate typed React client types and routes from a TypeScript serve or Python client contract, or the live cloud release |
| `hypequery export:client-contract <api>` | Export a TypeScript serve API's client contract for `hypequery generate:client` |
| `hypequery login [--device]` | Sign in to hypequery Cloud in a browser, or with `--device` by approving a code from any browser |
| `hypequery deploy <cloud>` | Build, release, and deploy a dataset-only Cloud publication, then print where it is served (hypequery cloud is not live yet) |
| `hypequery mcp [file]` | Serve this project's datasets to an MCP client over stdio or Streamable HTTP (`--http`), or check an endpoint with `--self-test` |
| `hypequery skill install` | Install hypequery's agent skills for Claude Code, Cursor and Codex |
| `hypequery examples list` | List the runnable examples, recipes and guides at hypequery.com/examples |
| `hypequery create <slug>` | Scaffold an example or recipe into `./<slug>`, pinned to published versions |
| `hypequery deployment:validate <artifact>` | Verify a deployment bundle or validate contract JSON and report its identity |
| `hypequery <group> <action>` | Run any hypequery Cloud operation (`releases rollback`, `members invite`, `api-keys create`, …); see [Cloud operation commands](/docs/cloud/cli-operations) |
| `hypequery help [command]` | Show help for the CLI or a specific command |
| `hypequery telemetry [status\|enable\|disable]` | Inspect or change anonymous usage telemetry preferences |

The sections below expand on the supported options and expected behavior for each command.

## `hypequery telemetry` [#hypequery-telemetry]

The CLI sends pseudonymous usage events to `https://hypequery.com/api/telemetry`
unless telemetry is disabled. `HYPEQUERY_TELEMETRY_DEBUG=1` prints validated events
to stderr instead of sending; `HYPEQUERY_TELEMETRY_URL` sends to a staging or
self-hosted first-party ingest endpoint instead. Opt-outs apply in every mode. See the
[telemetry reference](/docs/telemetry) for the event contract and delivery limits.

```bash
hypequery telemetry          # Same as telemetry status
hypequery telemetry disable # Save an opt-out
hypequery telemetry enable  # Save an opt-in
hypequery init --no-telemetry # Disable for one invocation
```

Status reports the effective setting, the source that determined it, and the random
install ID. `enable` changes the saved preference; environment variables and the
global flag still take precedence.

The first matching setting wins: `--no-telemetry`, `DO_NOT_TRACK=1`,
`HYPEQUERY_TELEMETRY_DISABLED=1`, test environments (`VITEST` or `NODE_ENV=test`)
and hypequery's own GitHub Actions CI, then the saved preference. The default
preference is enabled, including in customer CI. Unavailable or corrupt settings
disable telemetry for that invocation. An explicit `enable` or `disable` can repair
corrupt settings; a failed save reports an error and the temporary opt-out options.

Settings live in `telemetry.json` beside the CLI's Cloud profile: macOS Application
Support, Windows APPDATA (or LOCALAPPDATA), or Linux XDG_CONFIG_HOME (otherwise
`~/.config/hypequery`). `HYPEQUERY_CONFIG_DIR` overrides the directory. These
variables are read only from the real environment, never from a `.env` file, and
must be absolute paths; a relative `HYPEQUERY_CONFIG_DIR` is an error.

## `hypequery init` [#hypequery-init]

<CodeBlock>
```bash
# Without installation
npx @hypequery/cli init [options]

# With installation
npx hypequery init [options]
```
</CodeBlock>

**Options:**
- **`--path <dir>`** – Target directory for the scaffold (`client.ts`, `schema.ts`, and either `queries.ts` or `datasets.ts`/`api.ts`). Defaults to `analytics/`
- **`--style <style>`** – Scaffold style: `queries` (default — query-builder routes) or `datasets` (semantic datasets API)
- **`--auth <mode>`** – Auth scaffold mode: `none` (default) or `context` (adds host/user context auth helpers)
- **`--all-tables`** – With `--style datasets`, generate dataset definitions for every discovered table
- **`--tables <names>`** – With `--style datasets`, generate datasets only for these comma-separated tables
- **`--exclude-tables <names>`** – With `--style datasets`, exclude these comma-separated tables from generation
- **`--no-example`** – Skip generating the sample query
- **`--database <type>`** – Database driver: `clickhouse` (default) or `chdb` to scaffold onto [embedded ClickHouse](/docs/chdb) — no server or credentials, and no `.env` is created or updated
- **`--chdb-path <path>`** – With `--database chdb`, the directory the embedded session stores data in (e.g. `./analytics.chdb`); omit for an in-memory session. Reuse the same flag when later generate commands must see tables created by another process
- **`--no-interactive`** – Skip prompts and read the ClickHouse URL/database/user/password from `CLICKHOUSE_*` env vars. The command fails if any required variable is missing. With `--database chdb` there are no connection variables to read
- **`--force`** – Overwrite existing files without asking
- **`--skip-connection`** – Skip the initial database connectivity test and scaffold files without validating the selected driver first

Running `hypequery` with no command in an interactive terminal starts `init` too, so `npx hypequery` on its own begins setup. Use `hypequery --help` to list every command. When the CLI is not attached to a terminal (scripts, CI, piped input), the bare command still prints help and exits with code 1, so it never waits on a prompt nobody can answer.

**What it does:**

For the default `clickhouse` driver, the CLI validates the remote connection using the credentials you provide. For `chdb`, it installs and starts the embedded engine against the selected storage path. On success it:
- Writes remote ClickHouse credentials to `.env`; chDB writes no connection configuration because later commands use explicit driver and path flags
- Generates `client.ts`, `schema.ts`, and `queries.ts` (or `datasets.ts` + `api.ts` with `--style datasets`) in the selected directory
- Creates or updates `.gitignore` to protect secrets
- Installs the scaffold dependencies the generated files expect (`@hypequery/clickhouse`, `@hypequery/serve`, `zod`, plus `@hypequery/datasets` for the datasets style and `chdb` for the embedded driver) using the package manager detected in your project
- Prints follow-up instructions for `hypequery dev`

With a valid connection, interactive mode can generate a table-backed example after you select a table. Otherwise the query scaffold contains a database-independent `exampleMetric`. To skip the automatic dependency install (for example in CI), set `HYPEQUERY_SKIP_INSTALL=1` and install the packages yourself.

The generated scaffold is written for modern ESM and NodeNext-style resolution, so local relative imports include the `.js` extension where needed.

Use `init` when you want the CLI to create the starting files for you. If those files already exist and you only need to refresh `schema.ts`, use `generate` instead.

**Example:**

<CodeBlock>
```bash
# Interactive mode (recommended)
npx @hypequery/cli init

# Non-interactive with custom path
npx @hypequery/cli init --path src/analytics --no-interactive

# Scaffold the datasets semantic API for specific tables
npx @hypequery/cli init --style datasets --tables users,orders

# Scaffold datasets for every table, with context-based auth helpers
npx @hypequery/cli init --style datasets --all-tables --auth context
```
</CodeBlock>

Interactive mode first asks whether to use a ClickHouse server/Cloud or
embedded chDB. It then asks for the selected driver's connection or storage
details, the output directory, API style, and authentication scaffold. If the
ClickHouse URL is left blank, the remaining credential questions are skipped
and placeholder configuration is generated. Run the command from the project
directory containing `package.json`; otherwise the CLI asks for confirmation
before it writes any files.

## `hypequery dev [file]` [#hypequery-dev-file]

<CodeBlock>
```bash
# Without installation
npx @hypequery/cli dev [path/to/queries.ts] [options]

# With installation
npx hypequery dev [path/to/queries.ts] [options]
```
</CodeBlock>

**Options:**
- **`[file]`** – Optional path to your entry file. When omitted, the CLI searches, in order: `hypequery.ts`, `analytics/api.ts`, `src/analytics/api.ts`, `api.ts`, `src/api.ts`, `analytics/queries.ts`, `src/analytics/queries.ts`, `queries.ts`, `src/queries.ts`
- **`--path <path>`** – Analytics directory to load from (resolves `<path>/api.ts`, falling back to `<path>/queries.ts`)
- **`-p, --port <port>`** – Desired port (default: `4000`)
- **`-h, --hostname <host>`** – Bind address (default: `localhost`)
- **`--no-watch`** – Run once without watching for file changes
- **`--open`** – Open the local server URL in your default browser after the server starts
- **`-q, --quiet`** – Reduce startup noise

**What it does:**

The dev server:
- Loads your ClickHouse schema to display table counts
- Registers all queries from your queries file
- Starts a local HTTP server for your queries
- Provides interactive API documentation at `/docs`
- Auto-reloads on file changes (unless `--no-watch`)
- Displays query execution stats

When `--open` is set, the CLI opens your browser to the local server URL.

**Example:**

<CodeBlock>
```bash
# Basic usage
npx @hypequery/cli dev

# Custom port with browser auto-open
npx @hypequery/cli dev --port 3000 --open

# Run once without file watching
npx @hypequery/cli dev --no-watch
```
</CodeBlock>

**TypeScript files:**

Point the command at your TypeScript entry point (for example `analytics/queries.ts`) and the CLI loads it via the embedded runtime. No separate `tsx` install is necessary.


## `hypequery generate` [#hypequery-generate]

<CodeBlock>
```bash
# Without installation
npx @hypequery/cli generate [options]

# With installation
npx hypequery generate [options]
```
</CodeBlock>

`hypequery generate` auto-detects remote ClickHouse configuration and ships with that driver, so the remote path needs no extra database package. Pass `--database chdb` to introspect an [embedded ClickHouse](/docs/chdb) session instead; this requires `chdb`, which `init --database chdb` installs automatically. Add `--chdb-path <dir>` for a persistent session. If the CLI detects a chDB dependency without an explicit driver, it stops with the exact command to run rather than silently opening an empty in-memory session.

Detection prefers remote ClickHouse configuration over an installed `chdb` dependency. The order is: `CLICKHOUSE_*` environment variables, ClickHouse variables in `.env`, then a `chdb` dependency. If none are present, generation stops and asks you to select a database explicitly. Use `--database clickhouse` or `--database chdb` to override detection. This means a project may depend on `chdb` and still generate against ClickHouse Cloud:

<CodeBlock>

```bash
CLICKHOUSE_URL=https://example.clickhouse.cloud:8443 \
CLICKHOUSE_DATABASE=default \
CLICKHOUSE_USERNAME=default \
CLICKHOUSE_PASSWORD=secret \
npx hypequery generate --database clickhouse
```

</CodeBlock>

This is the command most users want after initial setup. Run it whenever your ClickHouse schema changes and you need to refresh the generated TypeScript types.

**Options:**
- **`-o, --output <file>`** – Where to write the generated types. When omitted, the CLI reuses an existing schema file (searching `analytics/schema.ts`, `src/analytics/schema.ts`, `schema.ts`, `src/schema.ts`) and otherwise defaults to `analytics/schema.ts`
- **`--path <dir>`** – Analytics directory to write into (derives `<dir>/schema.ts`). Takes effect when `--output` is not set
- **`--tables <names>`** – Comma-separated list of tables to include. By default all ClickHouse tables are introspected
- **`--database <type>`** – Override the detected database driver: `clickhouse` or `chdb`
- **`--chdb-path <path>`** – With `--database chdb`, select the embedded session directory to introspect; omit only when intentionally generating against a new in-memory session

`hypequery generate:types` is an alias for `hypequery generate` and accepts the same options.

**What it does:**

The generator:
- Connects to remote ClickHouse using `CLICKHOUSE_*`, or opens the configured chDB session
- Introspects your database schema
- Generates TypeScript interfaces for all tables
- Updates your schema file with type-safe definitions

For remote ClickHouse, ensure the `CLICKHOUSE_*` variables are set (or run `hypequery init` first). For chDB, use an on-disk session path when the schema was created by another process; an in-memory session starts empty in each CLI invocation.

Unlike `init`, `generate` does not scaffold `client.ts` or `queries.ts`. It only updates the generated schema types.

**Example:**

<CodeBlock>
```bash
# Generate all tables
npx @hypequery/cli generate

# Generate specific tables only
npx @hypequery/cli generate --tables users,events

```
</CodeBlock>

## `hypequery generate:datasets` [#hypequery-generatedatasets]

<CodeBlock>
```bash
# Without installation
npx @hypequery/cli generate:datasets [options]

# With installation
npx hypequery generate:datasets [options]
```
</CodeBlock>

Scaffolds [dataset (semantic layer)](/docs/datasets/overview) definitions from a remote ClickHouse schema, so you don't have to hand-write dimensions and measures for every table. This standalone command currently uses `CLICKHOUSE_*` configuration. For chDB, `hypequery init --database chdb --style datasets` can generate dataset definitions during the initial scaffold, but `generate:datasets` does not currently accept the chDB driver or session path.

**Options:**
- **`-o, --output <file>`** – Where to write the generated datasets. Defaults to `analytics/datasets.ts`, alongside `hypequery generate`'s `analytics/schema.ts`
- **`--path <dir>`** – Analytics directory to write into (derives `<dir>/datasets.ts`). Takes effect when `--output` is not set
- **`--tables <names>`** – Comma-separated list of tables to include. By default all tables are scaffolded
- **`--exclude-tables <names>`** – Comma-separated list of tables to exclude
- **`--tenant-column <column>`** – Set `tenantKey` to this column on every table that has it. Only pass this once a trusted runtime tenant scope is configured
- **`--force`** – Atomically replace an existing output file when generated contents differ
- **`--check`** – Do not write; exit non-zero when the output file is missing or out of date
- **`--diff`** – Do not write; print the generated changes and exit non-zero when they differ

**What it does:**

The generator connects to ClickHouse with your `CLICKHOUSE_*` env vars and renders a `datasets` export containing a `dataset(...)` definition per table with inferred dimensions and measures. It creates a missing output file, but refuses to overwrite an existing customized file unless you pass `--force`. Without `--force` the output is created exclusively, so a file another process wrote in the meantime is refused rather than clobbered; with `--force` the replacement is atomic and keeps the existing file's permissions. Use `--check` in CI or `--diff` to review schema-driven changes without writing. Review and customize the output, then import it into your application or `api.ts`.

Column names such as `tenant_id`, `organization_id`, or `customer_id` are reported as possible tenant-key candidates — all of them, not just the first match — but the generator never enables `tenantKey` from a name match. Tenant isolation is a security policy: add it explicitly only after configuring trusted runtime tenant scope in your application or Serve API.

To turn isolation on, pass `--tenant-column <column>`: every table that has that column gets a matching `tenantKey`, and tables that don't are reported as warnings. `hypequery init --auth context` does this for you, scaffolding an `api.ts` with a trusted tenant runtime on `tenant_id` and generating datasets with `tenantKey: 'tenant_id'`.

Regeneration replaces the whole file, so **pass `--tenant-column` again on every refresh of a tenant-scoped project**. Without it the new file has no `tenantKey` and tenant-scoped requests fail until you restore it. `init` prints the exact command to reuse.

**Example:**

<CodeBlock>
```bash
# Generate datasets for all tables (writes analytics/datasets.ts)
npx @hypequery/cli generate:datasets

# Generate into your analytics folder for specific tables
npx @hypequery/cli generate:datasets --path analytics --tables users,orders

# Review regeneration without overwriting customizations
npx @hypequery/cli generate:datasets --path analytics --diff

# Verify generated definitions in CI
npx @hypequery/cli generate:datasets --path analytics --check
```
</CodeBlock>

## `hypequery generate:manifest <api>` [#hypequery-generatemanifest-api]

<CodeBlock>
```bash
npx hypequery generate:manifest analytics/api.ts --output analytics/hypequery-manifest.json
```
</CodeBlock>

Loads the API module, calls `api.manifest()`, and writes the result as JSON: each query, metric and dataset key
(`dataset:<name>` for datasets) mapped to its HTTP method and full path. Import the file in the module that creates your
React hooks, together with `import type { api }` and `InferApiType`, so no server code reaches the browser bundle. See
[React: setup](/docs/react/getting-started#setup).

The module must export the value returned by `createAPI()` or `initServe(...).serve(...)`. Loading it runs its top-level
code, so the environment it needs to construct a client must be available.

**Options:**
- **`-o, --output <file>`** – Where to write the manifest. Defaults to `analytics/hypequery-manifest.json`. An existing
  file is overwritten

Re-run it whenever you add or re-route an endpoint, for example in a `prebuild` script.

## `hypequery generate:client [contract]` [#hypequery-generateclient-contract]

<CodeBlock>
```bash
# From a client contract exported by a TypeScript serve API or a Python API
npx hypequery generate:client client-contract.json --output src/hypequery-client.ts

# From the live cloud release of the target chosen with `hypequery login`
npx hypequery generate:client --cloud --output src/hypequery-client.ts
```
</CodeBlock>

Generates a browser-safe TypeScript file from a **client contract**: the signed description of each endpoint's fields,
routes and schema hash. It exports `ClientApi` (request and response types for `createAnalyticsHooks<ClientApi>()`),
`clientManifest` (routes and schema hashes), `clientContractHash`, and, with `--cloud`, `clientBaseUrl`. The generator
reads data only: it never imports your API module or opens a database connection.

Contracts come from a TypeScript serve API ([`hypequery export:client-contract`](#hypequery-exportclient-contract-api)),
a Python API (`python -m hypequery export client-contract`, see
[Python: React and MCP clients](/docs/python/client-endpoints#3-export-the-contract)) or a cloud release. Only the
**build** view is accepted; the authorized view served at a live `/v1/client-contract` route is refused. When the
React app is in the same repository as a TypeScript API, `InferApiType` with `generate:manifest` needs no contract.

**Options:**
- **`-o, --output <file>`** – Where to write the client. Defaults to `analytics/hypequery-client.ts`
- **`--check`** – Do not write; exit non-zero when the output is missing or out of date
- **`--force`** – Replace an existing generated file. Files not written by `generate:client` are never overwritten
- **`--cloud`** – Read the contract from the live cloud release instead of a file
- **`--project <project>`**, **`--environment <environment>`** – With `--cloud`, override the target chosen at login
- **`--endpoint <url>`** – With `--cloud`, an HTTPS submission endpoint; requires `HYPEQUERY_API_TOKEN`

When an endpoint changes after the client was generated, the server answers requests from the old client with
`409 CLIENT_SCHEMA_CHANGED`, and the hooks raise `ClientSchemaChangedError`. Regenerate the client and review the type
errors.

## `hypequery export:client-contract <api>` [#hypequery-exportclient-contract-api]

<CodeBlock>
```bash
npx hypequery export:client-contract analytics/api.ts --output client-contract.json
```
</CodeBlock>

Writes the build view of a TypeScript serve API's [client contract](/docs/react/getting-started#datasets-served-from-typescript-in-another-repo): every dataset endpoint and measure-backed metric endpoint, with typed fields, full paths and schema hashes. A React app in another repository turns it into typed hooks with `hypequery generate:client`. The module must export the value `createAPI()` returns, as `api` or as the default export; the command calls its `api.clientContract()`, checks the result's identities, and connects to no database.

**Options:**
- **`-o, --output <file>`** – Where to write the contract. Defaults to `client-contract.json`
- **`--stdout`** – Write only the canonical contract to stdout
- **`--check`** – Do not write; exit non-zero when the file is missing or out of date
- **`--force`** – Atomically replace an existing contract file

It refuses to overwrite an existing file without `--force`, and refuses an API with no dataset or metric endpoints, since named queries are not part of a client contract. The output is the same canonical JSON Python's `hypequery export client-contract` writes for an equivalent definition.

## `hypequery login` [#hypequery-login]

Signs this machine in to hypequery Cloud. Without options it opens a browser
here. With `--device` it prints a code and a URL to approve from any browser,
which works over SSH, in containers and for coding agents; it opens a browser
only when a person is at the terminal and `--no-input` is not set.

```bash
npx hypequery login
npx hypequery login --device
npx hypequery login --device --project shop --capabilities workspace:view,deployment:publish
```

| Option | Description |
| --- | --- |
| `--device` | Sign in by approving a code in any browser (RFC 8628 device sign-in) |
| `--project <slug>` | With `--device`: limit the token to one Cloud project |
| `--capabilities <list>` | With `--device`: cap the token below your role, comma-separated |
| `--cloud-url <url>` | Cloud origin (or `HYPEQUERY_CLOUD_URL`) |
| `--environment <environment>` | Browser sign-in only: the deployment target to save |

Both store a management token (`hqmt_`, 30 days) per Cloud origin, in the
operating-system credential vault or, where there is none, an owner-only
(`0600`) file in the CLI's config directory. `hypequery logout` revokes and
removes every stored token. `--device` prints its code and URL on stderr. Device sign-in doesn't save a deployment target
yet, so pass `--project` and `--environment` to the deploy commands after it.

Commands that talk to Cloud use `HYPEQUERY_API_TOKEN` first, then the stored
management token (for `HYPEQUERY_CLOUD_URL` when it is set, otherwise for the
latest sign-in), then browser sign-in's deploy credential. `HYPEQUERY_API_TOKEN`
may hold a management token (`hqmt_…`) or a deploy key (`hqdp_…`); either goes to
`HYPEQUERY_CLOUD_URL` unless `--endpoint` or `HYPEQUERY_DEPLOYMENT_ENDPOINT` names
another endpoint. Any other token needs that explicit endpoint. A
`HYPEQUERY_CLOUD_URL` or `HYPEQUERY_DEPLOYMENT_ENDPOINT` from a project `.env` file
is refused when `HYPEQUERY_API_TOKEN` comes from your shell; set it in your shell.
A management token goes only to its own Cloud origin; an explicit endpoint on
another host is refused (`MANAGEMENT_TOKEN_ENDPOINT_MISMATCH`). Deploy keys may go
to any endpoint.

`hypequery login` refuses a `HYPEQUERY_CLOUD_URL` from a project `.env` file
(`CLOUD_URL_FROM_ENV_FILE`); pass `--cloud-url` or set it in your shell. A
non-default Cloud from the shell is printed on stderr before the sign-in starts.

## `hypequery deploy <cloud>` [#hypequery-deploy-cloud]

<Callout type="warn" title="hypequery cloud is not live yet">
  `hypequery deploy` and the other Cloud commands need a Cloud account, which you can't create yet. They are
  documented ahead of launch. Join the waitlist from the [homepage](/).
</Callout>

Builds the publication module, prepares a release for the logged-in target,
and submits it. Once Cloud accepts the release, the CLI prints where it's
served:

```text
Hosted endpoints
  REST  https://<environment-slug>.hypequery.app
    orders  POST https://<environment-slug>.hypequery.app/api/analytics/datasets/orders/query
  MCP   https://<environment-slug>.hypequery.app/mcp
```

Cloud provides these URLs, so the CLI follows Cloud's current routing. A live
release is required before dataset calls work. A Cloud release that doesn't
provide endpoint details leaves deploy output unchanged.

The build refuses a derived measure the deployment contract cannot carry (one
that references another derived measure, or uses a literal anywhere other than
`round` decimals or a `coalesce` fallback) with an error naming the dataset and
measure, for example `orders.doubled: a numeric literal cannot be an arithmetic
operand in a deployable formula`. See
[Deployable formulas](/docs/datasets/measures#deployable-formulas).

| Option | Description |
| --- | --- |
| `--mcp-config` | Also print MCP client configuration for the hosted endpoint. It reads the key from `${HYPEQUERY_API_KEY}` and never contains a credential |
| `--project`, `--environment` | Override the target from `hypequery login` |
| `--replace-restored` | Replace a live release that was restored from history |
| `--take-ownership` | Replace a live model built in hypequery Cloud. The project is then managed in code. Without it, the CLI asks in a terminal and refuses in CI |
| `--draft <name>` | Save or update a named code draft without publishing Production |
| `--no-source` | Leave project source files out of the bundle |

### Named code drafts [#named-code-drafts]

```bash
npx hypequery deploy analytics/cloud.ts --draft revenue-update
# A prebuilt bundle supports the same option:
npx hypequery deployment:submit analytics/hypequery-deployment --release analytics/hypequery-deployment.release.json --draft revenue-update
```

Use lowercase letters, numbers and single hyphens, up to 64 characters. Reusing
that name updates the same draft in the target project. The CLI prints its draft
ID and staging endpoint, then stops; it does not print Production connection
configuration or change the active release. `--draft` cannot be combined with
`--replace-restored` or `--take-ownership`.

Review and test the saved model in Cloud before publishing it. Uploading again
does not silently advance a stale draft's Production base. If Production has
changed, incorporate those changes in your repository, upload to the same draft,
and explicitly refresh its base in Cloud before reviewing publication again.
This option requires a Cloud service that supports named code draft uploads.

## `hypequery deployment:status` [#hypequery-deploymentstatus]

Shows the current release and Cloud-provided REST and MCP URLs without building
or deploying again. It uses the target and deployment credential saved by
`hypequery login`. With an explicit deployment credential, pass both
`--project` and `--environment`.

```bash
npx hypequery deployment:status
npx hypequery deployment:status --mcp-config
```

The command says when no release is live. Its optional MCP configuration uses
`${HYPEQUERY_API_KEY}` as a placeholder and never includes the stored deployment
credential.

| Option | Description |
| --- | --- |
| `--project`, `--environment` | Override the target from `hypequery login`; pass both together |
| `--endpoint` | Use an explicit Cloud submission endpoint with `HYPEQUERY_API_TOKEN` |
| `--mcp-config` | Also print MCP client configuration for the hosted endpoint |

## `hypequery mcp [file]` [#hypequery-mcp-file]

Serves the project's datasets over stdio for a local MCP client, or over Streamable HTTP with `--http`
([Remote MCP over HTTP](/docs/mcp/remote)).

Without `[file]`, the command looks for a Serve API file in the current directory: `hypequery.ts`,
`analytics/api.ts`, `src/analytics/api.ts`, `api.ts`, `src/api.ts`, `analytics/queries.ts`, or
`src/analytics/queries.ts`. It serves the datasets registered with `serve({ queryBuilder, datasets })` in that file.
With an absolute `[file]` it runs from any directory: the file's imports resolve from its own project, and that project's `.env*` files are loaded (values already set in the environment win). See [MCP](/docs/mcp/overview) for client setup.

| Option | Description |
| --- | --- |
| `--tenant <id>` | Trusted tenant for tenant-scoped datasets (required when any dataset is tenant-scoped) |
| `--self-test` | Check the entrypoint and exit. It fails if `@hypequery/mcp` isn't installed |
| `--self-test --url <mcp-url>` | Check a hosted endpoint instead: initialize and list tools, without calling one. The runtime API key is read from `HYPEQUERY_API_KEY` rather than a command argument |
| `--http` | Serve over Streamable HTTP. Callers send `HYPEQUERY_MCP_KEY`, or without it are verified by `defineServe` auth, each with their own tenant |
| `--port <n>`, `--host <address>` | With `--http`: where to listen (default `127.0.0.1:3333`) |
| `--allowed-hosts <names>` | With `--http`: comma-separated `Host` names to answer (default: loopback; required for another bind address) |
| `--allowed-origins <origins>` | With `--http`: comma-separated browser origins allowed to call |
| `--resource <url>`, `--authorization-servers <urls>`, `--required-scopes <scopes>` | With `--http`: OAuth resource-server settings |

Supply `HYPEQUERY_API_KEY` through your environment or secret manager before
running the check; the command never takes the key as an argument.

```bash
npx hypequery mcp --self-test --url https://<environment-slug>.hypequery.app/mcp
```

## `hypequery skill install` [#hypequery-skill-install]

Writes hypequery's agent skills where coding agents load them, so Claude Code, Cursor and Codex know how to author
datasets and query them without guessing the API:

- `hypequery-datasets`: defining datasets, measures, tenancy and relationships in TypeScript or Python.
- `hypequery-query`: answering questions through the MCP tools or HTTP endpoints instead of writing SQL.

```bash
npx hypequery skill install
```

| Option | Description |
| --- | --- |
| `--agent <agent>` | `claude` (`.claude/skills/`), `cursor` or `codex` (both read `.agents/skills/`), or `all` (default) |
| `--scope <scope>` | `project` (default, the current directory) or `user` (your home directory, for every project) |
| `--check` | Exit 1 if a skill is missing or out of date, without writing; useful in CI |
| `--force` | Replace skills that were edited or are out of date |

Re-running is safe: up-to-date skills are left alone, and an edited skill is never replaced without `--force`. The
Python CLI has the same command: `hypequery skill install`. To get the same skills in Claude Code for every project,
together with the hypequery app connector, install the [Claude Code plugin](/docs/mcp/claude-code-plugin) instead.

## `hypequery examples list` [#hypequery-examples-list]

Lists every entry of the [examples registry](/examples): runnable examples, recipes and guides, each tested in CI against one seeded ClickHouse dataset. The registry index is fetched from `https://hypequery.com/examples.json`.

```bash
npx hypequery examples list
npx hypequery examples list --json --kind recipe
```

| Option | Description |
| --- | --- |
| `--json` | Print the index as JSON (slug, kind, title, outcome, packages, run commands, pinned package versions) |
| `--kind <kind>` | Only `example`, `recipe` or `guide` |

## `hypequery create <slug>` [#hypequery-create-slug]

Scaffolds an example or recipe from the registry into `./<slug>`. It needs `git` and network access, nothing else: no account, no prompts with `-y`, a non-zero exit on failure, and it always ends with a `Next:` block naming the commands to run.

```bash
npx @hypequery/cli create nextjs-dashboard -y
cd nextjs-dashboard
pnpm dev
```

What it does:

1. Fetches `examples/<slug>` (and the shared seed, `examples/_seed`) from the hypequery repository with a blobless sparse checkout.
2. Rewrites the example's `workspace:*` dependencies to the exact `@hypequery/*` versions the example was last tested with. A version that is not on npm yet falls back to `--tag` (default `latest`).
3. Copies the seed into `./<slug>/seed` so `docker compose -f seed/docker-compose.yml up -d --wait` and `pnpm seed` give you the same million-row dataset the pages show.
4. Installs dependencies with the package manager that ran it (`npx` → npm, `pnpm dlx` → pnpm, and so on).

| Option | Description |
| --- | --- |
| `-y, --yes` | Accept defaults and never prompt |
| `--dir <path>` | Target directory (default `./<slug>`; must be empty) |
| `--no-install` | Skip the dependency install |
| `--no-seed` | Skip copying the shared seed dataset |
| `--tag <dist-tag>` | Dist-tag for `@hypequery/*` packages whose recorded version is not on npm (default `latest`) |

Set `HYPEQUERY_EXAMPLES_INDEX` to a URL or a local file to scaffold from another index, for example a branch of the repository.

## Scripts, CI and coding agents [#scripts-ci-and-coding-agents]

Every command can run headless. Coding agents (Claude Code, Codex), CI jobs and scripts can parse its results and recover from its errors without a person.

- **`--json`** (on any command) prints exactly one JSON document on stdout. Logs, spinners, package-manager output and next steps go to stderr, without colour. On success the document is the command's result; on failure it is an error envelope (below).
- **No prompts without a person.** A command prompts only in a terminal, and never with `--json`, `--no-input` or `CI` set. Anything it would have asked fails fast with exit code `1` and `INPUT_REQUIRED`, naming the flag or environment variable to pass (`init` asks for `--no-interactive` and the `CLICKHOUSE_*` variables).
- **Destructive changes need an explicit flag.** Overwriting generated files needs `--force` (`OUTPUT_EXISTS` otherwise). `init --no-interactive` over existing files fails with `CONFIRMATION_REQUIRED` instead of exiting `0` without writing. Replacing a restored live release needs `--replace-restored`.
- **`--no-input`** (or `CI`) also stops `hypequery login` from waiting for a browser (it fails with exit code `2`), and package installers run by `create` and `init` get no stdin. `hypequery login --device` still runs: it prints a code for a person to approve elsewhere and never opens a browser. In unattended runs, set `HYPEQUERY_API_TOKEN` to a management token (`hqmt_…`) or deploy key (`hqdp_…`).

```bash
hypequery generate:datasets --check --json
hypequery deploy analytics/cloud.ts --json > deploy.json
```

### Exit codes and errors [#exit-codes-and-errors]

Exit codes are fixed (`EXIT_CODES` in the CLI source):

| Code | Meaning | What to do |
| --- | --- | --- |
| `0` | Success | — |
| `1` | Correctable: bad options, missing input, not found, output exists, out of date | Fix what the message names and run again |
| `2` | Auth: not signed in, expired, refused or insufficient credential | Run `hypequery login` (or `hypequery login --device`) or set `HYPEQUERY_API_TOKEN` |
| `3` | Plan limit | Upgrade the plan, or ask for less |
| `4` | Transient: ClickHouse or Cloud unreachable or failing temporarily | Retry |
| `5` | Internal error in hypequery | Report it |
| `130` | Interrupted (Ctrl+C), including a cancelled prompt | — |
| `143` | Terminated (SIGTERM) | — |

With `--json`, a failure prints the same envelope as Cloud's `/v1` operations and MCP tools, plus the exit code:

```json
{
  "error": {
    "code": "INPUT_REQUIRED",
    "message": "This step needs an answer, and there is no terminal to ask in (or --json, --no-input or CI is set). Pass --style queries|datasets.",
    "hint": "Pass --style queries|datasets.",
    "docsUrl": "https://hypequery.com/docs/reference/api/cli#exit-codes-and-errors",
    "category": "correctable_input",
    "retryable": false,
    "correctable": true,
    "exitCode": 1
  }
}
```

`requestId` (relayed from Cloud) and `issues` (`[{ path, message }]`, for example each file that is out of date) appear when they apply. `category` is one of decision 0003's nine, shared with Cloud: `correctable_input`, `unauthenticated`, `forbidden`, `tenant_unavailable`, `budget_exceeded`, `cancelled`, `stale_contract`, `unavailable`, `internal`. `correctable` is true only for `correctable_input`. Codes never change meaning once released:

| Code | Category | Exit | Meaning |
| --- | --- | --- | --- |
| `USAGE` | `correctable_input` | 1 | Unknown command or option, or a missing argument |
| `INPUT_REQUIRED` | `correctable_input` | 1 | The command would have prompted; pass the named option or variable |
| `CONFIRMATION_REQUIRED` | `correctable_input` | 1 | A destructive change needs the named flag |
| `OUTPUT_EXISTS` | `correctable_input` | 1 | An output exists and differs; pass `--force` or choose another output |
| `NOT_FOUND` | `correctable_input` | 1 | An example or Cloud resource does not exist |
| `ENTRYPOINT_NOT_FOUND` | `correctable_input` | 1 | No API file was found to serve |
| `CLICKHOUSE_CONNECTION_FAILED` | `correctable_input` | 1 | `init --no-interactive` could not connect with the `CLICKHOUSE_*` settings |
| `CLICKHOUSE_ACCESS_DENIED`, `CLICKHOUSE_QUERY_FAILED` | `correctable_input` | 1 | ClickHouse refused the user or the discovery query; check credentials, database and grants |
| `CLICKHOUSE_PROFILE_UNREADABLE` | `correctable_input` | 1 | ClickHouse returned an unexpected settings profile for the user, so no query can be bounded; check the user's settings profile |
| `INVALID_INPUT` | `correctable_input` | 1 | A file or value could not be read, such as a deployment JSON or a `--join` pair |
| `JSON_NOT_SUPPORTED` | `correctable_input` | 1 | `mcp` serves over stdout; use `--self-test` with `--json` |
| `OUT_OF_DATE` | `stale_contract` | 1 | `--check` or `--diff` found generated output missing or out of date |
| `CLOUD_STATE_CHANGED` | `stale_contract` | 1 | The live deployment changed since the command read it |
| `CLOUD_REQUEST_FAILED` | `correctable_input` | 1 | Cloud rejected the request; its reason is in the message |
| `CLOUD_ENDPOINT_WITHOUT_TOKEN` | `correctable_input` | 1 | An endpoint is set without `HYPEQUERY_API_TOKEN`; set both, or neither to use `hypequery login` |
| `CLOUD_TOKEN_WITHOUT_ENDPOINT` | `correctable_input` | 1 | `HYPEQUERY_API_TOKEN` is not an `hqmt_` or `hqdp_` token and no endpoint is set |
| `CLOUD_ENDPOINT_INSECURE` | `correctable_input` | 1 | The Cloud endpoint is not HTTPS (HTTP is allowed only on localhost), so the credential is not sent |
| `CLOUD_DEVICE_SIGN_IN_UNSUPPORTED` | `correctable_input` | 1 | This Cloud has no device sign-in; use `hypequery login` where a browser can open |
| `CLOUD_DEVICE_SIGN_IN_REFUSED` | `correctable_input` | 1 | Cloud refused `--project` or `--capabilities` |
| `CLOUD_NOT_SIGNED_IN`, `CLOUD_CREDENTIAL_EXPIRED`, `CLOUD_UNAUTHORIZED`, `LOGIN_NEEDS_A_PERSON`, `CLOUD_AUTHORIZATION_DECLINED`, `CLOUD_AUTHORIZATION_TIMED_OUT` | `unauthenticated` / `forbidden` | 2 | No usable Cloud credential, or the sign-in was denied or expired |
| `CLOUD_URL_FROM_ENV_FILE` | `unauthenticated` | 2 | A project `.env` file set the Cloud URL or endpoint that a shell token, or `hypequery login`, would use; set it in the shell or pass a flag |
| `MANAGEMENT_TOKEN_ENDPOINT_MISMATCH` | `forbidden` | 2 | `--endpoint` or `HYPEQUERY_DEPLOYMENT_ENDPOINT` is on another host than the management token's Cloud |
| `CLOUD_PLAN_LIMIT` | `budget_exceeded` | 3 | The organisation's plan does not allow this |
| `CONNECTION_FAILED`, `CLOUD_UNAVAILABLE`, `CLOUD_NETWORK_ERROR`, `CLOUD_UNREACHABLE` | `unavailable` | 4 | ClickHouse or Cloud could not be reached (retryable) |
| `COMMAND_FAILED` | `correctable_input` | 1 | Any other failure the message explains |

A Cloud operation command (`hypequery <group> <action>`) reports Cloud's own envelope instead: Cloud's `code` (for example `RELEASE_MOVED` or `PROJECT_NOT_FOUND`), `hint`, `docsUrl`, `requestId` and `issues`, with the exit code from its category (`unauthenticated` and `forbidden` exit 2, `budget_exceeded` 3, `unavailable` and `internal` 4, everything else 1). Before calling Cloud, these commands can also fail with `CONFIRMATION_REQUIRED` (a destructive operation, or one that grants access or creates a credential, without `--yes` and without a terminal), `CONFIRMATION_DECLINED` (you answered no), `MISSING_INPUT` or `INVALID_OPTION` (a required or malformed flag, named in `issues`; also a secret given inline in `--input-json`, or an `--input-json @<file>` path that climbs out of the working directory). Error text from Cloud has its control characters removed before it is printed.

### `--json` results [#--json-results]

Fields are only ever added. Paths are absolute.

| Command | Result |
| --- | --- |
| `telemetry` | `{ action, enabled, source, installId, docsUrl }` |
| `examples list` | `{ version, packageVersions, entries }` |
| `create` | `{ slug, kind, directory, packageManager, install, seed, unpublished, next, url }` |
| `init` | `{ directory, database, style, auth, connection, files, datasetsGenerated }` |
| `dev` | Printed once listening; the server keeps running: `{ url, hostname, port, entrypoint, docsUrl, openapiUrl, queries, watching }` |
| `mcp --self-test` | `{ ok, mode: "local" \| "hosted" \| "http", … }`. Serving MCP refuses `--json`: stdout carries the protocol |
| `generate`, `generate:types` | `{ output, database, tables }` |
| `generate:datasets` | `{ status, output, tables, warnings }` |
| `generate:manifest` | `{ output, routes }` |
| `generate:client` | `{ status, output, endpoints }` |
| `export:client-contract` | `{ status, output }`, or the canonical contract itself with `--stdout` |
| `skill install` | `{ installed, upToDate, files }` |
| `login` / `logout` | `{ signedIn, target, expiresAt, managementTokenExpiresAt }` / `{ signedIn: false, … }` |
| `login --device` | `{ signedIn, method: "device", cloudUrl, organizationId, project, projectLimited, capabilities, target, expiresAt, storage }`; never the token |
| `deployment:build` | `{ bundle, deployment, unscopedTenantCandidates }` |
| `deployment:validate` | `{ valid, kind, path, deployment, bundle? }` |
| `deployment:release` | `{ release: { path, identity, bundleIdentity, target } }` |
| `deployment:submit`, `deploy` | `{ status, releaseIdentity, bundleIdentity, target, endpoints \| draft }` |
| `deployment:status` | `{ target, live, endpoints }` |
| `pull` / `diff` | `{ destination, releaseIdentity, entrypoint, files }` / `{ releaseIdentity, matches, differences }` |
| `<group> <action>` (Cloud operations) | The operation's output, exactly as Cloud returns it (its schema is in `operations-v1.json`) |

## Environment variables [#environment-variables]

These variables are read whenever the CLI talks to a remote ClickHouse server (either during `init` in non-interactive mode or during later remote-driver commands). They are not used by chDB:

| Variable | Description |
| --- | --- |
| `CLICKHOUSE_URL` | Fully-qualified ClickHouse URL, e.g. `https://example.clickhouse.cloud:8443` |
| `CLICKHOUSE_DATABASE` | Database to target (defaults to `default`) |
| `CLICKHOUSE_USER` | Username used for CLI connections |
| `CLICKHOUSE_PASSWORD` | Password or token |
| `CLICKHOUSE_HOST` / `CLICKHOUSE_USERNAME` / `CLICKHOUSE_PASS` | Backward-compatible aliases also detected by the CLI |

Set these in an env file (the default ClickHouse `init` flow will scaffold `.env` for you) or export them in CI/CD before running remote-driver CLI commands.

The CLI reads the same cascade Next.js and Vite use, most specific first:

1. `.env.$NODE_ENV.local`
2. `.env.local`
3. `.env.$NODE_ENV`
4. `.env`

Earlier files win, and a variable already present in the real environment beats
every file. Files cannot change this: `DOTENV_CONFIG_OVERRIDE` and
`DOTENV_OVERRIDE` are ignored. So a Next.js project that keeps its ClickHouse credentials in
`.env.local` works with the CLI without duplicating them into `.env`.

## Troubleshooting [#troubleshooting]

### Connection errors [#connection-errors]

Verify the environment variables above and ensure network access to ClickHouse. The CLI reports detailed errors with actionable hints:
- `ECONNREFUSED` – ClickHouse is not running or the URL/port is wrong
- `Authentication failed` – Check username and password
- TLS errors – Verify SSL configuration

### Missing files [#missing-files]

Run `hypequery init --force` to regenerate the `analytics/` folder if it was removed.

### TypeScript errors [#typescript-errors]

If you see "Unexpected token" or syntax errors when running `hypequery dev`, the usual causes are:

1. A broken import path
2. A missing dependency in your project
3. A `tsconfig.json` mismatch affecting module resolution

As a fallback, compile your TypeScript first:
<CodeBlock>
```bash
tsc src/analytics/queries.ts
npx @hypequery/cli dev src/analytics/queries.js
```
</CodeBlock>

### Wrong file or export [#wrong-file-or-export]

If the CLI reports that your file doesn't export an API properly:

1. Ensure your entry file exports the hypequery API as `api` (a `default` export also works)
2. Check the error message for the list of exports found
3. See the expected format in the error message

The CLI accepts either entry style. Query-builder routes use `serve({ queries })`:
<CodeBlock>
```typescript
import { initServe } from '@hypequery/serve';

const { query, serve } = initServe({
  context: () => ({ db }),
});

const myQuery = query({
  query: async ({ ctx }) => {
      // ...
    },
});

export const api = serve({
  queries: { myQuery },
});
```
</CodeBlock>

The datasets semantic API uses `createAPI`:
<CodeBlock>
```typescript
import { createAPI } from '@hypequery/serve';
import { db } from './client.js';
import { datasets } from './datasets.js';

export const api = createAPI({
  queryBuilder: db,
  datasets,
});
```
</CodeBlock>

</div>
