# Python CLI (/docs/python/cli)

The `hypequery` command ships with the Python package and needs no Node tooling. `python -m hypequery` runs the same
CLI. Install the serving and ClickHouse extras for the full onboarding path, then run `init` in a terminal:

<CodeBlock>
```bash
pip install "hypequery[server,clickhouse]==0.1.0b4"
hypequery init analytics
```
</CodeBlock>

`init` asks how to reach ClickHouse and which app to scaffold, then writes datasets for your tables into `analytics/`.
Start the API it created:

<CodeBlock>
```bash
cd analytics
hypequery dev
```
</CodeBlock>

From another shell, query one of your datasets (the README `init` writes shows the call for your own tables):

<CodeBlock>
```bash
curl -s -X POST http://127.0.0.1:8000/datasets/orders/query \
  -H "Content-Type: application/json" \
  -d '{"dimensions": ["status"], "measures": ["totalCount"]}'
```
</CodeBlock>

The standalone app's API is open for local development: every request queries as one developer, with no token. Before
deploying, replace its `auth` with real authentication (see [Authentication](/docs/python/authentication)).

`hypequery --help`, `hypequery <command> --help`, `hypequery help <command>` and `hypequery --version` (or `-V`) work
without the extras. Exit codes are `0` for success, `1` for a runtime failure and `2` for invalid usage.

## Connection settings and `.env` [#connection-settings-and-env]

The CLI reads `CLICKHOUSE_URL`, or `CLICKHOUSE_HOST`, `_PORT`, `_DATABASE`, `_USERNAME`, `_PASSWORD` and `_SECURE`. Like
the TypeScript CLI, it also loads `.env.local` and then `.env` from the folder you run it in, so the settings can live
in a gitignored file:

<CodeBlock>
```bash
# .env
CLICKHOUSE_HOST=localhost
CLICKHOUSE_PORT=8123
CLICKHOUSE_DATABASE=analytics
CLICKHOUSE_USERNAME=default
CLICKHOUSE_PASSWORD=your-password
```
</CodeBlock>

A variable already set in your shell wins over both files. Only the CLI reads them (`init`, `generate datasets` and
`dev`): the library and the apps `init` generates read the real environment, so in production set these as environment
variables or secrets. To apply the same rules in a script of your own, call
`hypequery.cli.load_env_files(Path.cwd())` before `ClickHouseConnection.from_env()`.

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

Creates a project from your live schema: `datasets.py` with one dataset per table, a `schema.json` snapshot, the
application you choose, a `pyproject.toml`, a `README.md` and a `.env.example`. Existing files are never overwritten.
The `.env.example` and README repeat how discovery connected: `CLICKHOUSE_URL` if it was set, otherwise the host, port
and TLS setting that worked, with credentials left as placeholders.

### Guided setup [#guided-setup]

In a terminal, `init` asks for whatever its options leave unset, in this order:

