# Developer guide: API, client and local MCP

## What this is

NeoNumber adds before-and-after evaluation to your product. You send an idea in the person's
own words; NeoNumber reads it, the person confirms the reading, and a Review judges that exact
version: a Score out of 100 with its range, why, the biggest uncertainty and a useful next test.
Before the work starts the person agrees what to measure; afterwards a Result records what
happened, per objective. Reviews and Results are never combined into one number, and a Score is
a judgment, never a probability.

Four surfaces carry it: the HTTP API (contract 1.1), a typed TypeScript client
(`@neonumber/client`), a local MCP server for AI assistants, and embeddable public scorecards.
This is a private beta: the API origin and keys come with an invitation. The current limits are
under [Beta status](#beta-status).

## How to authenticate

A workspace owner opens **Workspace settings → Developer keys**, selects at least one permission
and only the ones needed, sets an expiry of 1 to 90 days, and saves the one-time secret directly
to the application's secret store. A Platform Key acts for its creator: when that person is
revoked or leaves the workspace, the key stops working. Admin and member roles cannot manage
keys. Never paste credentials into an assistant conversation.

Every request carries three headers:

```http
Authorization: Bearer <Platform Key>
NeoNumber-Contract-Version: 1.1
Idempotency-Key: <one saved key per write>
```

Select contract **1.1** on every request. Every response echoes the version it was served under
in `NeoNumber-Contract-Version`; a request that omits the header is served 1.0 for compatibility
and its answer carries `Deprecation: true`.

Supply `NEONUMBER_API_ORIGIN` (the API origin from your invitation, not the web
`/api/neonumber` proxy) and `NEONUMBER_PLATFORM_KEY`, or `NEONUMBER_PLATFORM_KEY_FILE` naming
a private file that holds the key, through your private process environment. The OpenAPI
`servers` entry is an example origin; the real one is provided with the invitation. HTTPS is
required except on loopback. The examples do not prompt for, print or persist those values.

## Your first call

Save an idea, read its reading, request its Review and read the Review:

```sh
curl -sS -X POST "$NEONUMBER_API_ORIGIN/v1/ideas" \
  -H "Authorization: Bearer $NEONUMBER_PLATFORM_KEY" \
  -H "NeoNumber-Contract-Version: 1.1" \
  -H "Idempotency-Key: idea-0001" \
  -H "Content-Type: application/json" \
  -d '{"schema_version":"idea-create.v1","advisory_only":true,"gate_authority":"none",
       "words":"A two-week referral offer for existing customers.","attachments":[]}'
```

Save `version` and `reading_id`. Read `GET /v1/readings/{reading_id}` until `state` is `ready`.
To confirm or correct the reading, send the person's corrections to
`POST /v1/ideas/{id}/versions`; it saves a new version. Then request the Review of that exact
version with `POST /v1/ideas/{id}/score` (`Prefer: respond-async` is the default): the answer
names the Review's `Location` and a `Retry-After`; read the Location until the Review is
written.

`examples/api/quickstart.sh` (curl and jq; the key never reaches the command line) and
`examples/api/quickstart.ts` (the typed client) run these steps from environment variables
only.

## Complete the workflow

Replace the constructed words, objective definitions, evidence and dates with the user's actual
intent; never report demonstration data as observed outcomes. The browsable reference at
`/developers/reference` has an anchor for each operation id.

| Step | Operation ID | Save and inspect |
|---|---|---|
| Submit words | `post_v1_ideas` | Exact Idea/version and reading ID |
| Find saved Ideas | `get_v1_ideas` | Exact versions; follow `next_cursor` until null |
| Wait for reading | `get_v1_readings_id` | Explicit state; ready is not a Review |
| Confirm or correct | `post_v1_ideas_id_versions` | Prior version, reason and user-confirmed fields; new version |
| Request judgment | `post_v1_ideas_id_score` | Same exact version, mutation identity and pending Location |
| Read judgment | `get_v1_reviews_id` | Review, uncertainty and Method; Score is not probability |
| Compare | `post_v1_comparisons` / `get_v1_comparisons_id` | Two or three exact versions under common conditions |
| Propose definitions | `post_v1_ideas_id_measurement_proposals` / `get_v1_measurement_proposals_id` | Proposed objectives; proposal is not registration |
| Register | `post_v1_measurement_plans` | Explicit user agreement to definitions and dates before start |
| Read definitions | `get_v1_measurement_plans_id` | Receipt and immutable definitions |
| Report outcomes | `post_v1_projects_id_results` or `post_v1_strategies_id_results` | Actual evidence, sources and component states |
| Read/correct outcome | `get_v1_results_id` / `post_v1_results_id_corrections` | Old Result stays readable; correction supersedes it |
| Follow work | `get_v1_measurement_tasks`, `get_v1_records`, `get_v1_records_id`, `get_v1_tenants_me_result_corrections` | Cursors and exact artifact references |
| Run a campaign | `post_v1_campaigns`, `get_v1_campaigns`, `get_v1_campaigns_id`, `post_v1_campaigns_id`, `get_v1_campaigns_id_snapshot`, `get_v1_campaigns_id_benchmark` | Campaign id and revision; the benchmark is a Result, never a Score |
| Follow events | `get_v1_events` | Signed events, oldest first; save `next_cursor` after handling the page |

Decimal quantities are strings, never binary floating-point values. Bodies carry their declared
`schema_version`, `advisory_only: true` and `gate_authority: "none"`. Retrospective measurement
remains retrospective; incomplete outcomes remain pending or not established.

## Errors, retries and pagination

Branch on the HTTP status, then the Error's `code`, then its `retry`. Every refusal has one
shape:

```json
{
  "schema_version": "error.v1",
  "advisory_only": true,
  "gate_authority": "none",
  "code": "conflict",
  "message": "idempotency_key_conflict: this key was used with a different body",
  "retry": "same_key_only",
  "request_id": "request-0001"
}
```

- **401** invalid, expired or revoked credential; **403** permission or membership; **404**
  unavailable artifact.
- **402** with `code: "budget_refused"`: a workspace or key limit refused the work. The registered
  reason, such as `platform_key_ceiling_exceeded` or `billing_cap_exceeded`, is the prefix of
  `message`. Never bypass a budget refusal by retrying with another key.
- **409** with `code: "conflict"`: the same `Idempotency-Key` was used with a different body, or
  the state changed. The same key with the same body replays the saved answer.
- **202**, or an Error with `code: "not_yet"` (a Review or Comparison still being written
  answers 503): the work is saved and pending. Read the `Location` after `Retry-After`.

A refusal is not transient by default: do not retry it with fresh mutation identities. Network
failure after submission is ambiguous: inspect saved work, then retry the same body and key if
necessary. A changed body needs a new explicit intent.

Lists are snapshots of 50 per page. Pass `next_cursor` as `after` (as `cursor` on the Result
corrections feed) and follow it until it is null. Store correction cursors only after applying
that page. Measurement pages are snapshots, not change feeds.

The event feed (`GET /v1/events`) is the one change feed: its `next_cursor` is never null. Follow
it while `has_more` is true, then keep the last one and poll with it later. A cursor is bound to
the workspace that received it (another workspace's is refused) and expires after the
workspace's retention window (`cursor_expired`: start again without `after`).

## TypeScript client

`packages/client` is `@neonumber/client`. Its operation names come from the generated contract
table, not handwritten URLs. A literal operation id checks the path parameters, query, body and
idempotency key and types the reply; any other string keeps the untyped call. `call` preserves
status, body, Location and Retry-After; `value(shape, request)` returns a validated artifact;
`client.wait(location, {attempts: 10, maxWaitMs: 30000})` polls within a bound. The client
follows only declared read operations on its configured origin, refuses redirects, and never
automatically resubmits a mutation.

Install it from the two tarballs provided with an invitation, in one command:
`npm install ./neonumber-contracts-0.0.0.tgz ./neonumber-client-0.0.0.tgz`. From a checkout,
`pnpm build`, then `pnpm --filter @neonumber/contracts pack` and
`pnpm --filter @neonumber/client pack`. The package README has create, wait and read examples.

The Node runner `examples/api/run.mjs` executes an explicit saved request
`{operation, params?, query?, body?, idempotencyKey?}`:

```sh
node examples/api/run.mjs examples/api/due-measurements.json
node examples/api/run.mjs examples/api/corrections.json
python examples/api/read.py
```

For a write, copy `examples/api/create-idea.json` to a private saved request file. Review the
words; replace the example idempotency key with one unique identity and keep that exact identity
with that exact body. Run deliberately:

```sh
node examples/api/run.mjs path/to/saved-request.json --allow-write
```

The write flag is an execution safeguard, not deployment or spending approval. Output contains
customer artifacts: treat it as workspace data, not public logs.

## Local MCP

`services/mcp` is a thin **stdio** server using the official SDK **1.32.2**, tested with its SDK
client using protocol **2025-11-25**. Read tools are exposed by default; mutation tools appear
only with `NEONUMBER_MCP_ALLOW_WRITES=1`. Each mutation additionally requires
`user_confirmed: true` and a saved `idempotency_key` for the exact body. This flag records the
caller's assertion of user intent; hosts must still obtain that intent. Every write is
append-only, so no tool is marked destructive. Hosts may omit the envelope constants
(`schema_version`, `advisory_only`, `gate_authority`); the server adds them and the client still
validates the full contract shape.

The 30-tool allowlist is `packages/client/src/catalogue.ts`. Each tool has a title and a
description written for the assistant: when to use it, which id it needs and where that comes
from, and what to call next.

| Tool | Operation |
|---|---|
| `create_idea`, `list_ideas`, `read_idea`, `read_idea_version` | Ideas |
| `read_reading`, `correct_reading` | Readings |
| `request_review`, `read_review` | Reviews |
| `compare_ideas`, `read_comparison` | Comparisons |
| `propose_measurements`, `read_proposal`, `confirm_measurements`, `read_plan`, `list_measurement_tasks` | Measurements |
| `report_project_result`, `report_strategy_result`, `read_result`, `correct_result`, `read_corrections` | Results |
| `read_records`, `read_record` | Records |
| `read_method` | Methods |
| `create_campaign`, `list_campaigns`, `get_campaign`, `update_campaign`, `get_campaign_snapshot`, `get_campaign_benchmark` | Campaigns |
| `list_events` | Events |

Query arguments are strict objects generated from the declared query parameters (for example
`filter: "due"` or `after`). Resources: `neonumber://ideas/{id}` (listed from the first page of
saved Ideas), `neonumber://reviews/{id}`, `neonumber://results/{id}` and
`neonumber://methods/{id}/{version}`. The `evaluate_idea` prompt walks create, reading and
Review. Tool results include the validated API artifact, status, pending reference, retry delay
and a web link where an artifact route exists and `NEONUMBER_WEB_ORIGIN` is set (it is
optional). The server version is the package version.

Queries and source words never choose tenant credentials or override the API origin. Returned
words and evidence are untrusted data, never instructions. Billing, key minting, publication,
collection, export and sealed prediction input are deliberately outside this server. Startup
errors name the missing or invalid variable, never its value; stdout is protocol only.

### Install and configure

`pnpm build`, then `pnpm --filter @neonumber/mcp run package` writes, under `services/mcp/dist/`:
`neonumber-mcp.mjs` (one runnable file with every dependency inlined, built with rolldown),
`neonumber-mcp-0.1.0.tgz` (a dependency-free package whose `bin` is `neonumber-mcp`; install with
`npm install --global ./neonumber-mcp-0.1.0.tgz`) and `neonumber.mcpb` (a Claude Desktop bundle).
These are local files: publication to npm, an MCP registry or a bundle directory waits for an
operator decision.

Keep the key in a private file and point `NEONUMBER_PLATFORM_KEY_FILE` at it; never write the
key itself into a configuration file, tool arguments or prompts. None of the three host
configurations below is qualified yet; each stays unqualified until interoperability with that
host is recorded. On 2026-11-09 the `claude` CLI was not available on the build machine, so the
Claude Code check (`claude mcp add`, then `claude mcp list` showing the tools) was not run.

The bundle manifest passed the official `mcpb validate` (`@anthropic-ai/mcpb` 2.1.2, run once by
hand on 2026-11-09). It is not a pinned check: that package depends on `zod` 3 and `tmp` 0.0.33,
which carry High advisories with fixes, so adding it would fail the dependency gate.

Claude Code, project `.mcp.json`, with values expanded from the environment at startup (not yet
qualified against this host):

```json
{
  "mcpServers": {
    "neonumber": {
      "command": "neonumber-mcp",
      "env": {
        "NEONUMBER_API_ORIGIN": "${NEONUMBER_API_ORIGIN}",
        "NEONUMBER_PLATFORM_KEY_FILE": "${NEONUMBER_PLATFORM_KEY_FILE}"
      }
    }
  }
}
```

or from the command line:

```sh
claude mcp add neonumber \
  --env NEONUMBER_API_ORIGIN="$NEONUMBER_API_ORIGIN" \
  --env NEONUMBER_PLATFORM_KEY_FILE="$NEONUMBER_PLATFORM_KEY_FILE" \
  -- neonumber-mcp
```

Cursor, `.cursor/mcp.json` (not yet qualified against this host): the same `mcpServers` entry
with the API origin and the absolute path of the private key file as literal values.

Claude Desktop (not yet qualified against this host): open `neonumber.mcpb`. Its manifest
declares the API origin, the Platform Key as a `sensitive` user setting, an optional web origin
and an "Allow writes" switch, and runs the bundled file with Node. Configured by hand instead,
the entry uses `NEONUMBER_PLATFORM_KEY_FILE`. Use an absolute Windows path with escaped
backslashes when appropriate.

Hosted HTTP MCP needs a separate scoped OAuth implementation with discovery, resource/audience
checks and no token passthrough, plus operator approval and actual host interoperability
qualification. A Platform Key is not that OAuth service.

## Embed a public record

A workspace owner publishes under **Workspace settings → Publication**: that consent covers the
Reviews and Results of that kind's future Ideas, and nothing is public without it. The
publication page shows each card's snippet: an iframe of `/embed/{scorecard_id}` (or
`/embed/results/{result_id}` for a Result) and a short inline script. The embed page posts only
its height to the host; the script accepts it only from the NeoNumber origin and only for the
frame that sent it, so the frame fits its content. No external script is loaded.

For your own layout, read `GET /v1/public/scorecards/{id}`, `GET /v1/public/results/{id}` or
`GET /v1/public/records/{id}` as JSON; they need no key. Corrections travel with the record: a
superseded Review links to the current one, and the Record lists both. Every public page and
embed ends with "Scored by NeoNumber. Campaign plans reviewed before launch and benchmarked
after. A judgment, not a chance of success." and a link to how it works.

## Staying in sync

Poll the event feed, `GET /v1/events?after=<saved next_cursor>`, with a key holding the
**events** permission. Each entry is a signed CloudEvent exactly as NeoNumber signed it (a Review
published; a Resolution published, finalized or corrected) and the time it was recorded. The
event carries references only: verify its signature with `GET /v1/verification-keys/{id}`, then
read the artifact it names under your own key. The feed holds no delivery state and sends
nothing anywhere; you pull it.

```sh
curl -sS "$NEONUMBER_API_ORIGIN/v1/events?after=$SAVED_CURSOR"   -H "Authorization: Bearer $NEONUMBER_PLATFORM_KEY"   -H "NeoNumber-Contract-Version: 1.1"
```

Omit `after` the first time to read the whole history. `examples/api/events.json` is the saved
request for the Node runner. Also follow the Result corrections cursor
(`get_v1_tenants_me_result_corrections`) and list due measurements with
`get_v1_measurement_tasks?filter=due`. Customer-configurable webhooks are future work, with no
date.

## Run locally without credentials

For contributors with a repository checkout, using the pinned tools from `pnpm run doctor`:

```sh
pnpm build
pnpm beta:demo
pnpm exec vitest run --config vitest.integration.config.ts services/mcp/src/stdio.integration.test.ts
```

`beta:demo` executes the same complete journey through the typed API client and the official
MCP client: create two Ideas, read/confirm their readings, request a Review, Compare, propose
measurements, register future definitions, report mixed outcomes, correct an outcome, read due
measurements and Records. Providers and time are constructed; the test does not establish
judgment quality. It also checks tenant isolation, expiry, revocation and reconnect with the
original mutation identity. The second command starts an actual stdio MCP child process against
an ephemeral local HTTP API and reconnects it, starts the single-file bundle from a key file, and
runs the TypeScript quickstart end to end. These fixtures are not deployable configuration and
need no real key. The executable walkthrough is `services/mcp/src/workflow.test.ts`.

## Campaign pilot workflow (contract 1.1)

Use `pnpm beta:demo` above for an executable Platform Key/MCP artifact workflow, which also runs
a campaign. In the web app, sign in to a workspace and open `/campaigns/new`. Through the API, a
signed-in member sends the chosen `NeoNumber-Workspace`; a Platform Key with the **campaigns**
permission acts in its own workspace and needs no workspace header (naming another workspace is
refused). Creating the alternatives also needs **ideas**. A key holding **campaigns** reads the
words of the Ideas its campaigns compare. All calls use `NeoNumber-Contract-Version: 1.1`. POSTs
keep the same `Idempotency-Key` and body on retry. Never paste actual tokens into a shared
transcript.

1. `POST /v1/ideas` for each alternative; confirm each reading with the existing version operation.
2. `POST /v1/campaigns` with `CampaignCreate`: name, objective, shared conditions, exact context
   labels, 2–3 version references and optional prior campaign. Review and compare the alternatives
   through existing operations. The web form assigns stable per-slot identities for partial retries.
3. `POST /v1/campaigns/{id}` with `CampaignUpdate`: expected revision, selected version,
   measurement plan, reminder preference and nullable learning. Link the confirmed plan before
   its start time. A stale revision conflicts; the plan/version freeze once linked.
4. Submit/correct the Result through the existing measurement APIs. Read
   `GET /v1/campaigns/{id}/benchmark`. `available` includes score, band, component positions and
   reference digest. `unavailable` names the reason and uses null, never zero, for a missing score.
5. Save `{learned, next_test}` in the campaign update after the agreed outcomes exist. Create the
   next cycle with `prior_campaign_id`. `GET /v1/campaigns/{id}/snapshot` contains history and
   authorized artifact links. `GET /v1/campaigns?after=…` follows its returned cursor.

Download one cycle at `/campaigns/{id}/export`, all cycles at `/campaigns/export`, and artifact
history from the existing Record export. No admitted reference is installed by default. See the
reference runbook for admission, exact profile definitions and
reproducibility. This is separate from public example data and from deployment approval.

## Beta status

Repository implementation, qualified with constructed providers. Nothing is deployed.
Deployment, live inference, spending changes and admission wait on the operator approvals
listed in docs/beta.md. Native iOS and hosted
MCP/OAuth are not built.

In the hosted beta (docs/beta.md) any invited, non-revoked tester is admitted,
and every private feature is on. A Platform Key acts for its creator: when that person is revoked
or leaves the workspace, the key stops working. Public publication is on, as the approved
beta scope names it: a workspace owner's consent publishes the Reviews and
Results of that kind's future Ideas, and nothing is public without it. Payments and connector
collection are off, and an operation that is switched off is refused before any handler work or
idempotent replay. Do not retry a refusal with fresh mutation identities. The complete OpenAPI
includes operations outside this beta; documentation does not grant capability. The local
constructed demo seeds its own billing state; it is not a production configuration.

In the beta nothing is charged: the key form asks no price, and the key's per-work price ceiling
never refuses beta work; the workspace's monthly cap and the service's daily model ceiling still
apply. Where payments are on (local mode only), the owner also sets a per-paid-work price
ceiling, and zero refuses new paid work; that ceiling is not a monthly allowance, and
workspace/service limits and subscription checks still apply. Revocation ends future access; it
does not cancel already accepted work. Membership removal also withdraws that person's keys.

The secret is displayed once, never available from the listing, and never retained in the
idempotency replay row. Replaying a mint returns the original key ID with `secret_once: null`.
If delivery was lost, revoke that key and create another. Hide the secret before screenshots.

The client, the MCP server and the Claude Desktop bundle are local packages; none is published
to a registry. The MCP host configurations above are unqualified until interoperability with
each host is recorded. Export and Activity require a customer session; a Platform Key does not
grant either, key management, billing or publication. Campaign cycles and the event feed need a
key created with the **campaigns** and **events** permissions (contract 1.1: send
`platform-key-create.v1.1`; the key is answered as `platform-key.v1.1`).
