# CLI API requests

> Send an authenticated API request and choose how the CLI prints the response.

Install the published CLI development prerelease with Node.js 22 or later:

```bash
npm install -g @polymorfa/cli@0.1.0-dev.0
polymorfa --version
```

This prerelease includes the commands below. Keep credentials in environment
variables, a secret manager, or a CLI authentication profile. The
[CLI reference](https://docs.polymorfa.com/cli) lists every command with its arguments, flags and
examples.

Use `polymorfa api` to send a request through the CLI with your selected
credential. Pass a relative path beginning with `/` and choose `messaging` or
`platform` as the credential surface:

```bash
polymorfa api /platform/customers --surface platform
```

The command uses GET unless you set `-X/--method`. Give the CLI a credential
through `POLYMORFA_API_KEY` or a configured authentication profile. Keep team
keys in a trusted environment. The API still enforces that credential's
permissions and project access.

For messaging, keep the returned `conversation.id` for later sends and replies.
The returned `phoneNumber` can differ from the phone used for lookup. See
[Conversation identity](https://docs.polymorfa.com/messaging/ids#conversation-identity).

## Check your CLI setup

Run `polymorfa doctor` before troubleshooting an API request. It checks your
Node.js version, profile configuration, keyring access, API reachability, and
server API key authentication:

```bash
polymorfa doctor --json
```

The command exits `0` when every required check completes. It exits `1` if a
check fails or credential validation is skipped. A missing credential or
multiple credential environment variables fail the check. A project or client
token is reported as present, but `doctor` cannot validate it remotely and
exits `1`; this does not determine whether that token can access a particular
command. Use one server API key to verify authentication. A `401` response
fails; a `403` response warns that the key authenticated but project listing
was denied. `--profile <name>` selects that profile instead of environment
credentials. The output does not include credential values.

## Complete commands in your shell

After installing the CLI, load the completion script for your shell:

```bash
source <(polymorfa completion bash)
```

For Zsh, initialize completion before loading the script:

```zsh
autoload -Uz compinit && compinit
source <(polymorfa completion zsh)
```

For Fish:

```fish
polymorfa completion fish | source
```

Press Tab after `polymorfa` to complete commands, or after a command to
complete its flags. The script also suggests fixed flag choices where a
command defines them. It uses information from the installed CLI and does not
look up profiles, project IDs, credentials, or other argument values. You can
add the loading command to your shell startup file for later sessions.

## Start a Node project

Run `init` in a directory where you want a Node.js and TypeScript
starter:

```bash
polymorfa init
```

The command writes `package.json`, `src/index.ts`, `.env.example`, and a
README. It refuses an existing starter file or `src` directory before writing
anything. No credential or project link is created. The package pins the
exact published SDK development version. Run
`npm install` and `npm run typecheck` in the starter directory, then set
`POLYMORFA_API_KEY` in your shell or secret manager before `npm start`.

Use `polymorfa link` separately when you want CLI commands to use a project.

## Inspect sessions

Use a
team API key with `sessions:read` to inspect session metadata:

```bash
polymorfa session list
polymorfa session list --project PROJECT_ID --json
polymorfa session view SESSION_ID
polymorfa session status SESSION_ID --json
```

`session list` returns every session in the team unless you pass a project ID.
Use a session ID from that list for `view` or `status`. Those two commands
reject `--project` because the session ID identifies one session across the
team. `status` shows the stored status and reason; it does not test the live
connection.

## Discover project sessions through local MCP

Run `polymorfa mcp tools` to list the local MCP tools.

Install the local MCP server for your agent client with
`polymorfa mcp install codex` or `polymorfa mcp install claude`. Give the CLI a
team API key with `sessions:read`. The read-only `polymorfa_session_list` tool
requires an explicit project UUID and returns each session's ID, name, stored status, and
test-mode flag. It does not return phone numbers, credentials, or message data,
and it does not probe a live connection. Project tokens and Messaging client
tokens cannot use this tool.

The local MCP server also exposes listener start, status, and stop tools. The
[hosted MCP server](https://docs.polymorfa.com/development/mcp) is a separate connection.

## Find documentation

Search the published documentation:

```bash
polymorfa docs search "rate limits"
```

The command prints matching page titles, paths, and links. It searches the
published documentation index and needs network access, but does not use your
Polymorfa credentials. Add `--json` to get the same results as a JSON array.

Open a page by the path shown in the results:

```bash
polymorfa docs open api/rate-limits
```

Use `--print` to get the URL without starting a browser. A short final path
segment works only when it identifies one page; use the full path when several
pages share the same name.

## Forward events to a local handler

`polymorfa listen` streams project events and forwards available exact event
bodies to a handler. Use a team key or project credential with
`events:listen`. Set `POLYMORFA_API_KEY` or `POLYMORFA_PROJECT_TOKEN`, or
select an authentication profile.

Pass the handler address and write the per-run local signing secret to a private
file:

```bash
polymorfa listen --project PROJECT_ID \
  --forward-to https://127.0.0.1:3000/webhooks \
  --forward-secret-out ./local-forwarding.secret \
  -H 'X-Local-Mode: test' --skip-verify --json
```

Forwarding requires the exact payload bytes. For events from a Number, enable
hosted message storage for that Number; message bodies are not retained by
default. If the body is unavailable, the listener reports `event_unavailable`
and stops forwarding with `forwarding_failed` instead of sending metadata in
its place. See [event payload availability](https://docs.polymorfa.com/development/event-streams#read-an-event)
for the other conditions that can make a body unavailable.

Verify the local signature before processing a forwarded body. For a
TypeScript handler using the [SDK development prerelease](https://docs.polymorfa.com/get-started/development-environment#install-the-typescript-sdk),
pass the unparsed request bytes, `Polymorfa-Local-Signature` header, and the
per-run secret to `webhooks.verifyLocal`:

```ts
import { readFile } from "node:fs/promises";
import { webhooks } from "@polymorfa/sdk";

const MAX_WEBHOOK_BYTES = 2 * 1024 * 1024;

// Read the raw body, or return null as soon as it passes the limit.
async function readRawBody(request: Request): Promise<Uint8Array | null> {
  if (Number(request.headers.get("content-length")) > MAX_WEBHOOK_BYTES) return null;
  const reader = request.body?.getReader();
  if (!reader) return new Uint8Array();
  const chunks: Uint8Array[] = [];
  let total = 0;
  for (;;) {
    const { done, value } = await reader.read();
    if (done) break;
    total += value.byteLength;
    if (total > MAX_WEBHOOK_BYTES) {
      await reader.cancel();
      return null;
    }
    chunks.push(value);
  }
  const body = new Uint8Array(total);
  let offset = 0;
  for (const chunk of chunks) {
    body.set(chunk, offset);
    offset += chunk.byteLength;
  }
  return body;
}

async function verifyForwardedEvent(request: Request) {
  const rawBody = await readRawBody(request);
  if (!rawBody) return new Response(null, { status: 413 });
  const signature = request.headers.get("Polymorfa-Local-Signature") ?? "";
  const secret = (await readFile("./local-forwarding.secret", "utf8")).trim();
  return webhooks.verifyLocal({ body: rawBody, signature, secret });
}
```

`verifyLocal` rejects an invalid signature or a timestamp more than 300 seconds
from the handler's clock. Reject the request when verification fails. The sample answers `413` above
`MAX_WEBHOOK_BYTES` (2 MiB), a sample default you can raise. Do not
parse and reserialize the body before verification. The local signing secret is
separate from your production webhook secret.

`-H` adds a custom header to forwarded requests. Repeat it for more headers.
It cannot replace authentication, body framing, or Polymorfa signature headers.
The CLI does not echo rejected header values. Custom headers cannot cross an
origin-changing redirect. Keep secret values out of command arguments.

`--skip-verify` accepts a self-signed certificate only for a loopback HTTPS
forwarding destination. It does not change TLS verification for the Polymorfa
API or public forwarding destinations. Omit it when your handler has a trusted
certificate. `--json` prints JSONL records for listener transitions, including
received events; server heartbeats do not produce output records. Forwarding in
JSON or a noninteractive terminal requires `--forward-secret-out`.

## Read every page

For an endpoint that returns `page.nextCursor`, add `--paginate`. The CLI sends
each cursor back in the `cursor` query parameter. It stops if the API reports
more pages without a cursor, repeats a cursor, or exceeds `--max-pages` (100 by
default).

```bash
polymorfa api /platform/customers --surface platform --paginate
```

Human output prints each page as it arrives. `--json` prints one document with
`data` set to an array of page bodies. Its `metadata` contains the final
response's status and request ID, when present, plus the page count. Use
`--include` for human output that includes each response's metadata. To collect
those page results into one array, combine it with `--slurp`:

```bash
polymorfa api /platform/customers --surface platform --paginate --slurp --include
```

`--paginate` accepts GET requests only. Leave the `cursor` query parameter out
of the path when the CLI manages pagination.

## Filter or format a response

`--jq` runs a jq expression on each page. It prints strings without quotes and
preserves spaces and newlines inside string values:

```bash
polymorfa api /platform/customers --surface platform --paginate \
  --jq '.data[].id'
```

Use `--slurp` to give one array of page bodies to the expression instead:

```bash
polymorfa api /platform/customers --surface platform --paginate --slurp \
  --jq 'map(.data | length) | add'
```

`--template` accepts paths, `range`, `if`, and string literals. Quoted strings
can contain `}}` without closing the action:

```bash
polymorfa api /platform/customers --surface platform \
  --template '{{range .data}}{{.id}}{{"\\n"}}{{end}}'
```

`--jq`, `--template`, and `--json` are mutually exclusive. `--include` cannot
be combined with either filter. `--slurp` requires `--paginate`.

## Read WhatsApp analytics

Enable Analytics in the Console, then use a trusted credential with
`sessions:read`. Select a project and optional Number record UUID:

```bash
polymorfa analytics get --project "$PROJECT_ID" \
  --session-id "$NUMBER_ID" \
  --since 2026-09-01T00:00:00Z --until 2026-10-01T00:00:00Z --json
```

Omit `--session-id` to read all numbers in the project. A team key
can omit `--project` to read the team. A project credential stays inside its
project. `--since` and `--until` accept dates with an explicit timezone; the
maximum range is 366 days and the default is the previous 30 days.

The table shows activity, read and reply rates, response time and connection
problems. `--json` returns the full API response, including message-type and
length comparisons, calling-code and device shares, phone replies, customer
activity and the reply-queue snapshot. Preserve nullable rates and coverage
flags. Human output includes call answer rates, missed incoming calls, pickup
times and follow-up rates even when messaging telemetry is absent. JSON includes
call timing coverage, quality and error breakdowns, and per-number daily call
series. Disabled analytics returns no business aggregates.

See [WhatsApp analytics](https://docs.polymorfa.com/numbers/analytics) for measurement definitions.

## Export analytics metrics

Use the CLI source build to write a collector-compatible snapshot:

```bash
polymorfa analytics metrics --project "$PROJECT_ID" \
  --window-hours 24 --format openmetrics > analytics.om
```

Add `--session-id` to select a number record UUID or `--segments` for metadata
breakdowns. `--json` wraps the metrics text and HTTP metadata in a JSON response.
The default output is metrics text. Published CLI versions may precede this command.

These are overlapping-window gauges, not monotonic counters. See
[collector setup](https://docs.polymorfa.com/numbers/analytics/collectors) for authentication, metric
definitions and the OpenTelemetry configuration.

### Observed phone intervals

Analytics responses include phone activity duration sums, completed span counts,
quiet-gap sums and counts, and their averages in `accountActivity`. Series rows
include sums and counts for weighted comparisons. Activity series use hourly
buckets for ranges up to 48 hours and daily UTC buckets for longer ranges.
These observations do not measure phone power state or verified online/offline
time. Read the [interval definitions](https://docs.polymorfa.com/numbers/analytics#phone-polymorfa-and-customer-activity)
before interpreting them. The JSON output preserves missing averages as `null`.

## Spending limits and funding order

Use a team key with `billing:read` for reads or `billing:manage` for
writes. Writes require Pay-As-You-Go. Project and client credentials cannot
access these controls.

```bash
polymorfa api /platform/billing/limits --surface platform
polymorfa api /platform/billing/priorities --surface platform
```

Use the revision in the response when changing a cap or priority. For project
or number order, send the complete highest-first list and the team-wide revision
to `PUT /platform/billing/priorities`. A stale or incomplete order fails without
partial changes. See [reorder priorities](https://docs.polymorfa.com/api/billing/reorder-billing-priorities)
and [set a limit](https://docs.polymorfa.com/api/billing/set-billing-limit) for request bodies.

### Resource financial controls

Use the team key with `billing:read` or `billing:manage` and a
project, customer or number UUID. Read a single resource before saving to obtain
`expectedBudgetRevision` and `expectedPriorityRevision`:

```bash
polymorfa api '/platform/billing/controls/customer/CUSTOMER_UUID' --surface platform
polymorfa api '/platform/billing/controls/customer/CUSTOMER_UUID' --surface platform -X PUT --input controls.json
```

`controls.json` contains `limitCredits`, `priority`, `expectedBudgetRevision` and
`expectedPriorityRevision`. A stale value returns a conflict without changing either
setting. `limitCredits: null` removes the cap. Real QuickLink creation accepts
`billingControls` in its JSON input; it requires a team financial credential and
Pay-As-You-Go. Testing and supplementary links reject initial financial controls.

### Mixed funding leaderboard

Read one project's priorities with `GET /platform/billing/priorities?projectId=PROJECT_UUID`.
Reorder its customers and real numbers together with `PUT /platform/billing/priorities`:

```json
{
  "scope": "resource",
  "projectId": "22222222-2222-4222-8222-222222222222",
  "resources": [
    { "scope": "number", "resourceId": "33333333-3333-4333-8333-333333333333" },
    { "scope": "customer", "resourceId": "44444444-4444-4444-8444-444444444444" }
  ],
  "expectedRevision": 5
}
```

Include every active customer and real number in the selected project. Use the
revision from its read; concurrent changes return 409. A higher number priority
outranks customer priority within its project. Project priority and all spending
caps still apply. Use the published client's raw request method for these calls.

## Stored group capabilities

CLI versions containing `group capabilities` read stored group settings with:

```bash
polymorfa group capabilities 9007199254740993 --session support --json
```

Use a server credential with `groups:read`. The linked number must be a current
group member and the team must have number-capabilities beta access. Unknown
configuration stays unknown; the command does not open the chat or fetch its
configuration. See [Number capabilities](https://docs.polymorfa.com/numbers/capabilities).

## Audience profiles beta

Use a team API key to call the
[audience profiles API](https://docs.polymorfa.com/campaigns/audience-profiles):

```bash
polymorfa api '/platform/audience-profiles?limit=25' --surface platform
```

Reads require `campaigns:read`. Project and client tokens cannot access team
profiles. Writes and import creation require `campaigns:manage` and beta
enrollment. Deletion and import cancellation remain available after withdrawal.
Use `--input` for JSON writes and include the latest `expectedRevision` when
replacing or deleting a profile. An import replay key must identify the same
CSV, mapping and credential; cancellation preserves edits already committed.

Dedicated profile commands are not included in the CLI version installed above.
Use the API command and only parameters supported by your API version. See the
profile guide for request bodies, consent history, import reports and limits.

For example, inspect one profile or its consent history with an encoded phone:

```bash
polymorfa api '/platform/audience-profiles/%2B14155550123' --surface platform
polymorfa api '/platform/audience-profiles/%2B14155550123/consent?limit=25' --surface platform
polymorfa api '/platform/audience-profile-imports/JOB_ID' --surface platform
```

Profile and consent lists return `data` plus `page`; retain the cursor and any
supported filters on subsequent requests. Import reports use `data.state`:
`queued` means work is active, and `completed` or `cancelled` is terminal.
Imports accept 10 MiB and 10,000 rows, with one active import per team. A cancelled
import keeps rows already written. If the creation response is lost, repeat the
request with the same replay key, CSV, mapping and credential. The API returns
the existing import and its job ID. Do not create a new replay key for the retry.

Manage team keys and project tokens in the [Console](https://docs.polymorfa.com/development/api-keys).
The CLI does not provide commands to create, list or revoke those credentials.
Client-token operations remain available through the public API.

Treat every credential as an opaque string. Never parse it or assume a fixed length. Credential storage must support at least 512 characters, preferably unrestricted text. The CLI stores credentials in the operating-system keyring.