1. **Where** to create the project (a new `analytics` folder when the current one isn't empty).
2. **How to reach ClickHouse**: the connection already in your environment or `.env`, or a URL, username, password
   (hidden as you type) and database. Typed-in details are used only to read the schema and are never written to a
   file; `init` prints the `.env` lines to save, with the password left for you. If the connection fails, you can try
   again, change the details, or create the offline example instead.
3. **Which tables**, only when the database has more than ten.
4. **The tenant column**, only when one looks like a tenant id (`tenant_id`, `organization_id`, `org_id`, `account_id`
   or `customer_id`): use it, pick another column, or skip tenant isolation.
5. **Which app** to scaffold: standalone, FastAPI, Django or Flask. The default follows your project: Django when
   there is a `manage.py`, otherwise whichever of the three your `pyproject.toml` or `requirements.txt` names.

It then shows a summary and the same choices as one command, for example
`hypequery init analytics --no-interactive --framework fastapi --tenant-column org_id`, and asks before writing
anything. Every option answers its question. `--no-interactive`, a `CI` environment variable, or input that isn't a
terminal skip the questions entirely, and unset options take their defaults.

### Options [#options]

| Option | Description |
| --- | --- |
| `[directory]` or `--path <dir>` | Destination; defaults to the current directory |
| `--tables a,b` | Only inspect these tables (default: all) |
| `--exclude-tables a,b` | Skip these tables |
| `--all-tables` | Inspect every table (the default) |
| `--tenant-column <column>` | Set `tenant_key` on tables that have this column, as `generate datasets` does |
| `--framework standalone\|fastapi\|django\|flask` | The application to write beside `datasets.py` (default `standalone`); see below |
| `--database clickhouse\|chdb` | A ClickHouse server (default), or embedded chDB with no server; see below |
| `--chdb-path <dir>` | The chDB database directory, relative to the project (default `analytics.chdb`). Implies `--database chdb` |
| `--skip-connection` | Write the offline orders example and `seed.sql` instead of inspecting a database |
| `--no-interactive` | Never ask questions, even in a terminal |

### Applications [#applications]

| `--framework` | Writes | Run with |
| --- | --- | --- |
| `standalone` (default) | `app.py`: an API from `create_api`, served as plain ASGI with no web framework | `hypequery dev` |
| `fastapi` | A FastAPI `app.py` that mounts the API, and a route of your own | `uvicorn app:app --reload` |
| `django` | A small Django project (`settings.py`, `urls.py`, `manage.py`) and `analytics.py` | `python manage.py runserver` |
| `flask` | A Flask `app.py` | `flask --app app run --port 5001` |

The standalone API is open for local development, as above. The framework apps authenticate:

- **Django and Flask** serve hypequery's endpoints natively ([`urls(api)`](/docs/python/django#serve-hypequerys-endpoints),
  [`blueprint(api)`](/docs/python/flask#serve-hypequerys-endpoints)) twice: at `/api/analytics` behind the framework's
  own login with the same-origin check, for `@hypequery/react` on pages the app serves, and at `/api/agents` behind a
  bearer token, for `@hypequery/mcp` and scripts. Until you wire them to your login, Flask's session API refuses
  everyone, and tenant-scoped datasets refuse signed-in Django users.
- **FastAPI** has no login of its own, so its app [mounts](/docs/python/fastapi) the bearer-token API at `/api/agents`
  and adds `/analytics/<dataset>`, a route of your own that queries as whoever its `current_principal` dependency
  returns. It refuses everyone until you wire that to your login. The project depends on `fastapi` directly; hypequery
  has no FastAPI extra.

The bearer token is `HYPEQUERY_DEV_TOKEN`, a local development token you set in the shell that runs the app. Their servers
don't load `.env` for you (Flask does only with python-dotenv installed), so export the connection settings there too. The generated README walks through
each app. Every choice also works with `--skip-connection`.

Schema discovery reads only `system.tables` and `system.columns` for the current database, so the user needs
`SHOW` and `SELECT` on it. A read-only user works, whether its profile sets `readonly = 1` or `2`. If discovery fails,
the message names what to check: credentials, host and port, the database, or grants.

### Tenant-scoped datasets [#tenant-scoped-datasets]

With `--tenant-column`, each dataset gets a `tenant_key`, and every query must run for one tenant. The standalone
app's developer principal has no tenant, so queries answer `403 FORBIDDEN` ("requires runtime tenant scoping") until
you give it one. For local testing, return one from `developer` in `app.py`:

<CodeBlock>
```python
return Principal(subject="developer", tenant_id="org_123")
```
</CodeBlock>

In the FastAPI, Django and Flask apps, the development token reads the tenant in `HYPEQUERY_DEV_TENANT` instead: export
it in the app's shell before starting it. Before real users, replace the open API or the token check with your own
authentication so the tenant comes from the signed-in user.
See [Multi-tenancy](/docs/python/multi-tenancy).

Physical names map to the same camelCase semantic names as the TypeScript CLI. Numeric value columns get suggested
`sum` and `avg` measures; ids and coordinates stay dimensions. Unsupported columns and likely tenant columns are
reported, and nothing is written to the database. Review the generated semantics and configure tenant isolation
explicitly before serving real data.

### Embedded ClickHouse (chDB) [#embedded-clickhouse-chdb]

`--database chdb` scaffolds onto [embedded ClickHouse](/docs/python/datasets/chdb) instead of a server. Install the
`chdb` extra first (`pip install "hypequery[server,chdb]"`).

- The app opens the chDB database at `--chdb-path` (default `analytics.chdb`), relative to `app.py`, with
  `create_chdb_executor`. There are no connection settings, and the project installs the `chdb` extra.
- The path is recorded in the project's `pyproject.toml` (`[tool.hypequery] chdb-path`) for `generate datasets`.
- If the database exists, `init` reads its tables as it would a server's.
- If it doesn't, `init` writes the orders example, and its README seeds the database from `seed.sql`. `init` never
  creates the database itself.
- chDB scaffolds the `standalone` and `fastapi` apps. The Django and Flask integrations connect to a ClickHouse server,
  so `--framework django` or `flask` is refused with `--database chdb`.

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

Regenerates `datasets.py` from the current schema. Also spelled `generate:datasets`, as in the TypeScript CLI.

| Option | Description |
| --- | --- |
| `--output <file>` | Output file (default `datasets.py`) |
| `--path <dir>` | Output directory containing `datasets.py` |
| `--tables`, `--exclude-tables` | Table selection, as for `init`. Without them, the selection `init` was given (recorded in `schema.json`) is reused |
| `--all-tables` | Inspect every table, ignoring a recorded selection |
| `--tenant-column <column>` | Set `tenant_key` on tables that have this column; reports tables that do not |
| `--check` | Exit 1 if the file would change, without writing |
| `--diff` | Show the drift without writing; exit 1 if any |
| `--force` | Replace the existing file; warns when it removes a configured `tenant_key` |
| `--database clickhouse\|chdb`, `--chdb-path <dir>` | Read a ClickHouse server or a chDB database; see below |

Replacement is atomic and preserves the file's permissions. Use `--check` in CI to catch schema drift.

`generate datasets` reads a chDB database when given `--database chdb` or `--chdb-path`, when `pyproject.toml` records
one, or when the project has an `analytics.chdb` directory and neither `CLICKHOUSE_URL` nor `CLICKHOUSE_HOST` is set.
chDB lets one process open a database at a time, so stop `hypequery dev` before regenerating.

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

Serves a local app with uvicorn. Requires the `server` extra.

| Option | Description |
| --- | --- |
| `[app]` | Import string, default `app:app`, resolved from the working directory. It names an `Api` from `create_api` or its `to_asgi_app` application |
| `--hostname`, `--host <addr>` | Bind address, default `127.0.0.1`. Binding beyond loopback prints a warning |
| `-p`, `--port <port>` | Port, default `8000` |
| `--reload` / `--no-watch` (`--no-reload`) | Reload on file changes; on by default |

The dev runner is not hardened for a network. APIs created with a `ProductionProfile` are refused here; run those
with [`start_server`](/docs/python/production) behind a reverse proxy instead. Startup failures are reported without
their traceback so credentials in an exception never reach the terminal.

## `hypequery export client-contract` [#hypequery-export-client-contract]

Writes the canonical client contract that generated React hooks and the MCP bridge consume, without starting a server
or running a query.

| Option | Description |
| --- | --- |
| `--factory module:attribute` | Your API (from `create_api`, `to_asgi_app` or `to_wsgi_app`), or a zero-argument function returning it or a definition-only contract (required) |
| `--output <file>` | Output file, default `client-contract.json`; `-` for stdout |
| `--stdout` | Write canonical JSON only to stdout |
| `--check` | Exit 1 if the artifact would change, without writing |
| `--force` | Replace an existing artifact |

An API exports the endpoints installed with a client profile. An export with no endpoints fails, and from an API it
names the dataset and metric routes that have no profile. See [React and MCP clients](/docs/python/client-endpoints) for
the end-to-end workflow.

See [React and MCP clients](/docs/python/client-endpoints) for the end-to-end workflow.

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

Serves an API's authorized client contract to AI agents over MCP stdio, or Streamable HTTP with `--http`, with the
same tools, input schemas and errors as `@hypequery/mcp`. Needs the `mcp` extra: `pip install "hypequery[mcp]"`.

| Option | Description |
| --- | --- |
| `module:api` | The `Api` from `create_api`, or its `to_asgi_app` app, served in-process (default `app:api`). An app's `lifespan` runs around the server |
| `--client-contract-url <url>` | Bridge a deployed API's discovery route instead (HTTPS; plain HTTP only on loopback) |
| `--header 'Name: value'` | A header sent with every call, such as a credential (repeatable) |
| `--project <dir>` | Directory to import the app from (default: current) |
| `--self-test` | Read and validate the contract, count its endpoints and exit, without serving |
| `--print-config` | Print an `mcpServers` entry for Claude, Cursor or another MCP client |
| `--http` | Serve over Streamable HTTP instead of stdio. Callers send `HYPEQUERY_MCP_KEY`, or without it are authenticated by the Api's own auth |
| `--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 |

`HYPEQUERY_API_KEY`, when set, is sent as `Authorization: Bearer …`. The API authenticates and scopes every call, so
an agent gets exactly the endpoints, fields and tenant that credential's principal may use. See
[MCP: datasets served from Python](/docs/mcp/overview#datasets-served-from-python) and
[Remote MCP over HTTP](/docs/mcp/remote).

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

Writes hypequery's agent skills where coding agents load them: `hypequery-datasets` (authoring datasets),
`hypequery-query` (querying through MCP or HTTP) and `hypequery-onboard` (onboarding a ClickHouse database end to
end; its analysis steps run the TypeScript CLI through `npx`, so they need Node.js). Works on the base install.

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

## `hypequery demo` [#hypequery-demo]

Serves a sample semantic layer to AI agents over MCP stdio, on embedded ClickHouse (chDB). It seeds a two-tenant shop
in a temporary directory from data shipped in the package, with no server, configuration or network, and deletes it
when the client disconnects. Needs the `chdb` and `mcp` extras, or nothing but uv:

<CodeBlock>
```bash
uvx --from "hypequery[chdb,mcp]" hypequery demo --self-test
```
</CodeBlock>

| Option | Description |
| --- | --- |
| `--tenant acme\|globex` | The tenant the agent is signed in as (default `acme`) |
| `--self-test` | Answer the demo's questions in the terminal and exit, without serving. Needs only the `chdb` extra |
| `--print-config` | Print an `mcpServers` entry that launches the demo through `uvx` |

The demo seeds a small shop for two tenants, `acme` and `globex`. `--self-test` answers its questions in the terminal,
each beside the answer a naive query gets: orders in a `ReplacingMergeTree` read as resolved rows (1,536, not the
2,864 row versions), exact and approximate distinct users, revenue growth by month, and a 7-day trailing measure, all
scoped to one tenant. chDB publishes wheels for Linux and macOS only.

To let Claude Code query it:

<CodeBlock>
```bash
claude mcp add hypequery-demo -- uvx --from "hypequery[chdb,mcp]" hypequery demo
```
</CodeBlock>

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

The CLI collects pseudonymous usage telemetry by default, as the TypeScript CLI does, to show which commands,
Python versions and installers to prioritise. Each invocation sends one `python_cli_command_completed` event: the
command, the documented flags used (names only, never values), the outcome, a duration bucket, and install context
such as the package and Python versions, OS, the installer recorded for the package (pip, uv, poetry, ...), and which
optional integrations are installed. For `init`, it also records the furthest setup step reached and whether connecting
to ClickHouse worked, failed or was skipped. Events never contain code, SQL, table or column names, paths or credentials.
Telemetry is sent by a detached process after the command exits, so it never delays or changes a command.

<CodeBlock>
```bash
hypequery telemetry status
hypequery telemetry disable
hypequery telemetry enable
```
</CodeBlock>

To disable for one invocation, pass `--no-telemetry` anywhere on the command line, or set `DO_NOT_TRACK=1` or
`HYPEQUERY_TELEMETRY_DISABLED=1` (a project `.env` file works too). Set `HYPEQUERY_TELEMETRY_DEBUG=1` to print the
exact event to stderr instead of sending it. Both CLIs share one settings file and install ID, so disabling telemetry
in either disables it in both. See [CLI telemetry](/docs/telemetry) for storage and delivery details.
