# Nexus402 documentation, in full > Every Nexus402 docs page as Markdown, in reading order. The index is https://www.nexus402.dev/llms.txt; each page is also at its own URL with .md in place of the trailing slash. --- # How Nexus402 works > We host nothing. Creators keep their servers where they want them; we add the meter, and developers reach every tool through one key. Source: https://www.nexus402.dev/docs/how-it-works/ Nexus402 is a metering gateway for MCP tools. It sits between two parties who never need an account with each other: a **developer**, whose AI agent calls tools from an ordinary MCP client, and a **creator**, who runs the server that does the work. The gateway decides who may call, charges a fixed price per call from a wallet the developer funded in advance, forwards the call to the creator's own server, and keeps the books for both sides. *Diagram: The Nexus402 system. A developer's MCP client posts to the Nexus402 gateway, which checks the key, meters the call and records the charge, then forwards a signed request to the creator's own server and relays the result. Charges go through a queue to a worker that posts them to a double-entry ledger in PostgreSQL. Top-ups arrive through Stripe; creators are paid out through Stripe Connect. One remote MCP server for the developer; the creator's server stays wherever the creator runs it.* ## The parts | Part | What it does | | --- | --- | | The gateway (`api.nexus402.dev`) | One remote MCP server for every tool. Authenticates the key, rate-limits it, meters the call, signs and forwards it to the creator, checks the answer, and relays it. Answers `initialize`, `tools/list` and `ping` itself from the published catalogue | | The meter | Redis holds each wallet's spendable balance and each key's rolling 24-hour spend. One atomic script checks both and deducts the price, so two calls can never spend the same cent. If Redis is unreachable, every paid call is refused with 503 rather than let through | | The charge queue | Every charge is written to a durable queue, and the gateway waits for that write *before* contacting the creator. A charge that cannot be recorded is a refused call, never a free one | | The ledger | PostgreSQL, double-entry and append-only: database triggers refuse edits and deletes. A worker nets charges into five-minute rollups. It is the only source of truth; Redis is rebuilt from it | | The registry | Every published version, with its fixed price and endpoint. Gateways keep a copy in memory and refresh it about every five minutes, so no database is read on a call | | Stripe | Card top-ups into a developer's wallet (Checkout with 3D Secure, no automatic top-up), and payouts to creators through Stripe Connect | | The creator's server | Any HTTPS endpoint the creator runs, anywhere. It receives signed MCP `tools/call` requests and returns results. Nexus402 never hosts it, deploys it or holds its code | ## How creators bring their servers in A creator does not move anything onto our infrastructure. They publish a pointer to a server they already run, at a price, and the gateway starts sending it paid calls. In your Nexus402 account On your own server 1. Sign in creator role Google, GitHub or Apple. No password. (in your Nexus402 account) 2. Claim a handle get nx_crt_ key Your name in every tool's address. The key is shown once. (in your Nexus402 account) 3. Build your endpoint A starter kit in your language checks each request is ours. (on your own server) 4. Host it anywhere, HTTPS Any host that serves HTTPS. Nothing of ours to install. (on your own server) 5. Publish price + proofs Set a fixed price per call; we check the endpoint answers. (in your Nexus402 account) 6. Get called metered, paid Each call is charged up front; you are owed your share. (in your Nexus402 account) Then, on every paid call 1. An agent calls with its key 2. Nexus402 charges the price, signs the request 3. Your endpoint checks the signature, answers 4. You are owed your share of every paid call From sign-in to your first paid call: two steps in your account, two on your own server, then publish and get called. 1. **Sign in** with Google, GitHub or Apple and take the creator role. 2. **Claim a handle**, the namespace every tool lives under (`acme/…`). The answer carries the creator key, `nx_crt_…`, shown once, which every forwarded call carries so the server knows it came from us. 3. **Build the endpoint**: a small HTTPS handler that checks our signature and key, runs the tool, and returns the MCP result with a proof header. See [Build a Server](https://www.nexus402.dev/docs/creators/build-a-server/). 4. **Host it anywhere** with a public HTTPS address on port 443: a VPS, a container platform, a serverless function. 5. **Publish a version** with its fixed price, endpoint, description and input schema. The first publish at a host proves the creator controls it with one static file, and every publish sends a signed "hello" the endpoint must answer. The version is callable within about five minutes. 6. **Get called.** Optionally give free calls per day, week or month to let developers try the tool. ## How developers connect through MCP A developer adds one remote MCP server to the client they already use — [Cursor](https://www.nexus402.dev/docs/developers/mcp-clients/cursor/), [Claude Code](https://www.nexus402.dev/docs/developers/mcp-clients/claude-code/), [OpenAI Codex](https://www.nexus402.dev/docs/developers/mcp-clients/codex/) or any other — at `https://api.nexus402.dev/v1/mcp`, with their key in the `X-Nexus-Api-Key` header. There is no SDK. The client's `tools/list` returns every published tool with its description and schema, free; the agent then calls whichever it needs. Each key has its own spend cap, so one agent's mistakes are bounded by what someone decided to give that key. See [Connect with MCP](https://www.nexus402.dev/docs/developers/mcp-clients/). ## How a tool call flows *Diagram: One paid tool call. The client sends a tools/call with its key. The gateway checks the key and rate limit and deducts the price in Redis, records the charge on a durable queue and waits for it, sends a signed request to the creator's server, checks the proof on the creator's answer, and streams the result back to the client as a JSON-RPC response. Nothing reaches the creator until step 3 succeeds; if it fails, the call is refused with 503 and nothing is charged.* 1. The client sends an MCP `tools/call` with the key. 2. The gateway verifies the key and its rate limit, finds the tool's version and price in memory, and deducts the price in one atomic step that also checks the wallet and the key's rolling 24-hour cap. A wallet or cap that cannot cover it is a `402`, and nothing is charged. 3. It writes the charge to the durable queue and waits for the acknowledgement. 4. It forwards the request to the creator's endpoint over HTTPS, signed with Ed25519 over the method, host, path, timestamp, correlation id and body hash, with the creator key beside it. 5. The creator's server answers with the tool's result and a proof header derived from that request, which shows the answer came from the endpoint that received it. 6. The gateway checks the proof before relaying a byte, wraps the result as the JSON-RPC response to the developer's request, and streams it back. A call may run for up to two minutes. The gateway reads only the envelope it needs to route and bill — the method and the tool name — and computes a one-way hash. It does not store or log the contents of tool calls. See the [Privacy Policy](https://www.nexus402.dev/privacy/). ## What a call costs, by outcome | What happened | Developer charged | Creator earns | | --- | --- | --- | | The creator answered `2xx` with a valid proof | Yes, the fixed price | Yes | | A free call (the tool's allowance, not yet used up) | No | No | | The creator answered `4xx` or `5xx` | No, refunded; the status and body are relayed | No | | The creator timed out, could not be reached, or answered `2xx` without a valid proof | No, voided; the developer gets `502` | No | | The response was cut off after it had started streaming | Yes: bytes reached the developer | Yes | | The wallet or the key's cap could not cover it | No; `402` | No | | Our own infrastructure could not authorize it | No; `503`, never a silent debit | No | ## How metering works - **Fixed prices.** A creator sets a price per call on each version, in integer micro-USD (up to $5.00 a call by default). A published version's price never changes; a new price is a new version. A price more than twice what unpinned callers were paying waits seven days before unpinned callers reach it. - **Pre-funded wallets.** Developers add funds by card before they spend. There is no automatic top-up, so the balance is the ceiling. - **Per-key caps.** Every key can carry a rolling 24-hour spend cap, checked in the same atomic step as the balance. - **Exactly once.** An `Idempotency-Key` makes a retry safe: a key that already paid for a call is refused with `422`, never charged twice. - **Free calls and trial credit.** A creator can give every account a number of free calls per UTC day, week or month. A new account may get trial credit from an operator offer, which pays only for those free calls and ends at the first top-up. Neither is money: a free call debits nothing and earns nothing. - **Settlement.** A worker posts charges to the ledger in five-minute rollups. The creator's share is the price less our margin, 10% today and effective-dated, so a change applies only from the date it takes effect. - **Payouts.** Earnings become withdrawable after holds that protect against chargebacks, from a $5.00 minimum, by Stripe Connect transfer, each withdrawal confirmed with an emailed code. See [Payouts](https://www.nexus402.dev/docs/creators/payouts/). ## What we handle, and what creators handle | Nexus402 handles | The creator handles | | --- | --- | | Developer accounts, keys, wallets, card top-ups, caps and rate limits | The server: its code, hosting, uptime, scaling and TLS certificate | | MCP discovery: `initialize`, `tools/list`, `ping`, from the published catalogue | The tool's behaviour, and its description and input schema | | Metering, the charge, refunds and voids, and idempotency | Choosing a price per version, and any free calls | | Signing every forwarded request, and checking every answer's proof | Verifying our signature and key, and returning the proof | | The ledger, settlement, holds and payouts | Connecting a Stripe account to be paid | | Marking an endpoint unhealthy: five failures in a row pause it for 30 seconds, and twenty de-list the version until it is re-published | Fixing the endpoint, and re-publishing a de-listed version | | Never storing or logging the contents of tool calls | Whatever the tool does with the arguments it receives, under the creator's own terms | > **Where to go next** > > **Calling tools?** [Developer quickstart](https://www.nexus402.dev/docs/developers/quickstart/), then [Connect with MCP](https://www.nexus402.dev/docs/developers/mcp-clients/). **Selling a tool?** [Build a Server](https://www.nexus402.dev/docs/creators/build-a-server/), then [Host and publish](https://www.nexus402.dev/docs/creators/build-a-server/publish/). --- # Glossary > Every Nexus402 term in one place, in plain words, each linked to the page that owns the detail. Source: https://www.nexus402.dev/docs/glossary/ **Nexus402** is a metering gateway for MCP tools. A developer's AI agent calls tools through one API key and pays a fixed price per call from a wallet funded in advance, with an optional spend cap on each key. Each tool runs on its creator's own server, and the creator is paid for every completed call. The terms below are the ones that matter for using it correctly. ### 402 Payment Required The HTTP status the gateway returns when the wallet behind a key, or that key's 24-hour cap, cannot cover a tool's price. Nothing is charged. [Error codes](https://www.nexus402.dev/docs/developers/errors/) ### API key (nx_dev_) The developer credential an MCP client sends in the X-Nexus-Api-Key header. It is shown once when created and stored only as a hash. An account can hold up to ten, each with its own optional cap. [Keys and caps](https://www.nexus402.dev/docs/developers/keys/) ### Cap (spend cap) An optional rolling 24-hour spend ceiling on one API key, checked in the same atomic step as the wallet balance. It is not a calendar day and not a monthly budget. [Keys and caps](https://www.nexus402.dev/docs/developers/keys/) ### Creator A person or company that runs an MCP server and publishes its tools on Nexus402 at a fixed price per call. Nexus402 never hosts, deploys or holds the creator's code. [Creator docs](https://www.nexus402.dev/docs/creators/) ### Creator handle The namespace every one of a creator's tools lives under, such as acme in acme/weather/forecast. A handle is never released or transferred to another account. [Creator quickstart](https://www.nexus402.dev/docs/creators/quickstart/) ### Credits What a developer buys to fund a wallet, denominated in US dollars. No fee is added: the wallet is credited exactly what the card is charged, and there is no automatic top-up. [Wallet](https://www.nexus402.dev/docs/developers/wallet/) ### Developer Someone whose AI agent calls tools through Nexus402 from an ordinary MCP client, with one API key and a wallet funded in advance. [Developer docs](https://www.nexus402.dev/docs/developers/) ### Double-entry ledger Nexus402's book of record, in PostgreSQL. Every charge posts a debit with matching credits, entries are never edited or deleted, and a correction is a new entry. [How Nexus402 works](https://www.nexus402.dev/docs/how-it-works/) ### Ed25519 signature Every call Nexus402 forwards to a creator's endpoint is signed with Ed25519 over the method, host, path, timestamp, correlation id and body hash, so the creator's server can check it came from Nexus402. [Verifying requests](https://www.nexus402.dev/docs/creators/verifying/) ### Fail closed (503) If the metering store cannot be reached, paid calls are refused with HTTP 503. A call is never let through unmetered. [How Nexus402 works](https://www.nexus402.dev/docs/how-it-works/) ### Free calls A number of calls a creator gives every account on a tool per UTC day, week or month, from 0 to 1,000. A free call charges nothing, earns nothing and does not count against the key's cap. [When you are charged](https://www.nexus402.dev/docs/developers/billing/) ### Idempotency key An Idempotency-Key header that makes a retry safe. A key that already paid for a tool call is single-use: replaying it is refused with HTTP 422 and is never charged twice. [Idempotency](https://www.nexus402.dev/docs/developers/idempotency/) ### Margin The share of a call's price Nexus402 keeps when it resells the call: 10% today. The creator is owed the rest as the wholesale price. [Settlement](https://www.nexus402.dev/docs/creators/settlement/) ### MCP (Model Context Protocol) The open protocol AI applications use to discover and call tools. Nexus402 is one remote MCP server, so Cursor, Claude Code, Codex and other MCP clients reach every published tool with one URL and one header. [Connect with MCP](https://www.nexus402.dev/docs/developers/mcp-clients/) ### Merchant of record Nexus402 sells each tool call in its own name, under Stripe. The creator is its supplier, owed a wholesale price for every completed call. [Settlement](https://www.nexus402.dev/docs/creators/settlement/) ### Micro-USD The unit every amount is counted in: one millionth of a US dollar. Amounts travel as JSON strings of integers, never as floating-point numbers. [Money format](https://www.nexus402.dev/docs/developers/money-format/) ### Proof (X-Nexus-Proof) A header a creator's server returns with every successful answer, showing it came from the server that received the call. A 2xx without a valid proof reaches the developer as a 502 and is not charged. [Verifying requests](https://www.nexus402.dev/docs/creators/verifying/) ### Rollup Charges are netted into five-minute rollups and posted to the ledger, rather than written one row per call. A wallet's balance and itemised entries catch up at the next rollup. [Settlement](https://www.nexus402.dev/docs/creators/settlement/) ### Tool One function a creator publishes, named handle/server/tool, such as acme/weather/forecast. Each has a fixed price per call and runs on the creator's own server. [Build a server](https://www.nexus402.dev/docs/creators/build-a-server/) ### Trial credit Credit a new account may get from an offer running when it signs up. It pays only for creators' free calls, is not balance, and ends at the first top-up. [When you are charged](https://www.nexus402.dev/docs/developers/billing/) ### Version Tools are published in immutable versions: a version's price and endpoint never change. A new price ships as a new version, and a retired version stops taking calls. [Versions](https://www.nexus402.dev/docs/creators/versions/) ### Wallet A developer's prepaid balance, funded with Credits. Each call is charged the tool's fixed price from it, and a call it cannot pay is refused with 402. [Wallet](https://www.nexus402.dev/docs/developers/wallet/) ### Wholesale price What Nexus402 owes the creator for a completed call: the call's price less the margin, rounded down to the micro-USD. [Settlement](https://www.nexus402.dev/docs/creators/settlement/) ### Withdrawal A creator's request to be paid what is withdrawable now, from a $5 minimum, through Stripe Connect. Earnings become withdrawable in stages because a card payment can be disputed for months; payouts reach the United States only today. [Payouts](https://www.nexus402.dev/docs/creators/payouts/) --- # Set up your agent > Connect Cursor, Claude Code or Codex in one step, and give your agent the rules it needs to use Nexus402 — or to build for it — correctly the first time. Source: https://www.nexus402.dev/docs/agents/ Two jobs, and this page covers both. **Developers** connect an agent to the gateway so it can call paid tools. **Creators** have an agent build the server that serves their tools. Either way the agent should know the contract, not guess it, so each job comes with a skill you can drop into the agent you already use. There is nothing to install and no SDK: these are a link, a command, a config entry and two text files. Every snippet reads your key from the `NEXUS402_API_KEY` environment variable. Set it first, with a key of its own for each agent so its spend cap bounds what that agent can spend: **Set your key (macOS or Linux; on Windows use setx)** ```bash export NEXUS402_API_KEY="nx_dev_..." ``` ## Install agent tools Paste this into Claude Code, Codex or Cursor. Your agent connects itself to Nexus402 and adds the skills, for whichever tool it is. **Prompt for your agent** ```text Set up Nexus402 for me in this coding agent. 1. Read https://www.nexus402.dev/docs/agents.md and work out which tool you are (Claude Code, Codex or Cursor). 2. Add the Nexus402 MCP server https://api.nexus402.dev/v1/mcp the way that page shows for your tool, sending the X-Nexus-Api-Key header from the NEXUS402_API_KEY environment variable. 3. Install the skills listed at https://www.nexus402.dev/.well-known/skills/index.json where your tool keeps skills or rules. Never write my key into a file, a commit or a reply. If NEXUS402_API_KEY is not set, stop and tell me to set it. Then check the connection lists tools, and tell me what you changed. ``` Connect the gateway, then add the two skills. **Terminal** ```bash claude mcp add --transport http --scope user nexus402 https://api.nexus402.dev/v1/mcp \ --header "X-Nexus-Api-Key: $NEXUS402_API_KEY" mkdir -p ~/.claude/skills/nexus402-tools && curl -fsSL https://www.nexus402.dev/.well-known/skills/nexus402-tools/SKILL.md -o ~/.claude/skills/nexus402-tools/SKILL.md mkdir -p ~/.claude/skills/nexus402-endpoint && curl -fsSL https://www.nexus402.dev/.well-known/skills/nexus402-endpoint/SKILL.md -o ~/.claude/skills/nexus402-endpoint/SKILL.md ``` Add the gateway to `~/.codex/config.toml`, then add the skills with `npx skills add https://www.nexus402.dev`. **~/.codex/config.toml** ```toml [mcp_servers.nexus402] url = "https://api.nexus402.dev/v1/mcp" env_http_headers = { "X-Nexus-Api-Key" = "NEXUS402_API_KEY" } tool_timeout_sec = 130 ``` Add to Cursor Opens Cursor and asks to add the gateway. Your key is read from `NEXUS402_API_KEY`. Or add it by hand to `~/.cursor/mcp.json`. Then add the skills with `npx skills add https://www.nexus402.dev`. **~/.cursor/mcp.json** ```json { "mcpServers": { "nexus402": { "url": "https://api.nexus402.dev/v1/mcp", "headers": { "X-Nexus-Api-Key": "${env:NEXUS402_API_KEY}" } } } } ``` Skills-only installs don't update automatically. **Terminal** ```bash npx skills add https://www.nexus402.dev ``` Every option reads your key from `NEXUS402_API_KEY`; none writes it into a file. [Learn more](https://www.nexus402.dev/docs/agents/) ## Connect in one step ### Cursor Add to Cursor Opens Cursor and asks to add the gateway. Your key is read from `NEXUS402_API_KEY`. If the button does nothing, add this to `~/.cursor/mcp.json` instead: **~/.cursor/mcp.json** ```json { "mcpServers": { "nexus402": { "url": "https://api.nexus402.dev/v1/mcp", "headers": { "X-Nexus-Api-Key": "${env:NEXUS402_API_KEY}" } } } } ``` ### Claude Code **Run once in a terminal** ```bash claude mcp add --transport http --scope user nexus402 https://api.nexus402.dev/v1/mcp \ --header "X-Nexus-Api-Key: $NEXUS402_API_KEY" ``` Your shell fills in the key when you run it, and Claude Code keeps it in your private `~/.claude.json`. Check it with `claude mcp list`. ### OpenAI Codex **~/.codex/config.toml** ```toml [mcp_servers.nexus402] url = "https://api.nexus402.dev/v1/mcp" env_http_headers = { "X-Nexus-Api-Key" = "NEXUS402_API_KEY" } tool_timeout_sec = 130 ``` Check it with `codex mcp list`. The full guides, with troubleshooting, are under [Connect with MCP](https://www.nexus402.dev/docs/developers/mcp-clients/). ## Many tools, small context: meta mode The address above lists every tool your key may call, each with its full schema, at the start of every session. With a large catalogue that is a lot of context. Use `https://api.nexus402.dev/v1/mcp/meta` instead, with the same key and header, and your agent sees four small tools: - `nexus402_search` finds tools by words, category, price or free calls, ranked by match and measured reliability. Free. - `nexus402_describe` shows one tool's arguments, examples, price, free calls left and how many paid calls your key's cap still allows. Free. - `nexus402_call` calls a tool by name. It is charged exactly like a direct call, never more than the `max_price_micro` it passes, and a refusal comes back as an error your agent can read and act on. - `nexus402_budget` shows the key's 24-hour cap, what it spent and what remains. Free. Tools your key used in the last week are listed directly beside the four, so a repeated task needs no search. > **Running an agent with no one approving calls** > > Give it a key with a low daily cap, a maximum price per call, and, if the work allows it, a list of tools. Those three are what bound an unattended agent, and only you can set them. A client that "always allows" > > nexus402_call > > allows every tool the key may call, so use the plain address if you want to approve tools one by one. ## Skills for your agent Each skill is a short file of rules, checked against the gateway's code on every build. Claude Code loads a skill when the task matches its description; Cursor applies a rule when it is relevant; Codex reads `AGENTS.md` in your repository. The quickest way to add both is the open `skills` tool, which reads the skills this site publishes at [`/.well-known/skills/index.json`](https://www.nexus402.dev/.well-known/skills/index.json) and asks which of your agents to install them into. It is not ours and installs nothing of ours but these two text files: **Add both skills to your agents** ```bash npx skills add https://www.nexus402.dev ``` Or add them by hand, per agent: | Skill | For | Files | | --- | --- | --- | | `nexus402-tools` | Developers whose agent calls paid tools | [Claude skill](https://www.nexus402.dev/.well-known/skills/nexus402-tools/SKILL.md) · [Cursor rule](https://www.nexus402.dev/docs/agents/rules/nexus402-tools.mdc) | | `nexus402-endpoint` | Creators whose agent builds their tool server | [Claude skill](https://www.nexus402.dev/.well-known/skills/nexus402-endpoint/SKILL.md) · [Cursor rule](https://www.nexus402.dev/docs/agents/rules/nexus402-endpoint.mdc) | ### nexus402-tools Use when calling tools through the Nexus402 MCP gateway, or when a Nexus402 call fails with 401, 402, 404, 422, 429, 502 or 503. Covers connecting, keys, idempotent retries, free calls and every refusal code. **Claude Code: install for every project** ```bash mkdir -p ~/.claude/skills/nexus402-tools && curl -fsSL https://www.nexus402.dev/.well-known/skills/nexus402-tools/SKILL.md -o ~/.claude/skills/nexus402-tools/SKILL.md ``` **Cursor: add as a rule in this project** ```bash mkdir -p .cursor/rules && curl -fsSL https://www.nexus402.dev/docs/agents/rules/nexus402-tools.mdc -o .cursor/rules/nexus402-tools.mdc ``` **Codex or any agent: paste into AGENTS.md** ```markdown # Calling tools through Nexus402 Nexus402 is one remote MCP server, `https://api.nexus402.dev/v1/mcp`, that lists every published tool and charges a fixed price per call to a pre-funded wallet. There is no SDK. ## Connecting - Send the key in the `X-Nexus-Api-Key` header. Read it from the `NEXUS402_API_KEY` environment variable. Never write the key into a file, a commit, a log or a reply, and never send it as `Authorization`: the gateway refuses an `nx_dev_` key there (`400 Authorization_Rejected`), because `Authorization` is passed through to the tool's creator. - `tools/list`, `initialize` and `ping` are free. Only `tools/call` is billed. - A tool is named `handle/server/tool`; clients may show it with underscores (`mcp__nexus402__handle_server_tool`) and still call the original name. The gateway also accepts that underscore form (`handle_server_tool`, the tool's listed name) on `tools/call`, billed exactly the same. ## Money - Each call costs the tool's fixed price, once. `X-Nexus-Price` on the answer is what it cost, in dollars (`0.05`); it is absent when nothing was charged. - A tool may give free calls per day, week or month. Its answers carry `X-Nexus-Free-Quota-Remaining`; a free call carries no `X-Nexus-Price`. - A failure before any output is never charged. Once a result has started streaming, the charge stands. ## Retrying safely - To make a call safe to retry, send `Idempotency-Key: ` with it. Reuse that key ONLY to retry the same call. - `422 Idempotency_Conflict` means that key already paid for a call. Do not retry it with the same key: nothing will be charged twice, and the original result is not replayed. Use a fresh key only for a genuinely new call. - Honour `Retry-After` on 429 and 503. Do not loop on 402: it will not pass until someone adds funds or raises the key's cap. ## Refusal codes - `402 Budget_Exhausted` (charged: No). X-Nexus-Required-Amount (and the body's required) is the call's full price in decimal dollars, not the shortfall. Add funds or raise that key's cap. - `429 Rate_Limited` (charged: No). Honour Retry-After wherever a 429 carries one. Retrying sooner meets the same window and wastes the attempt. - `429 key_rate_limited` (charged: No). Honour Retry-After, which is the seconds left in the window. Spread load across keys only if that reflects real separate workloads. - `502 Upstream_Unavailable` (charged: No). Retry. A failure after the response began is not a 502: the status stays 200, the payload_truncated trailer is sent, and the charge stands. - `503 Lock_Unavailable` (charged: No). Retry with backoff. A 503 is never a silent debit. - `422 Idempotency_Conflict` (charged: No). Check your call log for the first attempt. Use a fresh key for a new request; a key whose call was refunded may be retried. - `400 Authorization_Rejected` (charged: No). Put the tool's own credential there, never your Nexus key. - `404 Unknown_Tool` (charged: No). Check the name against GET /v1/tools. An unpublished tool is not listed there, and neither is a retired version. - `404 Unknown_Version` (charged: No). Drop the @v pin to resolve the highest published version, or pin one that GET /v1/tools still lists. - `405 Method_Not_Allowed` (charged: No). Read the Allow header and use the method it names. - `401` with `{"error":{"code":"unauthorized"}}`: the key is missing, wrong, revoked or expired. Some clients show this as a sign-in or OAuth prompt; the gateway does not use OAuth. Check `NEXUS402_API_KEY`. ## Reference - Developer docs: https://www.nexus402.dev/docs/developers/ - Building an agent in code (MCP SDKs, LangChain, OpenAI Agents SDK): https://www.nexus402.dev/docs/developers/frameworks/ - Every error code: https://www.nexus402.dev/docs/developers/errors/ - All docs as Markdown: https://www.nexus402.dev/llms-full.txt ``` ### nexus402-endpoint Use when building, changing or debugging an HTTPS endpoint that serves MCP tools through Nexus402. Covers the signed request, the hello, the X-Nexus-Proof header, the result shape, limits and publishing. **Claude Code: install for every project** ```bash mkdir -p ~/.claude/skills/nexus402-endpoint && curl -fsSL https://www.nexus402.dev/.well-known/skills/nexus402-endpoint/SKILL.md -o ~/.claude/skills/nexus402-endpoint/SKILL.md ``` **Cursor: add as a rule in this project** ```bash mkdir -p .cursor/rules && curl -fsSL https://www.nexus402.dev/docs/agents/rules/nexus402-endpoint.mdc -o .cursor/rules/nexus402-endpoint.mdc ``` **Codex or any agent: paste into AGENTS.md** ```markdown # Building a Nexus402 tool endpoint Nexus402 hosts nothing. The creator runs an HTTPS endpoint; the gateway meters calls and forwards each paid `tools/call` to it, signed. Start from the tested samples rather than from scratch: https://www.nexus402.dev/docs/agents/examples/server.mjs and https://www.nexus402.dev/docs/agents/examples/verify.mjs (Node 18+, no dependencies), or a tested starter kit in Node.js, TypeScript, Python, Go, PHP, Rust, Java, C# or Ruby at https://www.nexus402.dev/docs/creators/build-a-server/#starters (each downloads as https://www.nexus402.dev/downloads/starters/nexus402-.zip). ## What the endpoint receives - Always `POST` to the exact published URL. Body: the developer's MCP `tools/call` request, byte for byte. Dispatch on the LAST segment of `params.name` (`acme/text@v2/word_count` -> `word_count`). - `initialize`, `tools/list` and notifications never arrive: the gateway answers them from the published description and input schema. - Headers: `X-Nexus-Signature` (`ed25519:` + base64), `X-Nexus-Timestamp` (unix seconds), `X-Correlation-ID`, `X-Nexus-Creator-Key` (`nx_crt_`). ## Verifying - Signature: Ed25519 over six lines joined by `\n`, no trailing newline: method, the host you PUBLISHED (not the inbound Host header), path with query, timestamp, correlation id, lowercase hex SHA-256 of the RAW body. Public keys: `GET https://api.nexus402.dev/v1/signing-key`; accept any key listed. - Refuse a timestamp more than 60 seconds from now in either direction. - Compare `X-Nexus-Creator-Key` in constant time. Keep the key in an environment variable, never in the repository. ## The hello When a version is published, the gateway sends one signed `POST` with an EMPTY body and NO creator key. Verify its signature, skip the key check, run no tool, and answer `200` with the proof. Without this, publishing fails with `422 endpoint_hello_failed`. ## What the endpoint returns - `X-Nexus-Proof: sha256:` + unpadded base64url of SHA-256 over `nexus-endpoint-proof-v1\n\n\n`. Set it on EVERY answer to a verified request, before the status line. A `2xx` without a valid proof is voided: nobody is charged or paid. - On success, the BARE MCP result with `Content-Type: application/json`, for example `{"content":[{"type":"text","text":"4"}]}`. Never wrap it in `jsonrpc`/`id`: the gateway does, and a second envelope would nest. - `2xx` is a paid call, even with `"isError": true`. Any `4xx` or `5xx` refunds the developer; a proved `4xx` is never counted against the endpoint, a `5xx` always is. Twenty failures in a row de-list the version. - A developer never pays for your failure: when the tool itself fails, answer a `5xx`; when the request is wrong before any work, a `4xx`. Keep `"isError": true` (paid) for a call the caller's input made fail after the tool did work. ## Limits Headers within 5 s, no silence over 5 s, 120 s per call, 10 MiB response, HTTPS on port 443 to public addresses only, no redirects followed. ## Reference - Build a Server: https://www.nexus402.dev/docs/creators/build-a-server/ - Verifying a request: https://www.nexus402.dev/docs/creators/verifying/ - All docs as Markdown: https://www.nexus402.dev/llms-full.txt ``` The creator skill points at the two files our test suite runs against the gateway's real signer, so an agent can start from working code: [`server.mjs`](https://www.nexus402.dev/docs/agents/examples/server.mjs) and [`verify.mjs`](https://www.nexus402.dev/docs/agents/examples/verify.mjs). ## Docs your agent can read - **Copy for LLM** and **View as Markdown** sit under the title of every docs page. - Every docs page is also at its URL with `.md` in place of the trailing slash, for example [`/docs/developers/errors.md`](https://www.nexus402.dev/docs/developers/errors.md). - [`/llms.txt`](https://www.nexus402.dev/llms.txt) is the index, and [`/llms-full.txt`](https://www.nexus402.dev/llms-full.txt) is every docs page in one file. - When a call fails, [Every error code](https://www.nexus402.dev/docs/developers/errors/#ask-your-agent) has a ready prompt for each refusal. > **The skills are rules, not code** > > Nothing here runs on your machine but what you choose to run. The skill files are plain Markdown with no instructions to fetch or run anything; read them before you add them. --- # Call paid MCP tools > Pre-fund a wallet, mint one key, and point the MCP client you already use at the gateway. Source: https://www.nexus402.dev/docs/developers/ You pre-fund a wallet, mint one key, and point the MCP client you already use at the gateway. We authenticate the call, check it against your balance and that key’s 24-hour cap, charge a fixed price, route it to the tool, and stream the answer back. > **Nothing to install** > > There is no SDK, in any language, by design. The key goes in a header and everything else is the MCP you already speak — which also means there is no client library that can fall out of step with the gateway. New here? [**Start with the quickstart**](https://www.nexus402.dev/docs/developers/quickstart/) — four steps to a paid call. ## Everything in these docs ### Start here - [**Overview**](https://www.nexus402.dev/docs/developers/) What the gateway does for you, and what it costs. - [**Quickstart**](https://www.nexus402.dev/docs/developers/quickstart/) Fund a wallet, mint a key, make a paid call. Copy-paste. ### Connect with MCP - [**Connect with MCP**](https://www.nexus402.dev/docs/developers/mcp-clients/) One URL and one header in the client you already use. No SDK, nothing to host. - [**Cursor**](https://www.nexus402.dev/docs/developers/mcp-clients/cursor/) mcp.json, the key in an environment variable, and the 60-character name limit. - [**Claude Code**](https://www.nexus402.dev/docs/developers/mcp-clients/claude-code/) claude mcp add or .mcp.json, scopes, and checking it with claude mcp list. - [**OpenAI Codex**](https://www.nexus402.dev/docs/developers/mcp-clients/codex/) config.toml with env_http_headers, for the CLI, the IDE extension and the app. - [**Agent frameworks**](https://www.nexus402.dev/docs/developers/frameworks/) Agents built in code: the MCP SDKs, LangChain and the OpenAI Agents SDK, each example tested. - [**MCP Python SDK**](https://www.nexus402.dev/docs/developers/frameworks/python-mcp/) The official Python client, with the key header on its httpx client. - [**LangChain**](https://www.nexus402.dev/docs/developers/frameworks/langchain/) Every tool your key may call, loaded as LangChain tools. - [**OpenAI Agents SDK**](https://www.nexus402.dev/docs/developers/frameworks/openai-agents/) Nexus402 as one MCP server in an agent's mcp_servers. - [**MCP TypeScript SDK**](https://www.nexus402.dev/docs/developers/frameworks/typescript-mcp/) The official TypeScript client, with the header in requestInit. ### Keys and limits - [**Keys, caps and rotation**](https://www.nexus402.dev/docs/developers/keys/) Ten keys, an optional rolling 24-hour cap, immediate revocation. - [**Rate limits**](https://www.nexus402.dev/docs/developers/rate-limits/) What is metered, what a 429 means, and how to back off. ### Money - [**When you are charged**](https://www.nexus402.dev/docs/developers/billing/) The one case you pay for a failure, and why. - [**Idempotency**](https://www.nexus402.dev/docs/developers/idempotency/) A safe retry, and the 422 that refuses an unsafe one. - [**Money is a string**](https://www.nexus402.dev/docs/developers/money-format/) Integer micro-USD, and the 2^53 bug it prevents. - [**Funding and spend**](https://www.nexus402.dev/docs/developers/wallet/) Top-ups, receipts, and seeing where it went. ### Reference - [**Every error code**](https://www.nexus402.dev/docs/developers/errors/) Generated from the gateway's source, so it cannot fall behind. - [**Headers**](https://www.nexus402.dev/docs/developers/headers/) What you send, what you get back, what is never forwarded. - [**Alerts**](https://www.nexus402.dev/docs/developers/alerts/) Signed webhooks, Slack and Discord: the events, the signature and a tested verifier. ## What you can rely on - **A price you can see before you call.** Fixed per tool version, and a published version’s price can never change. - **A ceiling you set.** Your wallet balance bounds everything, there is no auto-top-up, and no heuristic of ours lowers a cap you chose. - **No charge for our failures.** A 402, 429 or 503 is never billed, and a tool that fails before delivering anything is refunded automatically. - **Your key never reaches a creator.** It is consumed at the gateway and stripped. - **Your payloads are not stored.** Nexus402 does not store or log the contents of tool calls. The gateway reads only the request envelope (method and tool name) to route and bill, and computes a one-way hash. See the [Privacy Policy](https://www.nexus402.dev/privacy/). --- # Your first paid call > Fund a wallet, mint a key, call a tool. Four steps, nothing to install. Source: https://www.nexus402.dev/docs/developers/quickstart/ Four steps to a paid call. You do not install anything. 1. **Sign in** with Google, GitHub or Apple and choose the **developer** role. 2. **Add funds.** There is no auto-top-up — the balance you add is the ceiling on what anything can spend. 3. **Mint a key.** It is shown **once**. Give it a 24-hour cap if you want one. 4. **Call a tool.** ## Try it in a minute Some tools give free calls, so your first call can cost nothing. The catalogue is public, so you can find them before you have an account: **1. Tools with free calls (no key needed)** ```bash curl -s https://api.nexus402.dev/v1/tools \ | jq -r '.tools[] | select(.free_calls) | "\(.name) \(.free_calls) free a \(.free_period)"' ``` Then sign in, mint a key and call one. A free call carries `X-Nexus-Free-Quota-Remaining` and no `X-Nexus-Price`. A new account can take free calls with trial credit when an offer is running; otherwise add funds first. See [When you are charged](https://www.nexus402.dev/docs/developers/billing/). **2. Call it, and see the free-call headers** ```bash curl -si https://api.nexus402.dev/v1/mcp \ -H "X-Nexus-Api-Key: $NEXUS402_API_KEY" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call", "params":{"name":"TOOL_NAME_FROM_STEP_1","arguments":{}}}' \ | grep -i -E "^x-nexus-(free-quota-remaining|price)|jsonrpc" ``` ## Your first call **POST /v1/mcp — curl** ``` curl -s https://api.nexus402.dev/v1/mcp \ -H "X-Nexus-Api-Key: nx_dev_..." \ -H "Content-Type: application/json" \ -d '{ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "acme/weather/forecast", "arguments": { "city": "Lisbon" } } }' ``` **POST /v1/mcp — Python** ``` import requests response = requests.post( "https://api.nexus402.dev/v1/mcp", headers={"X-Nexus-Api-Key": "nx_dev_...", "Content-Type": "application/json"}, json={ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "acme/weather/forecast", "arguments": {"city": "Lisbon"}, }, }, # 130s: the gateway's own hard timeout is 120s. timeout=130, ) if response.status_code != 200: raise RuntimeError(response.headers.get("X-Nexus-Error", "call failed")) # X-Nexus-Price is what this call cost, in decimal dollars ("0.05"). # It is absent when nothing was charged, such as on a free call. print(response.headers.get("X-Nexus-Price"), response.json()) ``` **POST /v1/mcp — Node.js** ``` const response = await fetch("https://api.nexus402.dev/v1/mcp", { method: "POST", headers: { "X-Nexus-Api-Key": "nx_dev_...", "Content-Type": "application/json", }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "acme/weather/forecast", arguments: { city: "Lisbon" }, }, }), }); if (!response.ok) { throw new Error(response.headers.get("X-Nexus-Error") ?? "call failed"); } // X-Nexus-Price is what this call cost, in decimal dollars ("0.05"). // It is absent when nothing was charged, such as on a free call. console.log(response.headers.get("X-Nexus-Price"), await response.json()); ``` **POST /v1/mcp — Go** ``` payload := []byte(`{"jsonrpc":"2.0","id":1,"method":"tools/call",` + `"params":{"name":"acme/weather/forecast","arguments":{"city":"Lisbon"}}}`) request, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.nexus402.dev/v1/mcp", bytes.NewReader(payload)) if err != nil { return err } request.Header.Set("X-Nexus-Api-Key", "nx_dev_...") request.Header.Set("Content-Type", "application/json") response, err := http.DefaultClient.Do(request) if err != nil { return err } defer response.Body.Close() if response.StatusCode != http.StatusOK { return fmt.Errorf("nexus: %s", response.Header.Get("X-Nexus-Error")) } // X-Nexus-Price is what this call cost, in decimal dollars ("0.05"). // It is absent when nothing was charged, such as on a free call. fmt.Println(response.Header.Get("X-Nexus-Price")) ``` **POST /v1/mcp — Rust** ``` let response = client .post("https://api.nexus402.dev/v1/mcp") .header("X-Nexus-Api-Key", "nx_dev_...") .json(&serde_json::json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": { "name": "acme/weather/forecast", "arguments": { "city": "Lisbon" } } })) .send() .await?; if !response.status().is_success() { let code = response.headers().get("x-nexus-error").cloned(); return Err(CallError::Refused(code)); } // X-Nexus-Price is what this call cost, in decimal dollars ("0.05"). // It is absent when nothing was charged, such as on a free call. let price = response.headers().get("x-nexus-price").cloned(); let body: serde_json::Value = response.json().await?; ``` **POST /v1/mcp — PHP** ``` true, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => [ "X-Nexus-Api-Key: nx_dev_...", "Content-Type: application/json", ], CURLOPT_POSTFIELDS => json_encode([ "jsonrpc" => "2.0", "id" => 1, "method" => "tools/call", "params" => [ "name" => "acme/weather/forecast", "arguments" => ["city" => "Lisbon"], ], ], JSON_THROW_ON_ERROR), ]); $body = curl_exec($handle); if ($body === false) { throw new RuntimeException(curl_error($handle)); } $payload = json_decode($body, true, 512, JSON_THROW_ON_ERROR); ``` That is standard MCP JSON-RPC. The only thing that is ours is the header. ## Finding tools to call The catalog is public and needs no key, so you can browse before you fund anything: **Browsing the catalog** ```bash # Every published tool, with its price and description curl -s https://api.nexus402.dev/v1/tools # One tool's input schema and example curl -s https://api.nexus402.dev/v1/tools/acme/weather/forecast ``` > **A price is known before you call** > > Every tool version has a fixed price in its catalog entry. You are never charged a variable or metered amount, and the price of a version you pinned can never change — a published version is immutable. ## What to read next - [Using an MCP client](https://www.nexus402.dev/docs/developers/mcp-clients/) — point the client you already have at the gateway. - [Keys and caps](https://www.nexus402.dev/docs/developers/keys/) — bound what any one key can spend in a day. - [Error codes](https://www.nexus402.dev/docs/developers/errors/) — what each refusal means and whether you were charged. --- # Connect with MCP > Use every tool in the catalogue from the MCP client you already use: one URL, one header, nothing to host. Source: https://www.nexus402.dev/docs/developers/mcp-clients/ This guide is for **developers**: you connect an MCP client to Nexus402 and call tools that creators built. You do not build or host an MCP server here — for that, see [Build a Server](https://www.nexus402.dev/docs/creators/build-a-server/). The whole catalogue is **one remote MCP server**, the gateway, reached over streamable HTTP. Your client sends MCP JSON-RPC to it with your key in one header; the gateway answers discovery itself, meters each tool call against your wallet, and forwards it to the creator's own server. Tool discovery, argument schemas and streaming work as they already do in your client. | Setting | Value | | --- | --- | | Server URL | `https://api.nexus402.dev/v1/mcp` | | Transport | Streamable HTTP. Every message is a `POST`; a `GET` is answered `405` with `Allow: POST`, as the transport allows, because the gateway pushes nothing on its own | | Authentication | The header `X-Nexus-Api-Key: nx_dev_…`. No OAuth | | SDK | None. Nothing to install means nothing that can version-skew against the gateway | ## Before you connect 1. **Sign in** with Google, GitHub or Apple and choose the developer role. 2. **Have something to spend.** Add funds to your wallet, or use trial credit if an offer was running when you signed up — it pays only for creators' free calls. See [Funding and spend](https://www.nexus402.dev/docs/developers/wallet/). 3. **Create a key** for this client. It is shown once. Give each client its own key with its own 24-hour spend cap, so one leaked key can never spend more than its cap. See [Keys, caps and rotation](https://www.nexus402.dev/docs/developers/keys/). ## Set up your client - [**Cursor**](https://www.nexus402.dev/docs/developers/mcp-clients/cursor/) — `mcp.json`, the key from an environment variable, and the 60-character name limit. - [**Claude Code**](https://www.nexus402.dev/docs/developers/mcp-clients/claude-code/) — `claude mcp add` or a committed `.mcp.json`, scopes, and `claude mcp list`. - [**OpenAI Codex**](https://www.nexus402.dev/docs/developers/mcp-clients/codex/) — `config.toml` with `env_http_headers`, shared by the CLI, the IDE extension and the app. ## Other clients **Connect your client — VS Code** ``` { "inputs": [ { "type": "promptString", "id": "nexus402-key", "description": "Nexus402 API key (nx_dev_...)", "password": true } ], "servers": { "nexus402": { "type": "http", "url": "https://api.nexus402.dev/v1/mcp", "headers": { "X-Nexus-Api-Key": "${input:nexus402-key}" } } } } ``` **Connect your client — Claude Desktop** ``` { "mcpServers": { "nexus402": { "command": "npx", "args": [ "-y", "mcp-remote", "https://api.nexus402.dev/v1/mcp", "--header", "X-Nexus-Api-Key:${NEXUS402_KEY}" ], "env": { "NEXUS402_KEY": "nx_dev_..." } } } } ``` **Connect your client — Windsurf** ``` { "mcpServers": { "nexus402": { "serverUrl": "https://api.nexus402.dev/v1/mcp", "headers": { "X-Nexus-Api-Key": "nx_dev_..." } } } } ``` **Connect your client — Any client** ``` # Any client, or none: check your key with tools/list, which is never billed. curl -s https://api.nexus402.dev/v1/mcp \ -H "X-Nexus-Api-Key: nx_dev_..." \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' ``` Where each one goes: - **VS Code** — `.vscode/mcp.json` in the workspace. The key is *prompted for* when the server first starts and is never written into the file, which is why this is the form to commit. - **Claude Desktop** — `claude_desktop_config.json` (Settings → Developer → Edit Config). It reaches a remote server through the `mcp-remote` bridge, so Node.js must be installed. The key sits in `env` and is substituted into the header, because an argument containing a space breaks on Windows. - **Windsurf** — `~/.codeium/windsurf/mcp_config.json`. Note the field is `serverUrl`, not `url`. > **If a client stops connecting, check the last tab first** > > These follow each client’s documented configuration, and client config formats change between releases. The **Any client** tab talks to the gateway directly, so it separates the two questions: if it answers, your key and the gateway are fine and the problem is the client’s config; if it does not, it is not the client. > > Treat the key like a password. A config file in a repository is a committed secret — prefer the VS Code form, which prompts for it, or an environment variable. And give each client its own key with its own spend cap, so one leaked key cannot spend more than its cap. ## How tools appear in your client `tools/list` returns the latest published version of every tool in the catalogue, each with its creator's description and input schema. A key scoped to some tools is shown only those. A tool's name is `handle/server/tool`, for example `acme/weather/forecast`. Clients rename tools for the model, because most accept only letters, digits, `_` and `-`: Claude Code and Codex show `mcp__nexus402__acme_weather_forecast`, and Cursor removes or replaces the slashes. The client still calls the original name, so nothing changes on the gateway. The gateway also accepts the underscore form, the tool's *listed name* (`acme_weather_forecast`, shown on each tool's catalogue page), and bills it exactly as the original. Through a client you reach the version an unpinned call reaches, normally the latest; pinning one (`acme/weather@v2/forecast`) is for direct requests. When a tool gives free calls, every answer from it carries `X-Nexus-Free-Quota-Remaining`, the free calls you have left this period, and a free call carries no `X-Nexus-Price`. See [When you are charged](https://www.nexus402.dev/docs/developers/billing/). ## Which methods are billed | Method | Billed | Notes | | --- | --- | --- | | `tools/call` | **Yes** | The only billed method. Charged once at the version's fixed price. A success is the JSON-RPC response to your request, with the creator's result inside; a refusal keeps its HTTP status and wire code | | `tools/list` | No | Discovery is free. Each tool comes with its own description and input schema | | `initialize` | No | Protocol negotiation | | `ping` | No | Liveness, answered by the gateway itself | | `notifications/*` | No | Acknowledged with `202` and no body, as the protocol requires | | Anything else | No | Never forwarded. Answered with HTTP 200 and the JSON-RPC error `-32602` (invalid params), as is a request with no `id` | ## Your own Authorization header If the tool needs its own credential — an API key for the service it wraps — send it in `Authorization` and the gateway forwards it untouched. The creator sees it; we do not inspect or store it. > **One refusal, and it protects you** > > An `Authorization` header carrying an `nx_dev_` token is refused with `400 Authorization_Rejected`. Forwarding it would hand your Nexus key to a creator, who could then spend your wallet. This is the one header value we will not pass through. ## Streaming Server-sent events work. The gateway relays creator output without buffering the whole response, so you see tokens as they are produced. A tool that goes quiet for five seconds is cut; a tool that keeps producing can run for up to two minutes. ## What we do with your payloads > **Tool-call contents are not stored** > > Nexus402 does not store or log the contents of tool calls. The gateway reads only the request envelope (method and tool name) to route and bill, and computes a one-way hash. See the [Privacy Policy](https://www.nexus402.dev/privacy/). --- # Cursor > One entry in mcp.json gives Cursor's agent every published tool, billed to your wallet. Source: https://www.nexus402.dev/docs/developers/mcp-clients/cursor/ You are connecting Cursor to the Nexus402 gateway, which is one remote MCP server. You install nothing and host nothing: Cursor speaks MCP over HTTPS to the gateway, and the gateway forwards each paid call to the creator who built the tool. If you want to build and sell a tool instead, see [Build a Server](https://www.nexus402.dev/docs/creators/build-a-server/). ## Prerequisites - A Nexus402 account, signed in with Google, GitHub or Apple, with the developer role. - Money to spend: a funded wallet, or trial credit if an offer is running when you sign up (it pays only for creators' free calls). See [Funding and spend](https://www.nexus402.dev/docs/developers/wallet/). - An API key. Create it under **Keys** in the app; it starts `nx_dev_`, is **shown once**, and needs a 24-hour spend cap. Give Cursor a key of its own, so its cap bounds what Cursor's agent can spend. See [Keys, caps and rotation](https://www.nexus402.dev/docs/developers/keys/). - A current version of Cursor. ## Configure the connection Cursor reads MCP servers from `mcp.json`: `~/.cursor/mcp.json` for every project, or `.cursor/mcp.json` inside one project. Add the gateway as a remote server with a `url` and your key in `headers`: **~/.cursor/mcp.json** ```json { "mcpServers": { "nexus402": { "url": "https://api.nexus402.dev/v1/mcp", "headers": { "X-Nexus-Api-Key": "${env:NEXUS402_API_KEY}" } } } } ``` The `${env:NEXUS402_API_KEY}` form reads the key from an environment variable when Cursor starts, so the file holds no secret and can be committed. Set the variable where Cursor will see it, then restart Cursor: **Set the key (macOS or Linux shell; on Windows use setx, then sign out and back in)** ```bash export NEXUS402_API_KEY="nx_dev_..." ``` - **Keep the name short.** Cursor limits the server name plus the tool name to 60 characters and filters out tools over that. `nexus402` leaves the most room for creators' tool names. - **Define it once.** If the same server appears in both the global and the project file, remove one: duplicate definitions are a known cause of headers going missing. - A key pasted directly in place of `${env:…}` also works. It is then a secret in a file, so keep that file out of version control. ## Verify the connection 1. Open Cursor's settings and find the MCP section. `nexus402` should be listed and switched on, with its tools. 2. In the agent chat, the gateway's tools appear under the available tools. 3. If it does not connect, open the Output panel (`Ctrl`/`Cmd`+`Shift`+`U`) and choose **MCP Logs**. To separate a key problem from a Cursor problem, ask the gateway directly. `tools/list` is never billed: **Check the key without Cursor** ```bash curl -s https://api.nexus402.dev/v1/mcp \ -H "X-Nexus-Api-Key: $NEXUS402_API_KEY" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' ``` A JSON list of tools means the key and the gateway are fine and anything left is Cursor's configuration. `{"error":{"code":"unauthorized"}}` with a 401 means the key is wrong, revoked or expired. ## Use the tools Ask the agent for something a tool does, or name the tool. Each tool comes with the creator's description and input schema, so the agent knows its arguments. Every tool you call through the gateway is billed at its fixed price per call, once, to the wallet behind the key; a tool with free calls costs nothing until they run out. - **Names are rewritten.** The gateway names a tool `handle/server/tool`, for example `acme/weather/forecast`. Cursor accepts letters, digits and underscores, so it shows the name with the slashes removed or replaced, and calls the original name for you. The gateway also accepts the tool's listed name, `acme_weather_forecast`. - **Which tools you see.** A key with no tool scope sees the latest published version of every tool. A key scoped to some tools sees only those. - **Cursor's tool approval** still applies: the agent asks before it runs a tool unless you have allowed it to run automatically. Every run is a paid call. ## Common errors | What you see | Likely cause | Fix | | --- | --- | --- | | An OAuth or sign-in prompt, or a red server | The gateway answered 401: the key is missing, wrong, revoked or expired. Cursor reacts to a 401 by trying OAuth, which the gateway does not use | Run the curl check above. Fix the key or the environment variable, then restart Cursor fully | | The server shows no tools | The variable is unset in the environment Cursor started from, or the key is scoped to no published tool | Start Cursor from a shell that has the variable, or paste the key in a local-only file. Check the key's tool scope | | "Some tools have naming issues and may be filtered out" | A server name plus tool name over 60 characters | Use a short server name such as `nexus402` | | A tool call fails with `Budget_Exhausted` (402) | The wallet cannot cover the call, or the key's 24-hour cap would be exceeded | Add funds or raise that key's cap. Nothing was charged | | `key_rate_limited` (429) | Too many requests on this key in its window | Wait the seconds in `Retry-After` | | `Upstream_Unavailable` (502) | The creator's endpoint failed or timed out | Retry later. You were not charged | > **Cursor changes faster than this page** > > This follows Cursor's documented configuration as of November 2026. If a release moves the settings, the gateway side does not change: the URL, the `X-Nexus-Api-Key` header and the curl check above stay the same. Every refusal code is on [Every error code](https://www.nexus402.dev/docs/developers/errors/). --- # Claude Code > One command, or one entry in .mcp.json, and Claude Code can call every published tool. Source: https://www.nexus402.dev/docs/developers/mcp-clients/claude-code/ You are connecting Claude Code to the Nexus402 gateway, which is one remote MCP server reached over HTTP. You install nothing and host nothing. If you want to build and sell a tool instead, see [Build a Server](https://www.nexus402.dev/docs/creators/build-a-server/). ## Prerequisites - Claude Code installed and signed in. - A Nexus402 account with the developer role, and a funded wallet or trial credit. See [Funding and spend](https://www.nexus402.dev/docs/developers/wallet/). - An API key (`nx_dev_…`, **shown once**) with its own 24-hour spend cap. A key per tool you connect keeps each one's spending bounded. See [Keys, caps and rotation](https://www.nexus402.dev/docs/developers/keys/). ## Configure the connection **For yourself, in every project** — add it once with the CLI: **Add the gateway for your user** ```bash claude mcp add --transport http --scope user nexus402 https://api.nexus402.dev/v1/mcp \ --header "X-Nexus-Api-Key: nx_dev_..." ``` The command stores the key in `~/.claude.json`. Leave out `--scope user` to add it for the current project only (the default, `local` scope, also private to you). **For a team, in the repository** — commit a `.mcp.json` at the project root that names an environment variable rather than the key. Each person sets their own key: **.mcp.json** ```json { "mcpServers": { "nexus402": { "type": "http", "url": "https://api.nexus402.dev/v1/mcp", "headers": { "X-Nexus-Api-Key": "${NEXUS402_API_KEY}" } } } } ``` **Each person, before starting Claude Code** ```bash export NEXUS402_API_KEY="nx_dev_..." ``` - `"type": "http"` is required: an entry with a `url` and no `type` is skipped. - Claude Code asks once before using servers from a project's `.mcp.json`. - Do not write `--header "X-Nexus-Api-Key: $NEXUS402_API_KEY"` on the command line expecting it to stay a reference: your shell expands it when you run the command, and the plain key is stored. - Watch for a trailing newline or space in a pasted key. Claude Code warns about whitespace in a header value; the gateway sees a different key. ## Verify the connection **Check it** ```bash claude mcp list # nexus402 should say: ✔ Connected claude mcp get nexus402 # details, and an Issue: line if it failed ``` Inside a session, `/mcp` shows the server's status and how many tools it offers, and can reconnect it. "Added" after `claude mcp add` only means the configuration was written; `claude mcp list` is what actually connects. To rule Claude Code out, ask the gateway directly; `tools/list` is never billed: **Check the key without Claude Code** ```bash curl -s https://api.nexus402.dev/v1/mcp \ -H "X-Nexus-Api-Key: $NEXUS402_API_KEY" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' ``` ## Use the tools Ask for what you need and Claude chooses a tool, or name one. Claude Code names each tool `mcp__nexus402__…` and replaces every character other than letters, digits, `_` and `-` with `_`, so the gateway's `acme/weather/forecast` appears as `mcp__nexus402__acme_weather_forecast`. The call still reaches `acme/weather/forecast`, and the gateway accepts `acme_weather_forecast`, the tool's listed name, as well. - Each call is billed once at the tool's fixed price, to the wallet behind the key. A tool with free calls costs nothing until they run out. - Claude Code asks permission before running an MCP tool unless you allow it; allowing `mcp__nexus402` allows every tool from the gateway, and every run is a paid call. - A key scoped to some tools sees only those. - Large results: Claude Code warns when a tool's output passes 10,000 tokens and caps it at 25,000 by default (`MAX_MCP_OUTPUT_TOKENS`). ## Common errors | What you see | Likely cause | Fix | | --- | --- | --- | | `! Needs authentication`, or a browser opens for sign-in | The gateway answered 401, and Claude Code treats a 401 as a server that wants OAuth. The gateway does not use OAuth: the key is missing, wrong, revoked or expired | Run the curl check. Fix the key or the variable, then `/mcp` to reconnect | | `✘ Failed to connect` | The URL is wrong, or a network or proxy blocks `api.nexus402.dev` | Compare the URL with the one above; run the curl check from the same machine | | A warning that a variable is not set | `NEXUS402_API_KEY` was not in the environment Claude Code started from. The literal text is then sent as the key | Export it, then start Claude Code from that shell | | `Budget_Exhausted` (402) in a tool result | The wallet cannot cover the call, or the key's 24-hour cap would be exceeded | Add funds or raise the cap. Nothing was charged | | `key_rate_limited` (429) | Too many requests on this key in its window | Wait the seconds in `Retry-After` | | `Upstream_Unavailable` (502) | The creator's endpoint failed or timed out | Retry later. You were not charged | > **Timeouts** > > A creator's tool can run for up to two minutes through the gateway. Claude Code's own limits are longer than that by default. If a server is slow to start, raise `MCP_TIMEOUT` (milliseconds) before launching Claude Code. --- # OpenAI Codex > One table in config.toml, shared by the Codex CLI, the IDE extension and the app. Source: https://www.nexus402.dev/docs/developers/mcp-clients/codex/ You are connecting Codex to the Nexus402 gateway, one remote MCP server reached over streamable HTTP. You install nothing and host nothing. The Codex CLI, its IDE extension and the desktop app read the same configuration, so one entry serves all three. If you want to build and sell a tool instead, see [Build a Server](https://www.nexus402.dev/docs/creators/build-a-server/). ## Prerequisites - Codex installed and signed in. - A Nexus402 account with the developer role, and a funded wallet or trial credit. See [Funding and spend](https://www.nexus402.dev/docs/developers/wallet/). - An API key (`nx_dev_…`, **shown once**) with its own 24-hour spend cap. See [Keys, caps and rotation](https://www.nexus402.dev/docs/developers/keys/). ## Configure the connection Add a server table to `~/.codex/config.toml`. `env_http_headers` maps a header to the *name* of an environment variable, so the key never sits in the file: **~/.codex/config.toml** ```toml [mcp_servers.nexus402] url = "https://api.nexus402.dev/v1/mcp" env_http_headers = { "X-Nexus-Api-Key" = "NEXUS402_API_KEY" } # A creator's tool may run for up to two minutes through the gateway; # Codex's own default per-tool limit is 60 seconds. tool_timeout_sec = 130 ``` **Set the key before starting Codex** ```bash export NEXUS402_API_KEY="nx_dev_..." ``` - **Edit the file rather than using `codex mcp add`.** Its `--url` form has a flag for a bearer token but none for a custom header, and the gateway's key is a custom header. - **Do not use `bearer_token_env_var`.** It sends the key as `Authorization: Bearer`, and the gateway refuses an `nx_dev_` key there with `400 Authorization_Rejected`, because `Authorization` is passed through to creators. - **If the variable is unset or empty, Codex silently sends no header.** The gateway then answers 401, which Codex reports as a login problem (below). - `http_headers = { "X-Nexus-Api-Key" = "nx_dev_..." }` also works, with the key in the file. Keep that file private. - A project `.codex/config.toml` is read only in a project you have marked trusted. ## Verify the connection **Check it** ```bash codex mcp list # nexus402 should be listed and enabled codex mcp get nexus402 # its URL and settings ``` In the Codex TUI or the app, `/mcp` shows each server and its tools. To rule Codex out, ask the gateway directly; `tools/list` is never billed: **Check the key without Codex** ```bash curl -s https://api.nexus402.dev/v1/mcp \ -H "X-Nexus-Api-Key: $NEXUS402_API_KEY" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' ``` ## Use the tools Ask Codex for what you need, or name the tool. Codex names each tool `mcp__nexus402__…` and replaces every character other than letters, digits and `_` with `_` — hyphens included — so `acme/weather/forecast` appears as `mcp__nexus402__acme_weather_forecast`. The call still reaches the original name, and the gateway accepts the tool's listed name, `acme_weather_forecast`, as well. Two names that clean to the same text get a short hash suffix to tell them apart. - Each call is billed once at the tool's fixed price to the wallet behind the key; a tool with free calls costs nothing until they run out. - `enabled_tools` and `disabled_tools` in the server table narrow what Codex offers the model, by the gateway's tool name. For a limit the gateway enforces, scope the key instead. - `enabled = false` switches the server off without deleting it. ## Common errors | What you see | Likely cause | Fix | | --- | --- | --- | | "The nexus402 MCP server is not logged in. Run `codex mcp login nexus402`." | The gateway answered 401. It does not use OAuth, so `codex mcp login` will not help: the key is missing, wrong, revoked or expired, or the variable was not set | Run the curl check. Export `NEXUS402_API_KEY` in the shell Codex starts from | | "timed out after N seconds" | The connection did not finish within `startup_timeout_sec` (10 s by default) | Check the network path to `api.nexus402.dev`; raise `startup_timeout_sec` if it is only slow | | A tool call times out after 60 seconds | Codex's default `tool_timeout_sec` is shorter than the gateway's two minutes | Set `tool_timeout_sec` as in the example | | `Authorization_Rejected` (400) | The key was sent as a bearer token | Use `env_http_headers`, not `bearer_token_env_var` | | `Budget_Exhausted` (402) | The wallet cannot cover the call, or the key's 24-hour cap would be exceeded | Add funds or raise the cap. Nothing was charged | | `Upstream_Unavailable` (502) | The creator's endpoint failed or timed out | Retry later. You were not charged | > **If the server is ready but the model sees no tools** > > Codex has open reports of a streamable HTTP server that connects and lists tools while the agent is offered none. If `/mcp` lists the gateway's tools, the gateway side is working; update Codex and restart it. --- # Agent frameworks > Call Nexus402 tools from an agent you build in code. The framework's own MCP client is the integration: one URL, one header, nothing of ours to install. Source: https://www.nexus402.dev/docs/developers/frameworks/ Every example below connects to `https://api.nexus402.dev/v1/mcp` over streamable HTTP, sends your key in the `X-Nexus-Api-Key` header, lists the tools the key may call, and calls the one you name in `NEXUS402_TOOL`. **A call to a paid tool is charged to your wallet.** If you name none, nothing is called. Each is run against a test gateway at the version shown, so a framework release that changes how headers are passed is caught before you meet it. > **Careful** > > Keep the key in the > > NEXUS402_API_KEY > > environment variable, never in code or a committed file. Give each agent its own key with a 24-hour spend cap and, if it chooses tools on its own, a maximum price per call. See > > Keys, caps and rotation > > . For an agent that should find tools itself instead of loading every schema, use `https://api.nexus402.dev/v1/mcp/meta` with the same key: see [agents](https://www.nexus402.dev/docs/agents/). A call your wallet cannot pay for is refused with HTTP `402` and nothing is charged; each example prints `call refused` and exits with code 2. ## MCP Python SDK Python, `mcp` 1.30.0 (tested). Give the SDK an httpx.AsyncClient that carries the header. [Its own page](https://www.nexus402.dev/docs/developers/frameworks/python-mcp/). ``` pip install -r requirements.txt export NEXUS402_API_KEY=nx_dev_... # The tool to call, by its name in the marketplace. A paid tool is charged. export NEXUS402_TOOL='' python main.py ``` ``` """Call a Nexus402 tool with the official MCP Python SDK (ADR-0236). The key comes from NEXUS402_API_KEY and travels in the X-Nexus-Api-Key header. It is never written in code. NEXUS402_TOOL names the tool to call (required: a call is charged) and NEXUS402_ARGS its JSON arguments. """ import asyncio import json import os import sys import httpx from mcp import ClientSession from mcp.client.streamable_http import streamable_http_client URL = os.environ.get("NEXUS402_MCP_URL", "https://api.nexus402.dev/v1/mcp") TOOL = os.environ.get("NEXUS402_TOOL", "") def refusal(error: BaseException) -> httpx.HTTPStatusError | None: """The HTTP refusal inside an error, however deeply the SDK grouped it.""" if isinstance(error, httpx.HTTPStatusError): return error if isinstance(error, BaseExceptionGroup): for inner in error.exceptions: found = refusal(inner) if found is not None: return found return None async def main() -> int: # The SDK raises an HTTP refusal (a 402 when the wallet cannot pay) from # its transport's task group, so it surfaces here, as an ExceptionGroup, # rather than from call_tool. try: return await call() except Exception as error: refused = refusal(error) if refused is None: raise print(f"call refused: HTTP {refused.response.status_code}") return 2 async def call() -> int: headers = {"X-Nexus-Api-Key": os.environ["NEXUS402_API_KEY"]} async with httpx.AsyncClient(headers=headers, timeout=60) as http: async with streamable_http_client(URL, http_client=http) as (read, write, _): async with ClientSession(read, write) as session: await session.initialize() tools = (await session.list_tools()).tools print(f"{len(tools)} tools listed") args = json.loads(os.environ.get("NEXUS402_ARGS", "{}")) try: result = await session.call_tool(TOOL, args) except Exception as error: # a 402 or another refusal print(f"call refused: {error}") return 2 if result.isError: print(f"call refused: {result.content}") return 2 for block in result.content: print(getattr(block, "text", block)) return 0 if __name__ == "__main__": # Never a default: a call is charged, and you choose who is paid. if not TOOL: sys.exit( "Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. " "A call to a paid tool is charged to your wallet." ) sys.exit(asyncio.run(main())) ``` ## LangChain (Python) Python, `langchain-mcp-adapters` 0.3.2 (tested). Put the header in the connection's headers; every tool the key may call becomes a LangChain tool. [Its own page](https://www.nexus402.dev/docs/developers/frameworks/langchain/). ``` pip install -r requirements.txt export NEXUS402_API_KEY=nx_dev_... # The tool to call, by its name in the marketplace. A paid tool is charged. export NEXUS402_TOOL='' python main.py ``` ``` """Call a Nexus402 tool through LangChain's MCP adapters (ADR-0236). The adapters turn every tool the key may call into a LangChain tool, so an agent built with LangChain or LangGraph can use them directly. Here one is invoked by hand: the one NEXUS402_TOOL names (required: a call is charged). The key comes from NEXUS402_API_KEY, never from code. """ import asyncio import json import os import sys from langchain_mcp_adapters.client import MultiServerMCPClient URL = os.environ.get("NEXUS402_MCP_URL", "https://api.nexus402.dev/v1/mcp") TOOL = os.environ.get("NEXUS402_TOOL", "") def routing_name(tool) -> str: """The tool's routing name (acme/weather/forecast), when the list names it by its MCP-safe listed name (acme_weather_forecast, ADR-0264) and the adapters keep the row's _meta. So NEXUS402_TOOL may be either spelling.""" meta = (getattr(tool, "metadata", None) or {}).get("_meta") return meta.get("nexus402/name", "") if isinstance(meta, dict) else "" async def main() -> int: client = MultiServerMCPClient( { "nexus402": { "transport": "streamable_http", "url": URL, "headers": {"X-Nexus-Api-Key": os.environ["NEXUS402_API_KEY"]}, } }, handle_tool_errors=False, ) tools = await client.get_tools() print(f"{len(tools)} tools listed") tool = next(t for t in tools if TOOL in (t.name, routing_name(t))) args = json.loads(os.environ.get("NEXUS402_ARGS", "{}")) try: result = await tool.ainvoke(args) except Exception as error: # a 402 or another refusal print(f"call refused: {error}") return 2 print(result) return 0 if __name__ == "__main__": # Never a default: a call is charged, and you choose who is paid. if not TOOL: sys.exit( "Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. " "A call to a paid tool is charged to your wallet." ) sys.exit(asyncio.run(main())) ``` ## OpenAI Agents SDK (Python) Python, `openai-agents` 0.25.0 (tested). Put the header in MCPServerStreamableHttp's params, then pass the server to an Agent's mcp_servers. [Its own page](https://www.nexus402.dev/docs/developers/frameworks/openai-agents/). ``` pip install -r requirements.txt export NEXUS402_API_KEY=nx_dev_... # The tool to call, by its name in the marketplace. A paid tool is charged. export NEXUS402_TOOL='' python main.py ``` ``` """Call a Nexus402 tool through the OpenAI Agents SDK's MCP server (ADR-0236). Pass the same server to an Agent (`Agent(..., mcp_servers=[server])`) and the model can call any tool the key allows. Here one is called directly, so the example needs no model: the one NEXUS402_TOOL names (required: a call is charged). The key comes from NEXUS402_API_KEY, never from code. """ import asyncio import json import os import sys from agents.mcp import MCPServerStreamableHttp URL = os.environ.get("NEXUS402_MCP_URL", "https://api.nexus402.dev/v1/mcp") TOOL = os.environ.get("NEXUS402_TOOL", "") async def main() -> int: params = {"url": URL, "headers": {"X-Nexus-Api-Key": os.environ["NEXUS402_API_KEY"]}} async with MCPServerStreamableHttp(params=params, name="nexus402") as server: tools = await server.list_tools() print(f"{len(tools)} tools listed") args = json.loads(os.environ.get("NEXUS402_ARGS", "{}")) try: result = await server.call_tool(TOOL, args) except Exception as error: # a 402 or another refusal print(f"call refused: {error}") return 2 # The SDK re-exports the MCP result; newer MCP releases name the flag is_error. if getattr(result, "is_error", getattr(result, "isError", False)): print(f"call refused: {result.content}") return 2 for block in result.content: print(getattr(block, "text", block)) return 0 if __name__ == "__main__": # Never a default: a call is charged, and you choose who is paid. if not TOOL: sys.exit( "Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. " "A call to a paid tool is charged to your wallet." ) sys.exit(asyncio.run(main())) ``` ## MCP TypeScript SDK TypeScript, `@modelcontextprotocol/sdk` 1.32.2 (tested). Pass the header in the transport's requestInit. [Its own page](https://www.nexus402.dev/docs/developers/frameworks/typescript-mcp/). ``` npm install export NEXUS402_API_KEY=nx_dev_... # The tool to call, by its name in the marketplace. A paid tool is charged. export NEXUS402_TOOL='' node main.ts ``` ``` // Call a Nexus402 tool with the official MCP TypeScript SDK (ADR-0236). // // The key comes from NEXUS402_API_KEY and travels in the X-Nexus-Api-Key // header; it is never written in code. NEXUS402_TOOL names the tool to call // (required: a call is charged) and NEXUS402_ARGS its JSON arguments. import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; const url = process.env.NEXUS402_MCP_URL ?? "https://api.nexus402.dev/v1/mcp"; const key = process.env.NEXUS402_API_KEY; if (!key) throw new Error("Set NEXUS402_API_KEY"); const name = process.env.NEXUS402_TOOL; // Never a default: a call is charged, and you choose who is paid. if (!name) { throw new Error("Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. A call to a paid tool is charged to your wallet."); } const client = new Client({ name: "nexus402-example", version: "1.0.0" }); await client.connect(new StreamableHTTPClientTransport(new URL(url), { requestInit: { headers: { "X-Nexus-Api-Key": key } } })); const { tools } = await client.listTools(); console.log(`${tools.length} tools listed`); const args = JSON.parse(process.env.NEXUS402_ARGS ?? "{}") as Record; let code = 0; try { const result = await client.callTool({ name, arguments: args }); if (result.isError) { console.log(`call refused: ${JSON.stringify(result.content)}`); code = 2; } else { for (const block of result.content as { type: string; text?: string }[]) console.log(block.text ?? JSON.stringify(block)); } } catch (error) { // A 402 or another refusal. console.log(`call refused: ${String(error)}`); code = 2; } await client.close(); // exitCode, not process.exit(): exiting while the transport's handles close // aborts Node on Windows. process.exitCode = code; ``` --- # MCP Python SDK > Call paid MCP tools through Nexus402 from MCP Python SDK: one URL, one header, and the framework's own MCP client. Nothing of ours to install. Source: https://www.nexus402.dev/docs/developers/frameworks/python-mcp/ The MCP Python SDK is the official Python client for the Model Context Protocol. Use it when you are writing your own agent loop in Python and want to call tools directly, with no framework in between. The example connects to `https://api.nexus402.dev/v1/mcp` over streamable HTTP, sends your key in the `X-Nexus-Api-Key` header, lists the tools the key may call, and calls the one you name in `NEXUS402_TOOL`. **A call to a paid tool is charged to your wallet.** If you name none, nothing is called. It is run against a test gateway at `mcp` 1.30.0, so a release that changes how headers are passed is caught before you meet it. > **Careful** > > Keep the key in the > > NEXUS402_API_KEY > > environment variable, never in code or a committed file. Give each agent its own key with a 24-hour spend cap and, if it chooses tools on its own, a maximum price per call. See > > how to give an agent a budget > > . ## Install and run Python. Give the SDK an httpx.AsyncClient that carries the header. ``` pip install -r requirements.txt export NEXUS402_API_KEY=nx_dev_... # The tool to call, by its name in the marketplace. A paid tool is charged. export NEXUS402_TOOL='' python main.py ``` ## The example ``` """Call a Nexus402 tool with the official MCP Python SDK (ADR-0236). The key comes from NEXUS402_API_KEY and travels in the X-Nexus-Api-Key header. It is never written in code. NEXUS402_TOOL names the tool to call (required: a call is charged) and NEXUS402_ARGS its JSON arguments. """ import asyncio import json import os import sys import httpx from mcp import ClientSession from mcp.client.streamable_http import streamable_http_client URL = os.environ.get("NEXUS402_MCP_URL", "https://api.nexus402.dev/v1/mcp") TOOL = os.environ.get("NEXUS402_TOOL", "") def refusal(error: BaseException) -> httpx.HTTPStatusError | None: """The HTTP refusal inside an error, however deeply the SDK grouped it.""" if isinstance(error, httpx.HTTPStatusError): return error if isinstance(error, BaseExceptionGroup): for inner in error.exceptions: found = refusal(inner) if found is not None: return found return None async def main() -> int: # The SDK raises an HTTP refusal (a 402 when the wallet cannot pay) from # its transport's task group, so it surfaces here, as an ExceptionGroup, # rather than from call_tool. try: return await call() except Exception as error: refused = refusal(error) if refused is None: raise print(f"call refused: HTTP {refused.response.status_code}") return 2 async def call() -> int: headers = {"X-Nexus-Api-Key": os.environ["NEXUS402_API_KEY"]} async with httpx.AsyncClient(headers=headers, timeout=60) as http: async with streamable_http_client(URL, http_client=http) as (read, write, _): async with ClientSession(read, write) as session: await session.initialize() tools = (await session.list_tools()).tools print(f"{len(tools)} tools listed") args = json.loads(os.environ.get("NEXUS402_ARGS", "{}")) try: result = await session.call_tool(TOOL, args) except Exception as error: # a 402 or another refusal print(f"call refused: {error}") return 2 if result.isError: print(f"call refused: {result.content}") return 2 for block in result.content: print(getattr(block, "text", block)) return 0 if __name__ == "__main__": # Never a default: a call is charged, and you choose who is paid. if not TOOL: sys.exit( "Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. " "A call to a paid tool is charged to your wallet." ) sys.exit(asyncio.run(main())) ``` ## When a call is refused A call your wallet or your key's cap cannot cover is refused with HTTP `402` before anything is charged, and the example prints `call refused` and exits with code 2. A call that fails before any output reaches your agent is not charged either. Every refusal code is in [the error reference](https://www.nexus402.dev/docs/developers/errors/). ## Next - [All four framework examples](https://www.nexus402.dev/docs/developers/frameworks/), side by side. - [Keys, caps and rotation](https://www.nexus402.dev/docs/developers/keys/), for a key per agent. - [The marketplace](https://www.nexus402.dev/marketplace/), for the tools your agent can call. --- # LangChain (Python) > Call paid MCP tools through Nexus402 from LangChain (Python): one URL, one header, and the framework's own MCP client. Nothing of ours to install. Source: https://www.nexus402.dev/docs/developers/frameworks/langchain/ LangChain is a Python framework for building agents from models and tools. With langchain-mcp-adapters, every Nexus402 tool your key may call becomes a LangChain tool your agent can choose, with its schema and description intact. The example connects to `https://api.nexus402.dev/v1/mcp` over streamable HTTP, sends your key in the `X-Nexus-Api-Key` header, lists the tools the key may call, and calls the one you name in `NEXUS402_TOOL`. **A call to a paid tool is charged to your wallet.** If you name none, nothing is called. It is run against a test gateway at `langchain-mcp-adapters` 0.3.2, so a release that changes how headers are passed is caught before you meet it. > **Careful** > > Keep the key in the > > NEXUS402_API_KEY > > environment variable, never in code or a committed file. Give each agent its own key with a 24-hour spend cap and, if it chooses tools on its own, a maximum price per call. See > > how to give an agent a budget > > . ## Install and run Python. Put the header in the connection's headers; every tool the key may call becomes a LangChain tool. ``` pip install -r requirements.txt export NEXUS402_API_KEY=nx_dev_... # The tool to call, by its name in the marketplace. A paid tool is charged. export NEXUS402_TOOL='' python main.py ``` ## The example ``` """Call a Nexus402 tool through LangChain's MCP adapters (ADR-0236). The adapters turn every tool the key may call into a LangChain tool, so an agent built with LangChain or LangGraph can use them directly. Here one is invoked by hand: the one NEXUS402_TOOL names (required: a call is charged). The key comes from NEXUS402_API_KEY, never from code. """ import asyncio import json import os import sys from langchain_mcp_adapters.client import MultiServerMCPClient URL = os.environ.get("NEXUS402_MCP_URL", "https://api.nexus402.dev/v1/mcp") TOOL = os.environ.get("NEXUS402_TOOL", "") def routing_name(tool) -> str: """The tool's routing name (acme/weather/forecast), when the list names it by its MCP-safe listed name (acme_weather_forecast, ADR-0264) and the adapters keep the row's _meta. So NEXUS402_TOOL may be either spelling.""" meta = (getattr(tool, "metadata", None) or {}).get("_meta") return meta.get("nexus402/name", "") if isinstance(meta, dict) else "" async def main() -> int: client = MultiServerMCPClient( { "nexus402": { "transport": "streamable_http", "url": URL, "headers": {"X-Nexus-Api-Key": os.environ["NEXUS402_API_KEY"]}, } }, handle_tool_errors=False, ) tools = await client.get_tools() print(f"{len(tools)} tools listed") tool = next(t for t in tools if TOOL in (t.name, routing_name(t))) args = json.loads(os.environ.get("NEXUS402_ARGS", "{}")) try: result = await tool.ainvoke(args) except Exception as error: # a 402 or another refusal print(f"call refused: {error}") return 2 print(result) return 0 if __name__ == "__main__": # Never a default: a call is charged, and you choose who is paid. if not TOOL: sys.exit( "Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. " "A call to a paid tool is charged to your wallet." ) sys.exit(asyncio.run(main())) ``` ## When a call is refused A call your wallet or your key's cap cannot cover is refused with HTTP `402` before anything is charged, and the example prints `call refused` and exits with code 2. A call that fails before any output reaches your agent is not charged either. Every refusal code is in [the error reference](https://www.nexus402.dev/docs/developers/errors/). ## Next - [All four framework examples](https://www.nexus402.dev/docs/developers/frameworks/), side by side. - [Keys, caps and rotation](https://www.nexus402.dev/docs/developers/keys/), for a key per agent. - [The marketplace](https://www.nexus402.dev/marketplace/), for the tools your agent can call. --- # OpenAI Agents SDK (Python) > Call paid MCP tools through Nexus402 from OpenAI Agents SDK (Python): one URL, one header, and the framework's own MCP client. Nothing of ours to install. Source: https://www.nexus402.dev/docs/developers/frameworks/openai-agents/ The OpenAI Agents SDK builds agents in Python that plan, call tools and hand off to each other. It speaks MCP natively, so Nexus402's tools reach an agent as one MCP server passed to its mcp_servers. The example connects to `https://api.nexus402.dev/v1/mcp` over streamable HTTP, sends your key in the `X-Nexus-Api-Key` header, lists the tools the key may call, and calls the one you name in `NEXUS402_TOOL`. **A call to a paid tool is charged to your wallet.** If you name none, nothing is called. It is run against a test gateway at `openai-agents` 0.25.0, so a release that changes how headers are passed is caught before you meet it. > **Careful** > > Keep the key in the > > NEXUS402_API_KEY > > environment variable, never in code or a committed file. Give each agent its own key with a 24-hour spend cap and, if it chooses tools on its own, a maximum price per call. See > > how to give an agent a budget > > . ## Install and run Python. Put the header in MCPServerStreamableHttp's params, then pass the server to an Agent's mcp_servers. ``` pip install -r requirements.txt export NEXUS402_API_KEY=nx_dev_... # The tool to call, by its name in the marketplace. A paid tool is charged. export NEXUS402_TOOL='' python main.py ``` ## The example ``` """Call a Nexus402 tool through the OpenAI Agents SDK's MCP server (ADR-0236). Pass the same server to an Agent (`Agent(..., mcp_servers=[server])`) and the model can call any tool the key allows. Here one is called directly, so the example needs no model: the one NEXUS402_TOOL names (required: a call is charged). The key comes from NEXUS402_API_KEY, never from code. """ import asyncio import json import os import sys from agents.mcp import MCPServerStreamableHttp URL = os.environ.get("NEXUS402_MCP_URL", "https://api.nexus402.dev/v1/mcp") TOOL = os.environ.get("NEXUS402_TOOL", "") async def main() -> int: params = {"url": URL, "headers": {"X-Nexus-Api-Key": os.environ["NEXUS402_API_KEY"]}} async with MCPServerStreamableHttp(params=params, name="nexus402") as server: tools = await server.list_tools() print(f"{len(tools)} tools listed") args = json.loads(os.environ.get("NEXUS402_ARGS", "{}")) try: result = await server.call_tool(TOOL, args) except Exception as error: # a 402 or another refusal print(f"call refused: {error}") return 2 # The SDK re-exports the MCP result; newer MCP releases name the flag is_error. if getattr(result, "is_error", getattr(result, "isError", False)): print(f"call refused: {result.content}") return 2 for block in result.content: print(getattr(block, "text", block)) return 0 if __name__ == "__main__": # Never a default: a call is charged, and you choose who is paid. if not TOOL: sys.exit( "Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. " "A call to a paid tool is charged to your wallet." ) sys.exit(asyncio.run(main())) ``` ## When a call is refused A call your wallet or your key's cap cannot cover is refused with HTTP `402` before anything is charged, and the example prints `call refused` and exits with code 2. A call that fails before any output reaches your agent is not charged either. Every refusal code is in [the error reference](https://www.nexus402.dev/docs/developers/errors/). ## Next - [All four framework examples](https://www.nexus402.dev/docs/developers/frameworks/), side by side. - [Keys, caps and rotation](https://www.nexus402.dev/docs/developers/keys/), for a key per agent. - [The marketplace](https://www.nexus402.dev/marketplace/), for the tools your agent can call. --- # MCP TypeScript SDK > Call paid MCP tools through Nexus402 from MCP TypeScript SDK: one URL, one header, and the framework's own MCP client. Nothing of ours to install. Source: https://www.nexus402.dev/docs/developers/frameworks/typescript-mcp/ The MCP TypeScript SDK is the official TypeScript client for the Model Context Protocol. Use it from Node.js when your agent, or the service around it, is written in TypeScript. The example connects to `https://api.nexus402.dev/v1/mcp` over streamable HTTP, sends your key in the `X-Nexus-Api-Key` header, lists the tools the key may call, and calls the one you name in `NEXUS402_TOOL`. **A call to a paid tool is charged to your wallet.** If you name none, nothing is called. It is run against a test gateway at `@modelcontextprotocol/sdk` 1.32.2, so a release that changes how headers are passed is caught before you meet it. > **Careful** > > Keep the key in the > > NEXUS402_API_KEY > > environment variable, never in code or a committed file. Give each agent its own key with a 24-hour spend cap and, if it chooses tools on its own, a maximum price per call. See > > how to give an agent a budget > > . ## Install and run TypeScript. Pass the header in the transport's requestInit. ``` npm install export NEXUS402_API_KEY=nx_dev_... # The tool to call, by its name in the marketplace. A paid tool is charged. export NEXUS402_TOOL='' node main.ts ``` ## The example ``` // Call a Nexus402 tool with the official MCP TypeScript SDK (ADR-0236). // // The key comes from NEXUS402_API_KEY and travels in the X-Nexus-Api-Key // header; it is never written in code. NEXUS402_TOOL names the tool to call // (required: a call is charged) and NEXUS402_ARGS its JSON arguments. import { Client } from "@modelcontextprotocol/sdk/client/index.js"; import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js"; const url = process.env.NEXUS402_MCP_URL ?? "https://api.nexus402.dev/v1/mcp"; const key = process.env.NEXUS402_API_KEY; if (!key) throw new Error("Set NEXUS402_API_KEY"); const name = process.env.NEXUS402_TOOL; // Never a default: a call is charged, and you choose who is paid. if (!name) { throw new Error("Set NEXUS402_TOOL to the name of the tool to call. Nothing was called. A call to a paid tool is charged to your wallet."); } const client = new Client({ name: "nexus402-example", version: "1.0.0" }); await client.connect(new StreamableHTTPClientTransport(new URL(url), { requestInit: { headers: { "X-Nexus-Api-Key": key } } })); const { tools } = await client.listTools(); console.log(`${tools.length} tools listed`); const args = JSON.parse(process.env.NEXUS402_ARGS ?? "{}") as Record; let code = 0; try { const result = await client.callTool({ name, arguments: args }); if (result.isError) { console.log(`call refused: ${JSON.stringify(result.content)}`); code = 2; } else { for (const block of result.content as { type: string; text?: string }[]) console.log(block.text ?? JSON.stringify(block)); } } catch (error) { // A 402 or another refusal. console.log(`call refused: ${String(error)}`); code = 2; } await client.close(); // exitCode, not process.exit(): exiting while the transport's handles close // aborts Node on Windows. process.exitCode = code; ``` ## When a call is refused A call your wallet or your key's cap cannot cover is refused with HTTP `402` before anything is charged, and the example prints `call refused` and exits with code 2. A call that fails before any output reaches your agent is not charged either. Every refusal code is in [the error reference](https://www.nexus402.dev/docs/developers/errors/). ## Next - [All four framework examples](https://www.nexus402.dev/docs/developers/frameworks/), side by side. - [Keys, caps and rotation](https://www.nexus402.dev/docs/developers/keys/), for a key per agent. - [The marketplace](https://www.nexus402.dev/marketplace/), for the tools your agent can call. --- # Keys, caps and rotation > Ten keys, an optional rolling 24-hour ceiling, immediate revocation and overlapping rotation. Source: https://www.nexus402.dev/docs/developers/keys/ A key is how a call is authenticated and how spend is attributed. You can hold ten at once. ## Minting - **Ten active keys** per account. The limit is enforced by the database, not by a check that can be forgotten. - **Shown once.** We store only an argon2id hash with a pepper, so we cannot show it again and cannot recover it. - **Name them.** A name is the only way to tell ten keys apart later, and it appears in the spend breakdown. It is 1 to 64 characters and unique among your active keys: a clash is `409 name_taken`, and a deleted key’s name is free again. - **Twenty a day.** Creating and rotating share one budget of 20 keys per account per day. Past it you get `429 key_create_limited` with `Retry-After: 3600`. - **Every change is emailed.** You get a security email each time a key is created, rotated or loosened. If you have used all 20 of your security emails for the day, the change is refused with `429 key_notice_limited`, and `Retry-After` says how long to wait. You can always delete a key or tighten its limits. ## Keys above $10.00 a day need a code **A key with a daily cap above $10.00, or with no cap, needs a code from your email** when you create it, rotate it or loosen any of its limits. Keys with a cap of $10.00 a day or less never need one. Calls never need one, and neither does deleting a key or only tightening its limits. The app asks for the code for you. From a script, ask for it with exactly the request you want to make, then send that request again with the code: **Request a key code** ```text POST /v1/dev/keys/code {"action": "create", "request": {"name": "production", "cap_micro": "25000000"}} POST /v1/dev/keys {"name": "production", "cap_micro": "25000000", "code": "ABCD2345"} ``` - **`action`** is `create`, `rotate` or `policy`. Rotate and policy also need `key_id`. - The code lasts 10 minutes, works once, and works only for exactly that change. If the key’s limits change after it is sent, ask for a new one. - Without a code you get `403 key_code_required`, and nothing changes. A wrong, old, used or mismatched code gets `403 key_code_invalid`. Asking for a code you do not need gets `409 key_code_not_needed`. - You can be sent 10 codes a day for all account actions. Once 7 are used, the last 3 need a new sign-in: `429 code_reserve_available`. If you did not ask for the first 7, end your other sessions after you sign in, then ask for a code. - **A person must read the code.** Never give a script access to your mailbox. Keep the keys your scripts manage at $10.00 a day or less, or rotate larger ones in the app. ## The 24-hour cap Each key is capped or uncapped, and you say which when you create it: a positive `cap_micro`, or `"uncapped": true`. Sending neither, or a cap of `"0"`, is refused rather than quietly read as unlimited. A cap is a **rolling 24-hour spend ceiling** for that key — not a calendar day, not a monthly budget. **What a cap does** ```text cap = 5000000 micro ($5.00) 09:00 spend $4.80 -> allowed, $0.20 of headroom left 09:01 spend $0.50 -> 402 Budget_Exhausted, nothing charged next day 09:01 -> the 09:00 spend ages out, headroom returns ``` > **A cap is yours, and nothing lowers it for you** > > No heuristic, no abuse detector and no operator reduces a cap you set. If a key of yours looks like it is looping, we tell you — we do not decide for you. A stated limit that something else can quietly tighten is not a limit. An uncapped key is bounded only by the wallet balance. That is a legitimate choice for a trusted workload, and it is why pre-funding matters: the balance is the ceiling that always applies. A cap can be changed later with `POST /v1/dev/keys/:id/policy`. ## Limiting a key to some tools, or to a lifetime Two optional settings narrow what a key can do: - **`allowed_tools`** — up to 50 tool names (`handle/mcp/tool`, without a version). A call to any other tool is refused with `404 Unknown_Tool`, before anything is charged, and `tools/list` shows the key only the tools it may call. Leave it out and the key may call every tool. It can be changed later through the same `policy` route; an empty list returns the key to every tool. - **`expires_at`** — an RFC 3339 time between one hour and 365 days from now. After it, the key stops working. ## Revocation is immediate Revoking takes effect on the next call, not eventually. There is no cache to wait out and no propagation delay to reason about. ## Rotation has an overlap window Rotating issues a new key while the old one keeps working for a grace period, so you can redeploy without refusing traffic. Expiry is enforced when the key is read, so a missed cleanup job cannot silently extend a credential past its window. **Rotating a key** ```text POST /v1/dev/keys/:id/rotate {"name": "production-2", "overlap_seconds": 3600} ``` - **`name` is required**, and must differ from the old key’s, because the old key is still active through the overlap. - **`overlap_seconds`** is how long the old key keeps working: one hour if you leave it out, at most seven days (604800). **`0` expires the old key now** — the response to a leaked key. - The new key keeps the old one’s cap, its tool list and its expiry. Rotation never extends a key’s life: an old key due to expire sooner than the overlap still expires on time. - The new key is shown once, like any other. ## What a key cannot do - It cannot change your wallet balance, add funds or move money. - It cannot read or write another account's anything. - It cannot raise its own cap. Caps are changed from your account, with a session, not with the key. - It is never forwarded to a creator. --- # Funding and spend > Pre-funding with 3D Secure, no fee on the Credits, and why there is no auto-top-up. Source: https://www.nexus402.dev/docs/developers/wallet/ One pre-funded wallet per account. Every key spends from it, and the balance is the ceiling that always applies. ## Adding funds 1. Choose an amount on your wallet page. 2. We show the **total charged** before you pay. It is the amount you chose: we add no fee. 3. Pay through Stripe Checkout, with 3D Secure requested. 4. The credit lands when the payment settles — usually seconds. > **No fee is added to your Credits** > > Pay $25.00 and your wallet is credited exactly $25.00. We absorb the cost of card processing, and the pay button names the total, so the number you confirm is the number that leaves your account. ## How much you can add - **$10.00 minimum** per top-up. - **A per-top-up ceiling that rises with account age:** $50.00 in your first seven days, $500.00 until the account is thirty days old, then $2,000.00. - **At most $2,000.00 and ten top-ups in any 24 hours**, summed across top-ups, at every account age. Past either, the next attempt is refused with `429 topup_velocity` and a `Retry-After`. Once you are past the ramp the per-top-up maximum and the daily total are the same figure, so you can do a whole day in one top-up. A refusal names the figure that applies to *your* account, so you never have to work out which limit you met. The ramp is about card fraud rather than about you: a stolen card loaded onto a prepaid balance and spent before the dispute arrives is the one loss nothing can recover, so the first week is bounded and after that it is not. ## There is no auto-top-up This is deliberate and it is the main safety property of the whole system. A pre-funded balance with no automatic refill means a runaway agent can spend at most what you have already decided to give it. There is no stored card to draw on and no overdraft. The cost is that you can run dry mid-workload and start getting `402`s. Two emails warn you first, and both are **on by default**: - **Low balance** — sent when your balance falls below a tenth of what your last top-up left it at. - **Spending cap reached** — sent when a key reaches its 24-hour cap. Either can be switched off under email preferences in your account (`GET` and `POST /v1/account/email-preferences`, notices `low_balance` and `key_cap_reached`). ## Trial credit A new account may be given trial credit when it is created, if an offer is running at the time. It is not money, and it is deliberately narrow: - It pays **only for creators’ free calls** — the free calls a creator offers on a tool are open to an account that has never topped up, as long as its trial credit covers the tool’s price. It never pays for a charged call. - It is **not part of your balance**, cannot be withdrawn or refunded, and expires. - **Your first top-up ends it.** What is left is not converted to balance; from then on creators’ free calls are open to you without it. `GET /v1/dev/wallet` reports it as `trial`: `granted_micro`, `remaining_micro`, `expires_at` and a `status` of `active`, `expired` or `finished` (you topped up). It is `null` when the account has no grant. ## Seeing where it went - **Movements** itemise every charge, refund and top-up against the ledger, not against a cache (`GET /v1/dev/movements`). - **Per-key usage** attributes spend to the key that made the call, which is why naming keys matters (`GET /v1/dev/usage`). - **The call log** lists your recent calls one by one, with each call’s outcome — `charged`, `free`, `refunded`, `voided` or `refused` — its status, amount and correlation id (`GET /v1/dev/calls`, filtered by `?outcome=`, `?key=` or `?tool=`, up to 500 rows per page with `?limit=`, and paged by passing a row’s `cursor` as `?before=`). It is a diagnostic record kept for 30 days and can miss a row under load; your bill is the ledger. - **CSV downloads** of the same three: `/v1/dev/calls.csv`, `/v1/dev/movements.csv` and `/v1/dev/usage.csv`. - **A receipt for each top-up** at `GET /v1/dev/topups/:txn_id/receipt`, using the top-up’s `txn_id` from your movements. It is a receipt, not a tax invoice. - **Every figure is integer micro-USD as a string.** See [money is a string](https://www.nexus402.dev/docs/developers/money-format/). ## Refunds A refund for a failed call is automatic and appears as its own entry. The ledger is append-only, so a refund is a new row rather than an edit to the charge — you can always see both what was taken and what came back. > **We do not refund on request** > > A completed call that did what it said is not refundable from here; that is between you and the creator. What is automatic is the failure case: if the tool did not deliver, you were not charged. ## Disputing a card payment If you dispute a top-up with your bank and the dispute is decided against us, three things happen together: the credit from that top-up you have **not yet spent** is reclaimed, the account is suspended, and **every API key on it is destroyed**. Anything still calling them fails immediately. If the dispute is later decided in your favour the suspension is lifted. The keys are not restored — you create new ones. Compute you had already consumed is not clawed back, because it was delivered, and nothing beyond the disputed credit is taken. > **Ask us before you ask your bank** > > A chargeback is not a refund route: it costs you the account rather than the argument, and it is slower than an email. The ledger is append-only and every entry is itemised, so a charge that is genuinely wrong is quick to show and quick to correct. --- # When you are charged > A fixed price, automatic refunds, and the one failure you do pay for. Source: https://www.nexus402.dev/docs/developers/billing/ One fixed price per call, known before you make it. Here is exactly when that price is taken and when it is not. ## When you are charged | Outcome | Charged? | | --- | --- | | The tool returned a success | **Yes**, once, at the version's fixed price | | The tool failed before any byte reached you | **No.** Refunded automatically | | The tool failed after the first byte reached you | **Yes.** You received part of the work | | The tool timed out before its first byte | **No.** Refunded | | Your wallet could not cover it | **No.** `402`, nothing taken | | The key's 24-hour cap was reached | **No.** `402`, nothing taken | | You were rate limited | **No.** `429` | | Our infrastructure failed | **No.** `503`, and we fail closed rather than guess | | It was one of the tool's free calls | **No.** See [free calls](#free) | | You cancelled mid-stream | **Yes.** The work was done and partly delivered | > **The first byte is the boundary, and it is not arbitrary** > > Before the first byte, nothing of value has been delivered and a refund costs nobody anything. After it, the creator has done the work and you have some of it — refunding then would make every long-running tool uneconomic to offer. ## How the charge happens The price is deducted **before** the tool is contacted, in a single atomic operation that checks the balance and the cap together. That ordering is deliberate: it means a call can never be served without being paid for, and a crash mid-call cannot leave a tool contacted but unbilled. If the call then fails before delivering anything, the refund is a separate recorded entry rather than an erasure — the ledger is append-only, so a correction is always a new row. ## When it appears What you can still spend reflects the charge immediately: the next call is checked against the balance after this one. The balance on your wallet page, and the itemised ledger entry, catch up at the next five-minute rollup, because charges are batched rather than written one row per call. The wallet page says so beside the figure. The two always agree once the rollup has run; one is just more immediate than the other. ## Free calls A creator can give every account a number of free calls to a tool per day, week or month — calendar periods in UTC, with weeks starting on Monday. While you have some left, a call to that tool is **not charged**: - The answer carries no `X-Nexus-Price`, because nothing was charged. - It carries `X-Nexus-Free-Quota-Remaining`, the free calls you have left on that tool this period. Once that reaches `0`, calls are charged at the normal price. - A free call does not count against the key’s 24-hour cap. - If the tool fails before delivering anything, the free call is handed back, just as a charge would be refunded. Free calls are granted only to an account that has a settled top-up (one later refunded or charged back no longer counts), or that holds enough [trial credit](https://www.nexus402.dev/docs/developers/wallet/#trial) to cover the tool’s price. Otherwise the call is charged as usual. ## Who you are buying from You buy from Nexus402, not from the creator. The price in the catalog is our price and is the whole of what you pay: nothing is added to it and nothing is collected from you on anyone else’s behalf. The creator is our supplier, owed a wholesale price for the call, and we keep a 10% margin on the resale. --- # Money is a string > Integer micro-USD as a JSON string, and the 2^53 parsing bug that choice prevents. Source: https://www.nexus402.dev/docs/developers/money-format/ Every amount in the account and catalogue JSON is **integer micro-USD encoded as a JSON string**, in a field whose name ends in `_micro`. Never a JSON number, never a float. Two places use a different unit, and say so in the name or the spec: - **The gateway’s money headers** — `X-Nexus-Price`, `X-Nexus-Required-Amount` and a `402`’s `required` — are **decimal US dollars as a string**: `"0.05"` is five cents. - **Top-ups** are in **integer cents as a string**: `amount_cents`, `charged_cents` and `fee_cents`, so `"1000"` is $10.00. None of them is ever a JSON number. **What an amount looks like** ```json { "balance_micro": "10000000", // $10.00 "price_micro": "50000", // $0.05 "currency": "USD" } ``` ## Why a string > **A JSON number cannot safely hold money** > > JavaScript parses JSON numbers as IEEE-754 doubles. Above 253 they lose integer precision, so `10000000000000001` becomes `10000000000000000` *before your code ever runs*. No amount of care on your side can recover a digit the parser already discarded. > > Micro-USD reaches 253 at about $9 billion, which sounds comfortable until you consider a platform total rather than one wallet. Strings make the question moot. ## Reading amounts correctly **Correct and incorrect — Node.js** ``` const { balance_micro } = await response.json(); // CORRECT: BigInt, or keep the string and format it for display. const micro = BigInt(balance_micro); const whole = micro / 1000000n; const cents = String(micro % 1000000n).padStart(6, "0").slice(0, 2); const display = `$${whole}.${cents}`; // WRONG: silently lossy above 2^53, and lossy in a way no test // with small numbers will ever catch. const broken = Number(balance_micro); ``` **Correct and incorrect — Python** ``` payload = response.json() # CORRECT. Python integers are arbitrary precision, so the only way to lose # a digit here is to ask for a float. micro = int(payload["balance_micro"]) display = f"${micro // 1_000_000}.{micro % 1_000_000 // 10_000:02d}" # WRONG: lossy above 2^53, exactly as in JavaScript. broken = float(payload["balance_micro"]) ``` **Correct and incorrect — Go** ``` // CORRECT: parse the string as a 64-bit integer and keep it that way. micro, err := strconv.ParseInt(amount, 10, 64) if err != nil { return err } display := fmt.Sprintf("$%d.%02d", micro/1_000_000, micro%1_000_000/10_000) // WRONG: strconv.ParseFloat, or unmarshalling into a float64 field — // `json.Unmarshal` into `interface{}` gives you float64 by default, which // is the same bug wearing a different hat. ``` **Correct and incorrect — Rust** ``` // CORRECT: i64 all the way through. let micro: i64 = amount.parse()?; let display = format!("${}.{:02}", micro / 1_000_000, micro % 1_000_000 / 10_000); // WRONG: `amount.parse::()`, or reaching for // `serde_json::Value::as_f64()` on a field that arrived as a string. ``` **Correct and incorrect — PHP** ``` A key is single-use for a paid call: a retry under it is refused, never charged a second time. Source: https://www.nexus402.dev/docs/developers/idempotency/ An idempotency key makes a retry safe: one key pays for a call at most once. A retry under a key that already paid is refused with `422 Idempotency_Conflict` rather than run again. ## Using one **A retryable call** ```bash curl -s https://api.nexus402.dev/v1/mcp \ -H "X-Nexus-Api-Key: nx_dev_..." \ -H "Idempotency-Key: 7f3a9c12-4e5b-4d8a-9f01-2b3c4d5e6f70" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call",...}' ``` Generate a fresh key per logical operation — a UUID is ideal. Reuse it only when retrying *that same operation*. Two requests are the same when they use the same API key, reach the same tool version and carry the same body. The JSON-RPC `id` and the order of object keys do not count, so a client that mints a new `id` for its retry is still sending the same request. ## A duplicate of the same request > **Refused with 422 Idempotency_Conflict, and not charged** > > If the first attempt under the key was accepted and has not been refunded, the retry is refused. It does not reach the tool and it does not touch your balance, so you cannot be billed twice for one intention. > > It also does not return the first attempt’s result. We never store your payloads, so there is no result to replay. A `422` on a retry tells you the first attempt was taken: it may still be running, or it ran and its answer was lost on the way to you. Look it up in your call log or your movements rather than retrying again. If the first attempt was **refunded** — the tool failed before delivering anything, or we failed closed with a `503` after the debit — the key is free again. A retry under it runs as a new call and is charged once. A refusal that took nothing (a `402`, a `429`, or a `503` before the debit) never used the key at all. ## A reused key with a different request > **Also refused with 422 Idempotency_Conflict, never run** > > If you send the same `Idempotency-Key` with a different body, we refuse. We do not run the new request, and we do not answer it as if it were the old one. > > Running it would mean one key charged for two operations, which is exactly what the key exists to prevent. The fix is always the same: use a new key for a new request. ## How long a key is remembered **Five days** from the call that used it. A key reused after that is treated as new and the call is charged again — which is another reason to generate one per operation rather than reusing a constant. ## Without a key A call with no `Idempotency-Key` is simply charged. If it times out and you retry, you may be charged twice, because we cannot tell the retry from a second genuine request. For anything that costs real money, send a key. --- # Rate limits > What is metered, what a 429 means, and how to back off without losing calls. Source: https://www.nexus402.dev/docs/developers/rate-limits/ Rate limits protect the gateway and your wallet. They are separate from spend caps: a limit refuses a request, a cap refuses a charge. ## What is metered | Limit | Keyed on | Refusal | | --- | --- | --- | | Requests per key | The verified key | `429 key_rate_limited` with `Retry-After` — the seconds left in the window. Counted after your key is verified and before anything is deducted | | Authentication attempts | Client IP, before any hashing | `401`. This is what makes brute-forcing a key infeasible | | Catalog reads | Client IP | `429`. `GET /v1/tools` needs no key, so it needs its own window | | Concurrent calls per creator | The creator's host | `502` after a short wait, if one creator is saturated | | The creator’s own limit | Whatever the creator chooses | The creator’s own `429`, relayed with their status, body and any `Retry-After` they sent. It carries no `X-Nexus-Error`, and the call is refunded | | Repeated creator failures | The creator's endpoint | `502 Upstream_Unavailable` **immediately**. After enough consecutive failures we stop dialling that endpoint for a cooldown, so this 502 can arrive with no attempt made at all | > **A 429 is never charged** > > Neither is a 401, a 402 or a 503. If the gateway did not authorize the call, it did not bill it — there is no partial charge for a refused request. ## Backing off Honour `Retry-After`. It is in seconds and it is not a suggestion: retrying faster meets the same window and wastes the attempt. **A correct retry — Node.js** ``` async function call(body, attempt = 0) { const response = await fetch(GATEWAY, { method: "POST", headers, body }); if (response.status !== 429) return response; // Retry-After is authoritative. Fall back to exponential backoff only // if it is absent, and give up rather than hammering. const after = Number(response.headers.get("Retry-After") ?? 2 ** attempt); if (attempt >= 5) throw new Error("rate limited: giving up"); await new Promise((r) => setTimeout(r, after * 1000)); return call(body, attempt + 1); } ``` **A correct retry — Python** ``` import time import requests def call(body, attempt=0): # 130s, because the gateway's own hard timeout is 120s. response = requests.post(GATEWAY, headers=headers, data=body, timeout=130) if response.status_code != 429: return response if attempt >= 5: raise RuntimeError("rate limited: giving up") # Retry-After is authoritative. Back off exponentially only without it. after = float(response.headers.get("Retry-After", 2 ** attempt)) time.sleep(after) return call(body, attempt + 1) ``` **A correct retry — Go** ``` func call(ctx context.Context, body []byte) (*http.Response, error) { for attempt := 0; ; attempt++ { response, err := post(ctx, body) if err != nil { return nil, err } if response.StatusCode != http.StatusTooManyRequests { return response, nil } response.Body.Close() if attempt >= 5 { return nil, errors.New("rate limited: giving up") } // Retry-After is authoritative. Back off only without it. wait := time.Duration(1<) -> Result { for attempt in 0..=5u32 { let response = client.post(GATEWAY).body(body.clone()).send().await?; if response.status() != StatusCode::TOO_MANY_REQUESTS { return Ok(response); } // Retry-After is authoritative. Back off only without it. let wait = response .headers() .get(RETRY_AFTER) .and_then(|value| value.to_str().ok()) .and_then(|value| value.parse::().ok()) .unwrap_or(1 << attempt); sleep(Duration::from_secs(wait)).await; } Err(CallError::RateLimited) } ``` **A correct retry — PHP** ``` = 5) { throw new RuntimeException('rate limited: giving up'); } // Retry-After is authoritative. Back off only without it. $after = (int) ($headers['retry-after'] ?? 2 ** $attempt); sleep($after); return call($handle, $body, $attempt + 1); } ``` ## Concurrency There is no published per-account concurrency limit. The practical bound is the per-creator connection ceiling: a single creator host accepts up to 64 concurrent calls, so a burst aimed at one tool queues briefly and then returns `502` rather than waiting indefinitely. If you are driving real volume at one tool, spread it over time rather than firing it all at once — and tell us, because that is a conversation about capacity rather than a limit to work around. --- # Every error code > Every error code the gateway can return, what it means, and whether you were charged. Source: https://www.nexus402.dev/docs/developers/errors/ > **This table is generated from the gateway's own source** > > The codes are extracted from the gateway’s own source — both the error registry and the handlers that write a code by hand. A code nobody documented **fails our tests**, and so does prose for a code the gateway no longer emits, so this list cannot quietly fall behind the thing it describes. ## The codes | Code | HTTP | Charged | `X-Nexus-Error` | What happened | What to do | | --- | --- | --- | --- | --- | --- | | `Budget_Exhausted` | 402 | No | Set | The wallet cannot cover this call, or the key's rolling 24-hour cap would be exceeded. Both are reported the same way, deliberately: either way you have hit a ceiling you set. | X-Nexus-Required-Amount (and the body's required) is the call's full price in decimal dollars, not the shortfall. Add funds or raise that key's cap. | | `Rate_Limited` | 429 | No | Set | Reserved: nothing in the gateway sends this code today. A 429 that a creator returns is relayed with the creator's own status and body, carries no X-Nexus-Error, and is refunded. The 429 the gateway sends is key_rate_limited. | Honour Retry-After wherever a 429 carries one. Retrying sooner meets the same window and wastes the attempt. | | `Upstream_Unavailable` | 502 | No | Set | The creator's endpoint failed, timed out before its first byte, answered in a shape we refuse to relay, or has failed often enough that we stopped dialling it for a cooldown. This 502 is sent only after the charge is voided, or before any was taken. | Retry. A failure after the response began is not a 502: the status stays 200, the payload_truncated trailer is sent, and the charge stands. | | `Lock_Unavailable` | 503 | No | Set | Our own infrastructure could not authorize the call, so we failed closed rather than guess. A metering system that cannot read its own state must refuse, not assume. | Retry with backoff. A 503 is never a silent debit. | | `Idempotency_Conflict` | 422 | No | Set | This Idempotency-Key is already bound to a call. A retry of the same request is refused unless that call was refunded, and a different request under the key is always refused. Nothing is replayed, because payloads are never stored. | Check your call log for the first attempt. Use a fresh key for a new request; a key whose call was refunded may be retried. | | `Authorization_Rejected` | 400 | No | Set | Your pass-through Authorization header carried an nx_dev_ token, which would have handed your Nexus key to a creator who could then spend your wallet. | Put the tool's own credential there, never your Nexus key. | | `Unknown_Version` | 404 | No | Not set | The tool exists but the version you pinned does not, or it has been retired. A published version is immutable, so a new price or endpoint ships as a new version instead of changing the one you pinned. | Drop the @v pin to resolve the highest published version, or pin one that GET /v1/tools still lists. | | `Unknown_Tool` | 404 | No | Not set | Nothing is published under that name. A tool name is creator-handle/mcp-name/tool-name, with an optional @v pin on the middle segment, and it resolves against the published catalogue rather than against anything you called before. | Check the name against GET /v1/tools. An unpublished tool is not listed there, and neither is a retired version. | | `Method_Not_Allowed` | 405 | No | Not set | The method is not implemented on that route — in practice a GET on /v1/mcp. The gateway opens no server-initiated stream, because it has nothing to push that is not the answer to a paid POST. | Read the Allow header and use the method it names. | | `key_rate_limited` | 429 | No | Set | Too many requests for this key inside its window, counted after your key is verified and before anything is deducted. This is the rate limit you will actually meet. | Honour Retry-After, which is the seconds left in the window. Spread load across keys only if that reflects real separate workloads. | ## The shape of a refusal Every code is in the body. Most are also in the `X-Nexus-Error` header, so you can branch on them without parsing JSON; the exceptions are the `404`s, the `405` and the `401`, which carry the code in the body only, as the table says. On a `402`, `required` and `X-Nexus-Required-Amount` are the **full price of the call** you tried, in decimal US dollars — not the shortfall. This one call cost five cents: ``` HTTP/1.1 402 Payment Required X-Nexus-Error: Budget_Exhausted X-Nexus-Required-Amount: 0.05 X-Nexus-Currency: USD X-Correlation-ID: 7f3a9c12-4e5b-4d8a-9f01-2b3c4d5e6f70 {"error":{"code":"Budget_Exhausted","required":"0.05","currency":"USD"}} ``` ## Refusals outside this table The table covers the gateway’s named error codes. A request can also be turned away in one of these ways, and none of them is charged: - **`401` `{"error":{"code":"unauthorized"}}`** — the key is missing, unknown, revoked or expired, or too many failed attempts came from your address. Body only, no `X-Nexus-Error`. A creator key (`nx_crt_`) in the key header gets the same 401 with a message saying so. - **`413`** `{"error":"request body too large"}`, **`408`** when the body does not arrive in time, and **`400`** when it cannot be read at all. - **`415`** when the declared `Content-Type` is not JSON in UTF-8. - **A JSON-RPC error at HTTP `200`**: `-32602 Invalid params` for a body that is not a JSON-RPC request, a request with no `id`, a method the gateway does not serve, or a tool name that does not parse. It is a JSON-RPC answer rather than an HTTP refusal, so check the body’s `error` as well as the status. ## The correlation id `X-Correlation-ID` is on every response, success or failure. Log it. It is the one thing that lets us answer a question about a specific call — we do not store your payloads, so it is the handle on a request rather than a copy of it. ## The rule for charges > **If we did not authorize it, we did not bill it** > > A 400, 401, 402, 422, 429 or 503 is never charged. There is no partial charge for a refused request and no fee for being rate limited. > > The only case where a failure costs you is a tool that failed *after* its first byte reached you — the work was done and partly delivered. See [when you are charged](https://www.nexus402.dev/docs/developers/billing/). ## Ask your agent When a call fails, paste the prompt for its code into the agent that wrote the call. Each one is built from this page's table, so it says what the code means, whether you were charged, and what to do, and it tells the agent never to print your key. **`402 Budget_Exhausted`** **Prompt for Budget_Exhausted** ```text A tool call through the Nexus402 MCP gateway (https://api.nexus402.dev/v1/mcp) failed with HTTP 402 Budget_Exhausted. Nexus402 says: The wallet cannot cover this call, or the key's rolling 24-hour cap would be exceeded. Both are reported the same way, deliberately: either way you have hit a ceiling you set. Charged: No. What to do: X-Nexus-Required-Amount (and the body's required) is the call's full price in decimal dollars, not the shortfall. Add funds or raise that key's cap. Find where my code or client config makes this call, explain which of those causes applies here, and fix it. Do not print or log my NEXUS402_API_KEY key. Reference: https://www.nexus402.dev/docs/developers/errors/ ``` **`429 Rate_Limited`** **Prompt for Rate_Limited** ```text A tool call through the Nexus402 MCP gateway (https://api.nexus402.dev/v1/mcp) failed with HTTP 429 Rate_Limited. Nexus402 says: Reserved: nothing in the gateway sends this code today. A 429 that a creator returns is relayed with the creator's own status and body, carries no X-Nexus-Error, and is refunded. The 429 the gateway sends is key_rate_limited. Charged: No. What to do: Honour Retry-After wherever a 429 carries one. Retrying sooner meets the same window and wastes the attempt. Find where my code or client config makes this call, explain which of those causes applies here, and fix it. Do not print or log my NEXUS402_API_KEY key. Reference: https://www.nexus402.dev/docs/developers/errors/ ``` **`502 Upstream_Unavailable`** **Prompt for Upstream_Unavailable** ```text A tool call through the Nexus402 MCP gateway (https://api.nexus402.dev/v1/mcp) failed with HTTP 502 Upstream_Unavailable. Nexus402 says: The creator's endpoint failed, timed out before its first byte, answered in a shape we refuse to relay, or has failed often enough that we stopped dialling it for a cooldown. This 502 is sent only after the charge is voided, or before any was taken. Charged: No. What to do: Retry. A failure after the response began is not a 502: the status stays 200, the payload_truncated trailer is sent, and the charge stands. Find where my code or client config makes this call, explain which of those causes applies here, and fix it. Do not print or log my NEXUS402_API_KEY key. Reference: https://www.nexus402.dev/docs/developers/errors/ ``` **`503 Lock_Unavailable`** **Prompt for Lock_Unavailable** ```text A tool call through the Nexus402 MCP gateway (https://api.nexus402.dev/v1/mcp) failed with HTTP 503 Lock_Unavailable. Nexus402 says: Our own infrastructure could not authorize the call, so we failed closed rather than guess. A metering system that cannot read its own state must refuse, not assume. Charged: No. What to do: Retry with backoff. A 503 is never a silent debit. Find where my code or client config makes this call, explain which of those causes applies here, and fix it. Do not print or log my NEXUS402_API_KEY key. Reference: https://www.nexus402.dev/docs/developers/errors/ ``` **`422 Idempotency_Conflict`** **Prompt for Idempotency_Conflict** ```text A tool call through the Nexus402 MCP gateway (https://api.nexus402.dev/v1/mcp) failed with HTTP 422 Idempotency_Conflict. Nexus402 says: This Idempotency-Key is already bound to a call. A retry of the same request is refused unless that call was refunded, and a different request under the key is always refused. Nothing is replayed, because payloads are never stored. Charged: No. What to do: Check your call log for the first attempt. Use a fresh key for a new request; a key whose call was refunded may be retried. Find where my code or client config makes this call, explain which of those causes applies here, and fix it. Do not print or log my NEXUS402_API_KEY key. Reference: https://www.nexus402.dev/docs/developers/errors/ ``` **`400 Authorization_Rejected`** **Prompt for Authorization_Rejected** ```text A tool call through the Nexus402 MCP gateway (https://api.nexus402.dev/v1/mcp) failed with HTTP 400 Authorization_Rejected. Nexus402 says: Your pass-through Authorization header carried an nx_dev_ token, which would have handed your Nexus key to a creator who could then spend your wallet. Charged: No. What to do: Put the tool's own credential there, never your Nexus key. Find where my code or client config makes this call, explain which of those causes applies here, and fix it. Do not print or log my NEXUS402_API_KEY key. Reference: https://www.nexus402.dev/docs/developers/errors/ ``` **`404 Unknown_Version`** **Prompt for Unknown_Version** ```text A tool call through the Nexus402 MCP gateway (https://api.nexus402.dev/v1/mcp) failed with HTTP 404 Unknown_Version. Nexus402 says: The tool exists but the version you pinned does not, or it has been retired. A published version is immutable, so a new price or endpoint ships as a new version instead of changing the one you pinned. Charged: No. What to do: Drop the @v pin to resolve the highest published version, or pin one that GET /v1/tools still lists. Find where my code or client config makes this call, explain which of those causes applies here, and fix it. Do not print or log my NEXUS402_API_KEY key. Reference: https://www.nexus402.dev/docs/developers/errors/ ``` **`404 Unknown_Tool`** **Prompt for Unknown_Tool** ```text A tool call through the Nexus402 MCP gateway (https://api.nexus402.dev/v1/mcp) failed with HTTP 404 Unknown_Tool. Nexus402 says: Nothing is published under that name. A tool name is creator-handle/mcp-name/tool-name, with an optional @v pin on the middle segment, and it resolves against the published catalogue rather than against anything you called before. Charged: No. What to do: Check the name against GET /v1/tools. An unpublished tool is not listed there, and neither is a retired version. Find where my code or client config makes this call, explain which of those causes applies here, and fix it. Do not print or log my NEXUS402_API_KEY key. Reference: https://www.nexus402.dev/docs/developers/errors/ ``` **`405 Method_Not_Allowed`** **Prompt for Method_Not_Allowed** ```text A tool call through the Nexus402 MCP gateway (https://api.nexus402.dev/v1/mcp) failed with HTTP 405 Method_Not_Allowed. Nexus402 says: The method is not implemented on that route — in practice a GET on /v1/mcp. The gateway opens no server-initiated stream, because it has nothing to push that is not the answer to a paid POST. Charged: No. What to do: Read the Allow header and use the method it names. Find where my code or client config makes this call, explain which of those causes applies here, and fix it. Do not print or log my NEXUS402_API_KEY key. Reference: https://www.nexus402.dev/docs/developers/errors/ ``` **`429 key_rate_limited`** **Prompt for key_rate_limited** ```text A tool call through the Nexus402 MCP gateway (https://api.nexus402.dev/v1/mcp) failed with HTTP 429 key_rate_limited. Nexus402 says: Too many requests for this key inside its window, counted after your key is verified and before anything is deducted. This is the rate limit you will actually meet. Charged: No. What to do: Honour Retry-After, which is the seconds left in the window. Spread load across keys only if that reflects real separate workloads. Find where my code or client config makes this call, explain which of those causes applies here, and fix it. Do not print or log my NEXUS402_API_KEY key. Reference: https://www.nexus402.dev/docs/developers/errors/ ``` --- # Headers > What you send, what comes back, the trailer that says your body is incomplete, and the one credential that is never forwarded. Source: https://www.nexus402.dev/docs/developers/headers/ Everything the gateway reads from you, returns to you, and refuses to pass on. ## What you send | Header | Required | Meaning | | --- | --- | --- | | `X-Nexus-Api-Key` | **Yes** | Your `nx_dev_` key. Never forwarded to a creator | | `Content-Type` | Yes | `application/json` for JSON-RPC | | `Idempotency-Key` | No | Makes a retry safe. See [idempotency](https://www.nexus402.dev/docs/developers/idempotency/) | | `Authorization` | No | The tool's own credential, forwarded untouched. Refused if it carries an `nx_dev_` token | | `Accept`, `MCP-Protocol-Version`, `Mcp-Session-Id` | No | Forwarded so a creator's MCP server can negotiate with your real client | ## What you get back | Header | When | Meaning | | --- | --- | --- | | `X-Correlation-ID` | Always | The id for this call. Quote it if you ask us about a specific request | | `X-Nexus-Price` | On a charged call | What this call cost, in decimal US dollars: `0.05` is five cents. Your receipt for the call you just made. **Absent when nothing was charged** — a free call, or a call that was refunded — so read it as optional | | `X-Nexus-Free-Quota-Remaining` | On every answer from a tool with free calls | How many free calls you have left on that tool this period, as an integer. `0` once they are used up, after which calls are charged | | `X-Nexus-Tool-Version` | On every relayed call | Which published version answered — set whether or not you were charged, so a retry knows what it reached | | `X-Nexus-Error` | On most refusals | The error code, also in the body. **Not set on the `404`s, the `405` or the `401`**, where the code is in the body only — see [every error code](https://www.nexus402.dev/docs/developers/errors/), which states it per code | | `X-Nexus-Required-Amount` | On a `402` | The full price of the call you tried, in decimal US dollars (`0.05`) — not the shortfall | | `X-Nexus-Currency` | On a `402` | `USD` | | `Retry-After` | On a `429` or a `503 Lock_Unavailable` | Seconds to wait. On a `503` it is `1` for a brief blip and `30` when a debit is being unwound or the server is draining | ## The one trailer, and why it matters We cap how much of a creator’s response we will relay. If a response exceeds the cap we **stop copying and send a trailer**, and we send the same trailer if the creator’s stream breaks off part-way: | Trailer | When | Meaning | | --- | --- | --- | | `Nexus-Error: payload_truncated` | Declared by `Trailer: Nexus-Error` on every relayed response; set only when the cap was hit or the stream broke off | The body you received is **incomplete** | > **Truncation is not a status code, and the call is still charged** > > The status stays `200` and the bytes you did receive are real. Nothing in the status line or the headers says anything is wrong, because the headers were sent before we knew. The first byte reached you, so the charge stands — which is the same first-byte rule as everywhere else, and it is why this is worth handling rather than ignoring. A creator cannot forge it: `Nexus-Error` is stripped from whatever they send, so the only one you ever see is ours. **Most HTTP clients do not expose trailers at all.** That is not a gap in this API, it is the state of the ecosystem, so the practical answer differs sharply by language — and where you cannot read it, a truncated JSON-RPC body fails to parse, which is the signal you do get. **Reading the truncation trailer — Go** ``` resp, err := client.Do(req) if err != nil { return err } defer resp.Body.Close() // The trailer is only populated AFTER the body is fully read. payload, err := io.ReadAll(resp.Body) if err != nil { return err } if resp.Trailer.Get("Nexus-Error") == "payload_truncated" { // 200, charged, and short. `payload` is NOT the whole answer. return errors.New("nexus: response truncated") } ``` **Reading the truncation trailer — Node.js** ``` import http from "node:http"; // `fetch` does not expose trailers. The `http` module does, after "end". const request = http.request(GATEWAY, { method: "POST", headers }, (response) => { const chunks = []; response.on("data", (chunk) => chunks.push(chunk)); response.on("end", () => { if (response.trailers["nexus-error"] === "payload_truncated") { // 200, charged, and short. throw new Error("nexus: response truncated"); } handle(Buffer.concat(chunks)); }); }); request.end(body); ``` **Reading the truncation trailer — Python** ``` # You CANNOT read this trailer from Python. CPython's http.client reads the # chunked trailer and discards it (`_read_and_discard_trailer`), and neither # requests nor urllib3 surfaces it. So do not infer completeness from a 200. response = requests.post(GATEWAY, headers=headers, data=body, timeout=130) response.raise_for_status() try: # A truncated JSON-RPC body fails to parse, which is the signal you get. payload = response.json() except ValueError as exc: raise RuntimeError("nexus: response truncated or malformed") from exc ``` **Reading the truncation trailer — Rust** ``` // `reqwest` does not surface trailers. `hyper` delivers them as the final // frame of the body, so read frames rather than collecting to bytes. use http_body_util::BodyExt; let mut response = client.request(request).await?; let mut payload = Vec::new(); while let Some(frame) = response.body_mut().frame().await { let frame = frame?; if let Some(data) = frame.data_ref() { payload.extend_from_slice(data); } if let Some(trailers) = frame.trailers_ref() { if trailers.get("nexus-error").is_some_and(|v| v == "payload_truncated") { // 200, charged, and short. return Err("nexus: response truncated".into()); } } } ``` **Reading the truncation trailer — PHP** ``` **Your Nexus key does not reach the creator** > > `X-Nexus-Api-Key` is consumed by the gateway and stripped. A creator cannot see it, cannot log it and cannot spend your wallet with it. This is also why an `Authorization` header carrying an `nx_dev_` token is refused outright rather than cleaned up: the refusal is unambiguous. ## What the creator receives For completeness, since it explains what a tool can and cannot know about you: the creator gets a correlation id, a signed envelope proving the request came from us, their own creator key, your pass-through `Authorization` if you sent one, and the MCP negotiation headers. They do not get your key, your account, your wallet or your balance. --- # Alerts: webhooks, Slack and Discord > Send what happens to your account to your own systems or your team's channels: the events, the body, the signature and a tested verifier. Source: https://www.nexus402.dev/docs/developers/alerts/ Email is not the only way we tell you something happened. An alert can go to a URL of yours, signed so you can prove it came from us, or into a Slack or Discord channel. Developers and creators both use them: a developer hears that a balance is running low before calls start returning `402`; a creator hears that an endpoint has started failing before the version is de-listed. ## Three kinds of destination | Kind | URL | What it carries | | --- | --- | --- | | **Signed webhook** | Any public HTTPS URL of yours | A JSON body with the event's exact figures, signed with a secret only you and we hold | | **Slack** | A Slack incoming-webhook URL, on `hooks.slack.com` | One line saying what happened and a link to the app. **No amounts** | | **Discord** | A Discord webhook URL, on `discord.com/api/webhooks` | The same line and link. **No amounts** | Slack and Discord URLs must be on those hosts. A “Slack” URL pointing anywhere else would just be an unsigned webhook, so it is refused. > **Why chat channels carry no amounts** > > A channel is read by a whole team, and often by people outside it. So Slack and Discord get what our emails get: what happened, and a link to see the figures in the app. Exact figures go only to a signed webhook, which only your own system receives. ## Setting one up 1. In the account app, open **Profile**, then **Alerts** (`/account/alerts`). 2. Add a destination: choose the kind, give it a label (1 to 60 characters), paste the URL, and tick the events it should receive. You see only the events for the roles your account holds. 3. **For a signed webhook, copy the signing secret now.** It starts `whsec_` and is shown once, when the destination is created, and never again. If you lose it, delete the destination and add it again. 4. Press **Send a test**. A `test` event is delivered within about fifteen seconds, and the destination then shows whether it arrived. An account holds at most **ten destinations**, of any mix of kinds. You can change a destination's events at any time. After you save it, the URL is shown only masked: a Slack or Discord webhook URL is itself the credential that lets anyone post to your channel, so we treat it like the signing secret. Deleting a destination wipes its stored URL and secret and cancels anything still waiting to be delivered to it. ### What URL is accepted - **HTTPS on port 443**, with a certificate a public client trusts. No `http://`, no other port, no user name or password in the URL, no `#fragment`. - **A public address.** A host that resolves to a private, loopback or link-local address is refused (`refused_address`). This is checked when you save, and again at every delivery, so a name that later starts resolving inward is refused then too. - **Redirects are never followed.** A `3xx` answer is a failed delivery. Give us the final URL. ## The events The list is closed: these are every event we send. A new event is added only by a later release, and this page lists it when it is. Each destination receives only the events you ticked for it. | Type | Audience | When | `data` fields | | --- | --- | --- | --- | | `balance.low` | Developer | Your balance fell below your low-balance threshold: a tenth of what your last top-up left it at, the same point as the low-balance email | `balance_micro`, `threshold_micro`, `currency` | | `key.cap_warning` | Developer | A key passed 80% of its spending cap | `key_name`, `key_last4`, `spent_micro`, `cap_micro`, `currency` | | `key.cap_reached` | Developer | A key reached its spending cap | `key_name`, `key_last4`, `cap_micro`, `currency` | | `topup.credited` | Developer | A top-up was credited to your wallet | `amount_micro` (what was credited to your balance), `currency` | | `endpoint.failing` | Creator | A tool's endpoint started failing | `tool`, `version`, `consecutive_failures` | | `version.delisted` | Creator | A tool version was de-listed after repeated failures | `tool`, `version`, `consecutive_failures` | | `withdrawal.paid` | Creator | A withdrawal was paid | `withdrawal_id`, `amount_micro` (before the fee), `fee_micro`, `received_micro`, `currency` | | `margin.changed` | Creator | Your platform margin is changing | `previous_bps`, `margin_bps`, `effective_from` | | `streak.at_risk` | Creator | Your reliable streak is at risk today: an endpoint is failing calls | `day`, `current_days` | | `withdrawal_fee.changed` | Creator | Your withdrawal fee is changing | `old_flat_micro`, `old_bps`, `new_flat_micro`, `new_bps`, `currency`, `effective_at`, `direction`, `reason` | | `milestone.reached` | Both | You reached a milestone | `award_id`, `milestone`, `name`, `scope`. No amount, even for an earnings milestone | | `followed.new_tool` | Both | A creator you follow published a new tool | `creator`, `tool`, `version` | | `followed.new_version` | Both | A creator you follow released a new version | `creator`, `tool`, `version`, `changelog` (at most 200 characters) | | `followed.retired` | Both | A creator you follow retired a tool version | `creator`, `tool`, `version` | | `test` | Both | You pressed **Send a test**. Never subscribable | `message` | - **Money is integer micro-USD in a JSON string**, always: `"1000000"` is one dollar. Never parse it as a float. See [money is a string](https://www.nexus402.dev/docs/developers/money-format/). `currency` is `"USD"`. - **Counts and basis points are JSON numbers**: `consecutive_failures`, `previous_bps` and `margin_bps` (1,000 basis points is 10%). `effective_from` and `created_at` are RFC 3339 times in UTC. - A key is named by its `key_name` and the last four characters of the key, `key_last4`. No event carries a key, a token, a request or response body, a prompt, or anything belonging to another account. ## The webhook body Each delivery is one `POST` with `Content-Type: application/json` and one event: its `id`, its `type`, when it happened (`created_at`) and its `data`. The examples are indented here; what we send is compact, and the signature covers those exact bytes. **An event body — Developer: balance.low** ``` { "id": "evt_3f9c0e0f6a1b4c3d9e8f7a6b5c4d3e2f", "type": "balance.low", "created_at": "2026-11-17T12:00:00Z", "data": { "balance_micro": "412000", "threshold_micro": "500000", "currency": "USD" } } ``` **An event body — Creator: withdrawal.paid** ``` { "id": "evt_0a1b2c3d4e5f60718293a4b5c6d7e8f9", "type": "withdrawal.paid", "created_at": "2026-11-17T12:00:00Z", "data": { "withdrawal_id": "wd_...", "amount_micro": "25000000", "fee_micro": "250000", "received_micro": "24750000", "currency": "USD" } } ``` In `withdrawal.paid`, `received_micro` is what reached you: `amount_micro` minus `fee_micro`, the withdrawal fee. See [payouts](https://www.nexus402.dev/docs/creators/payouts/). A Slack destination receives `{"text": ". Open Nexus402: "}` and a Discord one `{"content": "..."}` with the same words, for example: *Your balance fell below your low-balance threshold. Open Nexus402:* followed by a link to your wallet in the account app. Neither is signed, because Slack and Discord authenticate the URL itself. ## The signature Every webhook delivery carries three headers: **Webhook headers** ```text X-Nexus-Event-Id: evt_... (the body's id) X-Nexus-Webhook-Timestamp: (when this delivery was signed) X-Nexus-Webhook-Signature: v1= ``` The signature is an HMAC-SHA256, keyed with your **whole signing secret as UTF-8 text**, `whsec_` prefix included — copy it as shown and decode nothing. It is computed over the timestamp, one full stop, and the raw body: **The signed string** ```text . ``` - **Verify the raw bytes, before you parse the JSON.** Parsing and re-serialising changes the bytes, and the signature will not match. - **Compare in constant time**: `crypto.timingSafeEqual`, `hmac.compare_digest`, `subtle.ConstantTimeCompare`. An ordinary `==` returns sooner the earlier it finds a difference, which leaks the expected value to anyone who can time your answers. - **Refuse everything if your secret is missing.** Anyone can sign with an empty secret. These verifiers answer `bad_secret`, before reading the delivery, unless the secret starts with `whsec_` and has something after it. That means your setup needs fixing, not the delivery. - **Check the `v1=` prefix.** It names the scheme, so a later one can be added beside it without being mistaken for this one. ### Replay protection: 300 seconds either side Refuse a delivery whose timestamp is more than **300 seconds** from your clock, in **both** directions. Without a lower bound a captured delivery can be replayed at you forever; without an upper one a future-dated one is valid forever. The timestamp is inside the signed string, so it cannot be changed without breaking the signature. Keep your server's clock synchronised; five minutes is room for ordinary drift, not for a clock that is wrong. A retry is signed afresh, with a new timestamp, so a delivery we retry an hour later still verifies. ## A complete verifier One function per language that takes your secret, the raw body and the two header values, and returns whether the delivery is ours and recent, or the reason it is not. Standard library only in each. > **Machine-checked against our real signer** > > Our test suite signs real event bodies with the same function our delivery job signs with, and requires each of these verifiers to accept the genuine signature, including at exactly 300 seconds either side, and to refuse a changed body, a changed timestamp, the wrong secret, a timestamp 301 seconds old or 301 seconds ahead, and a signature without its `v1=` prefix. That runs on every change, so the code below cannot drift from what we send. **examples/webhooks — Node.js** ``` // A Nexus402 alert-webhook verifier for Node.js. NO DEPENDENCIES. // // Copy this file. It is not a package to import, so it can never version-skew // against the platform. `examples/webhooks/webhooks_test.go` signs real bodies // with the platform's own signer (`internal/alerts.Sign`) and refuses to pass // unless this code accepts the genuine signature and refuses every tampered // one, so what you copy is what our tests run. // // Every delivery carries three headers: // X-Nexus-Event-Id the event id, also the body's `id` // X-Nexus-Webhook-Timestamp Unix seconds when the delivery was signed // X-Nexus-Webhook-Signature v1= // // The signed string is `.`, and the HMAC key is your // whole signing secret as UTF-8, `whsec_` prefix included. import { createHmac, timingSafeEqual } from "node:crypto"; /** * How far either side of your clock a timestamp may be: 300 seconds. * Narrower rejects honest deliveries on ordinary clock skew; wider accepts * older replays of a captured delivery. */ export const TOLERANCE_SECONDS = 300; const SIGNATURE_PREFIX = "v1="; // Every signing secret starts with this. const SECRET_PREFIX = "whsec_"; /** * Verify one delivery. Call it with the RAW body bytes, before any JSON * parse: re-serialising changes the bytes and the signature will not match. * * @param {object} input * @param {string} input.secret your destination's signing secret, `whsec_...` * @param {Buffer|Uint8Array} input.rawBody the request body exactly as received * @param {string|undefined} input.timestamp the X-Nexus-Webhook-Timestamp header * @param {string|undefined} input.signature the X-Nexus-Webhook-Signature header * @param {number} [input.nowUnixSeconds] defaults to your clock * @returns {{ ok: boolean, reason: string }} */ export function verifyWebhook({ secret, rawBody, timestamp, signature, nowUnixSeconds = Math.floor(Date.now() / 1000) }) { // First: anyone can sign with an empty secret, so a missing one must // refuse every delivery. This is a mistake in YOUR setup, not in the // delivery: check that your signing secret is set. if (typeof secret !== "string" || !secret.startsWith(SECRET_PREFIX) || secret.length === SECRET_PREFIX.length) { return { ok: false, reason: "bad_secret" }; } // Digits only: a sign, a space or an exponent is not a timestamp we sent. if (typeof timestamp !== "string" || !/^[0-9]{1,15}$/.test(timestamp)) { return { ok: false, reason: "bad_timestamp" }; } // Both directions: without an upper bound a future-dated delivery is valid // forever; without a lower one a captured delivery replays forever. if (Math.abs(nowUnixSeconds - Number(timestamp)) > TOLERANCE_SECONDS) { return { ok: false, reason: "timestamp_out_of_tolerance" }; } if (typeof signature !== "string" || !signature.startsWith(SIGNATURE_PREFIX)) { return { ok: false, reason: "bad_signature_format" }; } const expected = createHmac("sha256", Buffer.from(secret, "utf8")) .update(`${timestamp}.`, "utf8") .update(rawBody) .digest("hex"); const presented = Buffer.from(signature.slice(SIGNATURE_PREFIX.length), "utf8"); // timingSafeEqual throws on a length mismatch. The length of a SHA-256 hex // digest is public (64), so checking it first leaks nothing secret. const want = Buffer.from(expected, "utf8"); if (presented.length !== want.length || !timingSafeEqual(presented, want)) { return { ok: false, reason: "signature_mismatch" }; } return { ok: true, reason: "" }; } // Using it, with node:http. Read the body as bytes, verify, THEN parse: // // const chunks = []; // for await (const chunk of req) chunks.push(chunk); // const rawBody = Buffer.concat(chunks); // const verdict = verifyWebhook({ // secret: process.env.NEXUS_WEBHOOK_SECRET, // rawBody, // timestamp: req.headers["x-nexus-webhook-timestamp"], // signature: req.headers["x-nexus-webhook-signature"], // }); // if (!verdict.ok) { res.writeHead(400).end(); return; } // const event = JSON.parse(rawBody.toString("utf8")); // // Delivery is at least once: drop an event.id you have already handled. // res.writeHead(204).end(); ``` **examples/webhooks — Python** ``` """A Nexus402 alert-webhook verifier for Python. STANDARD LIBRARY ONLY. Copy this file. `examples/webhooks/webhooks_test.go` signs real bodies with the platform's own signer (`internal/alerts.Sign`) and refuses to pass unless this code accepts the genuine signature and refuses every tampered one, so what you copy is what our tests run. Every delivery carries three headers: X-Nexus-Event-Id the event id, also the body's `id` X-Nexus-Webhook-Timestamp Unix seconds when the delivery was signed X-Nexus-Webhook-Signature v1= The signed string is `.`, and the HMAC key is your whole signing secret as UTF-8, `whsec_` prefix included. """ from __future__ import annotations import hashlib import hmac import re import time # How far either side of your clock a timestamp may be: 300 seconds. Narrower # rejects honest deliveries on ordinary clock skew; wider accepts older # replays of a captured delivery. TOLERANCE_SECONDS = 300 _SIGNATURE_PREFIX = "v1=" # Every signing secret starts with this. _SECRET_PREFIX = "whsec_" # ASCII digits only. `str.isdigit` would accept other scripts' digits, and a # sign, a space or an exponent is not a timestamp we sent. _TIMESTAMP = re.compile(r"[0-9]{1,15}") def verify_webhook( secret: str | None, raw_body: bytes, timestamp: str | None, signature: str | None, now: int | None = None, ) -> tuple[bool, str]: """Verify one delivery; returns (ok, reason). Call it with the RAW body bytes, before any JSON parse: re-serialising changes the bytes and the signature will not match. """ # First: anyone can sign with an empty secret, so a missing one must # refuse every delivery. This is a mistake in YOUR setup, not in the # delivery: check that your signing secret is set. if not secret or not secret.startswith(_SECRET_PREFIX) or secret == _SECRET_PREFIX: return False, "bad_secret" if now is None: now = int(time.time()) if timestamp is None or _TIMESTAMP.fullmatch(timestamp) is None: return False, "bad_timestamp" # Both directions: without an upper bound a future-dated delivery is # valid forever; without a lower one a captured delivery replays forever. if abs(now - int(timestamp)) > TOLERANCE_SECONDS: return False, "timestamp_out_of_tolerance" if signature is None or not signature.startswith(_SIGNATURE_PREFIX): return False, "bad_signature_format" expected = hmac.new( secret.encode("utf-8"), timestamp.encode("ascii") + b"." + raw_body, hashlib.sha256, ).hexdigest() presented = signature[len(_SIGNATURE_PREFIX):] # Bytes, not str: compare_digest refuses a str holding non-ASCII text. if not hmac.compare_digest(expected.encode("ascii"), presented.encode("utf-8")): return False, "signature_mismatch" return True, "" # Using it, with any framework that gives you the body as bytes. Verify, # THEN parse: # # ok, reason = verify_webhook( # os.environ["NEXUS_WEBHOOK_SECRET"], # request.body, # bytes, exactly as received # request.headers.get("X-Nexus-Webhook-Timestamp"), # request.headers.get("X-Nexus-Webhook-Signature"), # ) # if not ok: # return 400 # event = json.loads(request.body) # # Delivery is at least once: drop an event["id"] you have already handled. # return 204 ``` **examples/webhooks — Go** ``` // Package webhook verifies Nexus402 alert webhooks. STANDARD LIBRARY ONLY. // // Copy this file into your own package. `examples/webhooks/webhooks_test.go` // signs real bodies with the platform's own signer (`internal/alerts.Sign`) // and refuses to pass unless this code accepts the genuine signature and // refuses every tampered one, so what you copy is what our tests run. // // Every delivery carries three headers: // // X-Nexus-Event-Id the event id, also the body's `id` // X-Nexus-Webhook-Timestamp Unix seconds when the delivery was signed // X-Nexus-Webhook-Signature v1= // // The signed string is `.`, and the HMAC key is your // whole signing secret as UTF-8, `whsec_` prefix included. // // Using it in a handler. Read the body as bytes, verify, THEN parse: // // raw, err := io.ReadAll(io.LimitReader(r.Body, 64<<10)) // if err != nil { http.Error(w, "", http.StatusBadRequest); return } // if err := webhook.Verify(secret, raw, // r.Header.Get("X-Nexus-Webhook-Timestamp"), // r.Header.Get("X-Nexus-Webhook-Signature"), time.Now()); err != nil { // http.Error(w, "", http.StatusBadRequest) // return // } // // json.Unmarshal(raw, &event). Delivery is at least once: // // drop an event.ID you have already handled. // w.WriteHeader(http.StatusNoContent) package webhook import ( "crypto/hmac" "crypto/sha256" "crypto/subtle" "encoding/hex" "errors" "strconv" "strings" "time" ) // ToleranceSeconds is how far either side of your clock a timestamp may be. // Narrower rejects honest deliveries on ordinary clock skew; wider accepts // older replays of a captured delivery. const ToleranceSeconds = 300 const signaturePrefix = "v1=" // Every signing secret starts with this. const secretPrefix = "whsec_" // The reasons a delivery is refused. Each error's text is the same reason // code the Node and Python verifiers return. var ( // ErrBadSecret is a mistake in YOUR setup, not in the delivery: check // that your signing secret is set. ErrBadSecret = errors.New("bad_secret") ErrBadTimestamp = errors.New("bad_timestamp") ErrOutOfTolerance = errors.New("timestamp_out_of_tolerance") ErrBadSignatureFormat = errors.New("bad_signature_format") ErrSignatureMismatch = errors.New("signature_mismatch") ) // Verify checks one delivery against the destination's signing secret. Pass // the RAW body bytes, before any JSON parse: re-serialising changes the bytes // and the signature will not match. A nil error means the delivery is ours // and recent. func Verify(secret string, rawBody []byte, timestamp, signature string, now time.Time) error { // First: anyone can sign with an empty secret, so a missing one must // refuse every delivery. if rest, ok := strings.CutPrefix(secret, secretPrefix); !ok || rest == "" { return ErrBadSecret } // Digits only: strconv.ParseInt alone would accept a leading sign. if timestamp == "" || len(timestamp) > 15 || strings.Trim(timestamp, "0123456789") != "" { return ErrBadTimestamp } seconds, err := strconv.ParseInt(timestamp, 10, 64) if err != nil { return ErrBadTimestamp } // Both directions: without an upper bound a future-dated delivery is // valid forever; without a lower one a captured delivery replays forever. if skew := now.Unix() - seconds; skew > ToleranceSeconds || skew < -ToleranceSeconds { return ErrOutOfTolerance } presented, ok := strings.CutPrefix(signature, signaturePrefix) if !ok { return ErrBadSignatureFormat } mac := hmac.New(sha256.New, []byte(secret)) mac.Write([]byte(timestamp + ".")) mac.Write(rawBody) expected := hex.EncodeToString(mac.Sum(nil)) if subtle.ConstantTimeCompare([]byte(expected), []byte(presented)) != 1 { return ErrSignatureMismatch } return nil } ``` ## Delivery, retries and duplicates - **Answer `2xx` within 10 seconds.** Any `2xx` is success, and the body of your answer is ignored (we read at most 4 KiB of it). Anything else — another status, a redirect, a timeout, a refused connection, a failed TLS handshake — is a failed attempt. If you have slow work to do, answer first and do it afterwards. - **Failed attempts are retried with backoff for 24 hours.** After that the event counts as failed for that destination. - **Delivery is at least once.** A delivery that reached you but whose answer we never saw is sent again, so you can receive the same event twice. Remember the event `id` (also in `X-Nexus-Event-Id`) and drop one you have already handled. - **Do not depend on order.** A retried event can arrive after a newer one. Use `created_at` if order matters to you. - An alert reports something that has already happened. It never holds up a call, a top-up or a payout, and a failed delivery never undoes one. ### When a destination is paused After **20 consecutive failed events** — each one already retried for 24 hours — we pause the destination. It stops receiving, we email the account, and the app shows it as paused. Fix whatever is wrong, then press **Resume** on the destination: that clears the pause and its count of failed events. A paused destination cannot send a test until it is resumed. One delivered event resets the count to zero, so only an unbroken run of failures pauses a destination. The app shows each destination's last success, last failure and its reason, and the status code where there was one: | Reason | What happened | | --- | --- | | `http_status` | Your URL answered with a status that is not `2xx`, a redirect included. The status code is shown beside it | | `timeout` | No answer within 10 seconds | | `connect` | The connection could not be made | | `tls` | The TLS handshake failed, usually a certificate a public client does not trust | | `refused_address` | The host resolved to a private, loopback or link-local address, so we did not connect | | `invalid_url` | The stored URL no longer passes the rules above | | `unsealed` | We could not read the destination's stored URL or secret. This one is ours, not yours; if it persists, delete the destination and add it again | ## What we do to keep this safe - **Your secrets are encrypted at rest**: the signing secret and the Slack and Discord URLs. They are never written to a log, and our own operators see only a destination's host, never its URL. - **Every delivery goes through the same guard as calls to creators' endpoints**: the address is resolved and checked on every connection, so a name cannot be pointed at our internal network after you save it. - **Deliveries come from our background worker**, never from the gateway that serves paid calls, so a slow or failing webhook never slows a tool call. --- # Host a paid tool > Your server can answer only Nexus402: every call we forward is signed. You host an ordinary HTTP endpoint; we route, sign, meter and settle. Source: https://www.nexus402.dev/docs/creators/ We host nothing. You keep your server where you want it — we add the meter. You write an ordinary HTTP endpoint and host it yourself. We route paid calls to it, sign every one so you can prove it came from us, meter the developer’s spend, and settle what we owe you into a double-entry ledger. ## How your endpoint stays yours When your server checks the signature and refuses anything without it, knowing your URL is not enough to call your tool for free. Each line below links to the page that explains it. - [**Signed calls**](https://www.nexus402.dev/docs/creators/verifying/#signature) Every call we forward is signed with Ed25519. Verify it with our public key and refuse the rest; there is nothing on your side worth stealing. - [**Host proof**](https://www.nexus402.dev/docs/creators/quickstart/#host-proof) Before your first publish at a new host, you prove you control it with a file under `/.well-known/nexus402-challenge/`. A host you publish at stays yours. - [**Guarded egress**](https://www.nexus402.dev/docs/creators/requirements/#limits) Calls to creators leave through one SSRF-guarded client: HTTPS on port 443 only, never a private, loopback or link-local address, and a redirect is never followed. - [**Payloads not stored**](https://www.nexus402.dev/privacy/#privacy) Nexus402 does not store or log the contents of tool calls. The gateway reads only the request envelope (method and tool name) to route and bill, and computes a one-way hash. The verifier is copy-paste in [nine languages](https://www.nexus402.dev/docs/creators/verifying/#complete), and each comes as a complete endpoint in a [starter kit](https://www.nexus402.dev/docs/creators/build-a-server/#starters). > **We do not host your code** > > Your tool runs on your infrastructure, under your control, with your own dependencies and deploy process. We add the meter in front of it — which is also why there is nothing of ours for you to install. New here? [**Build a Server**](https://www.nexus402.dev/docs/creators/build-a-server/) takes you from nothing to a published, paid tool with a tested starter kit in Node.js, TypeScript, Python, Go, PHP, Rust, Java, C# or Ruby. The [quickstart](https://www.nexus402.dev/docs/creators/quickstart/) is the same path in five steps. ## Free calls You can let every developer account try a tool for free: from 0 (off, the default) to 1,000 free calls per tool per UTC day, week or month. Set it in the publish wizard for a new tool, or later on the tool’s page; it belongs to the tool, so every version shares it. You earn nothing on a free call, and nobody is charged for it. Your dashboard shows the free calls each tool served in the last 30 days. Details are on [Host and publish](https://www.nexus402.dev/docs/creators/build-a-server/publish/#free-calls). ## Everything in these docs ### Start here - [**Overview**](https://www.nexus402.dev/docs/creators/) What you build, what we do, and who holds what. - [**Quickstart**](https://www.nexus402.dev/docs/creators/quickstart/) Handle, endpoint, publish, paid. Five steps. ### Build a Server - [**Build a Server**](https://www.nexus402.dev/docs/creators/build-a-server/) We host nothing: build the endpoint that serves your tools, with a tested starter kit in nine languages. - [**Host and publish**](https://www.nexus402.dev/docs/creators/build-a-server/publish/) Deploy it where you like, prove the host, publish a price, test and troubleshoot. ### The contract - [**Verifying a request**](https://www.nexus402.dev/docs/creators/verifying/) The creator key, the six-field signature, and why both exist. - [**Endpoint requirements**](https://www.nexus402.dev/docs/creators/requirements/) HTTPS, timeouts, size caps, streaming, and what we refuse. - [**Versions are immutable**](https://www.nexus402.dev/docs/creators/versions/) Why a published price can never change, and how to ship v2. ### Getting paid - [**When you earn**](https://www.nexus402.dev/docs/creators/settlement/) Our 10% margin, when a call settles, and when it does not. - [**Payouts**](https://www.nexus402.dev/docs/creators/payouts/) Stripe Connect, the $5 minimum, holds, and the emailed code each withdrawal needs. - [**When calls do not arrive**](https://www.nexus402.dev/docs/creators/endpoint-health/) Reading your endpoint health, and what de-listing means. ## Who holds what | Thing | Who holds it | | --- | --- | | Your tool’s code and infrastructure | **You** | | Your bank details | **Stripe.** We hold a reference and capability flags, never the account itself | | The creator key | You, after it is shown once. We keep only a derived value | | The signing private key | **Us.** You only ever need the public half | | Request and response payloads | **Nobody.** They transit and are never stored | | The record of what we owe you | An append-only double-entry ledger. A correction is a new row, never an edit | > **Payouts are capped per day** > > You can publish, earn and request a withdrawal today, and withdrawals are paid through Stripe Connect. The total paid to all creators each day is capped, so a withdrawal can be paid on a later day than you request it, and Stripe sets when funds reach your bank — please do not plan revenue against a fixed date. Recent earnings are also held for a while before they are withdrawable; see [when you can withdraw it](https://www.nexus402.dev/docs/creators/settlement/#holds). --- # Publish a paid tool > Five steps from nothing to a paid call, and what your endpoint has to check and return. Source: https://www.nexus402.dev/docs/creators/quickstart/ Five steps from nothing to a paid call. We host nothing: you keep your server where you want it, and we add the meter. The Nexus-specific code is a signature check and one response header; everything else is the HTTP endpoint you would have written anyway. For a guided build with a complete server, see [Build a Server](https://www.nexus402.dev/docs/creators/build-a-server/). ## The five steps 1. **Sign in** with Google, GitHub or Apple and choose the **creator** role. There is no password and no sign-up form — the provider is the account. 2. **Claim a handle.** This is your namespace, like `acme`. One per account, and it is never released. The answer carries your `nx_crt_` creator key, **shown once**, and the public key you verify our signature with. 3. **Stand up an endpoint** behind HTTPS. Start from a [starter kit](https://www.nexus402.dev/docs/creators/build-a-server/#starters) in your language — each has the whole contract already handled. 4. **Publish a version** with its price and endpoint. The first time at a host, you [prove you control it](#host-proof) with one static file, and every publish sends your endpoint [the hello](https://www.nexus402.dev/docs/creators/verifying/#hello), which it must answer with the proof. 5. **Connect Stripe** when you want to withdraw. Earnings accrue without it, so this can wait. > **Your endpoint must be reachable over HTTPS before you publish** > > Publishing validates the URL immediately: plain HTTP is refused for any non-loopback host, and so are private, loopback and link-local addresses. Have TLS terminating first or the publish is rejected. ## How a tool is named A tool is addressed by three parts and a version, which together make the name a developer puts in their client: **A tool name** ```text acme/payments/charge the handle, the MCP server, the tool acme/payments@v2/charge pinned to a specific version ``` The pin goes on the MCP server segment, not after the tool. A developer who does not pin a version gets the highest published one, with one exception: a version priced at more than twice the lowest price unpinned callers paid over the last seven days is held from them for seven days, and the publish answer says so in `unpinned_from` and `price_notice`. Pinned callers reach it as soon as it is callable. See [price rises](https://www.nexus402.dev/docs/creators/versions/#price-rise). That is also why a handle is never released: a freed name could be claimed by someone else, who could publish a higher version and collect calls meant for you. ## The publish request The account app's publish wizard is the supported way. The underlying request, if you prefer to script it, is authenticated by your session cookie and, like every cookie-authenticated change, needs the `X-Nexus-CSRF` header set to the value of your `__Host-nexus_csrf` cookie: **POST /v1/creator/tools** ```bash curl -s https://api.nexus402.dev/v1/creator/tools \ -H "Content-Type: application/json" \ -H "X-Nexus-CSRF: $YOUR_CSRF_COOKIE_VALUE" \ --cookie "$YOUR_SESSION_COOKIES" \ -d '{ "handle": "acme", "mcp": "payments", "tool": "charge", "version": "v1", "price_micro": "50000", "endpoint": "https://mcp.acme.example/mcp", "description": "Charges a card and returns the receipt id.", "input_schema": { "type": "object", "properties": {} } }' ``` - `price_micro` is **integer micro-USD as a string**. `"50000"` is five cents. Never a JSON number. It must be above zero and at most **$5.00** (`"5000000"`) by default; a higher price is refused with `price_above_ceiling`. - `version` is `v` followed by a number. - `description` and `input_schema` are what the marketplace shows. A tool with no description says so plainly on its card, which is pressure on the person who can fix it rather than a broken listing. ## The first publish at a new host The first time you publish at a host, that host has to prove you control it. The publish answers `403 host_proof_required` with a `challenge_url` and a `challenge_content`. Nothing was published by that attempt. **The file to serve, once per host** ```text GET https://mcp.acme.example/.well-known/nexus402-challenge/ 200 OK nexus402-host-proof-v1: ``` - Serve `challenge_content` as the **whole body**. A static file is enough, and a trailing newline is fine. Then publish again. - It goes at the **root of the host**, not under your tool's path, and must answer `200` with **no redirect**. If a CDN or proxy sits in front, make sure it passes `/.well-known/` through. - You do this **once per host**. After a version is live there, the host stays proven for every tool you publish at it, and you can delete the file. - The token and content are derived from your creator id and the host, so your file proves nobody else and nobody else's file proves you. A host another creator already publishes at stays theirs. If you share a domain with other tenants, use a hostname of your own; a subdomain is enough. - Moving an existing tool to a new host also needs the emailed publish code. The host proof is checked first. > **The creator key is shown once** > > We store only a derived value and cannot show it again. If you lose it, rotate it in Creator settings; we email you a code first, so a stolen login cannot do it. The gateway starts sending the new key within 30 seconds, and calls fail until your server accepts it, so have the deploy ready and accept both keys until it is out. --- # Endpoint requirements > Timeouts, size caps, streaming, and what the gateway refuses to relay. Source: https://www.nexus402.dev/docs/creators/requirements/ What the gateway expects of your endpoint, and what it refuses to pass on. ## The limits | Requirement | Value | | --- | --- | | Scheme | **HTTPS on port 443.** An explicit `:443` is the same endpoint; any other port is refused at publish and on every call. Private, loopback and link-local addresses are refused at publish, and on every call the name is resolved again: if **any** address it resolves to is private or reserved, the connection is refused | | Response header | **`X-Nexus-Proof` on every response.** Without it a call is voided: you are not paid and the developer is not charged. See [verifying](https://www.nexus402.dev/docs/creators/verifying/) | | Host proof | Once per host, before your first publish there: serve the file the refusal names, under `/.well-known/nexus402-challenge/` at the root of the host. See [the first publish at a new host](https://www.nexus402.dev/docs/creators/quickstart/#host-proof) | | First byte | Within **5 seconds** of idle at any point | | Whole response | Within **120 seconds** | | Response size | **10 MiB**, enforced while streaming | | Method | Always `POST`: a tool call, and the empty-body [hello](https://www.nexus402.dev/docs/creators/verifying/#hello). The only `GET` is the once-per-host proof file | | Connections | Up to **64 concurrent** per creator host | > **The 5-second rule is about idle GAPS, not total duration** > > A tool that takes a minute is fine as long as it keeps producing output. Send your first byte quickly, then stream. What is refused is going quiet for five seconds, because from our side that is indistinguishable from a hung endpoint and a developer is waiting. ## What to return Return the MCP result object as JSON, for example `{"content":[{"type":"text","text":"..."}]}`. The developer's client sent a JSON-RPC request and waits for a JSON-RPC response with the same `id`. On a successful call the gateway writes that envelope around your body and streams your bytes through without reading them. Do not add `jsonrpc`, `id` or `result` yourself: the client would receive your answer wrapped twice. A `2xx` is relayed only if it carries a valid `X-Nexus-Proof`; without one the developer gets `502` instead. A non-2xx answer is relayed with its body, after the screening [below](#refused). ## Streaming Server-sent events are supported and are the right shape for a long-running tool. The gateway relays your bytes without buffering the whole response, so a developer sees output as you produce it. A `text/event-stream` answer is the one body the gateway does not wrap, so each event must already carry a complete JSON-RPC message. If you fail *after* the first byte has reached the developer, the charge stands: they received part of the work and you did it. If you fail *before* anything reached them, they are refunded automatically and you are not paid. That boundary is the whole of the billing rule. ## What the gateway refuses to relay Your response passes through unread, with these exceptions, each of which exists because relaying it would hurt the developer or impersonate us: | Header or status | What happens | Why | | --- | --- | --- | | `1xx`, `3xx`, or any status outside `200`–`599` | Clamped to `502` | We never follow a redirect. Relaying one would make a stock client resend the developer's credentials to a host you chose; an upgrade or a malformed status has no meaning to relay | | `Location`, `Content-Location`, `Refresh` | Stripped | Same reason: they steer a client elsewhere | | `Content-Encoding`, `Content-Length` | Stripped | We never request compression, so relaying it would make a client inflate an unbounded body past the response cap. The length is the gateway's to set | | `Set-Cookie` | Stripped | A creator does not get to set state in a developer's client | | `X-Correlation-Id`, `Nexus-Error`, every `X-Nexus-*` | Stripped | These are the gateway's own headers. A creator setting them would be indistinguishable from us | | Hop-by-hop headers (`Connection`, `Keep-Alive`, `Transfer-Encoding`, `Upgrade`, `Trailer`, `TE`, `Proxy-*`) and any header named in `Connection` | Stripped | They describe your connection to us, not ours to the developer | | `402` | Clamped to `502` | `402` is the gateway's own code for an exhausted wallet. A creator returning it would be indistinguishable from us | ## The circuit breaker If your endpoint fails repeatedly, a per-process breaker opens and calls are refused for a cooldown rather than queued against you. After the cooldown, one trial call is let through; if it succeeds the breaker closes, and if it fails it stays open for another cooldown. That protects developers from waiting on a dead endpoint and protects you from a thundering retry herd. Separately, a version whose endpoint is at fault on **20 consecutive** calls is **de-listed**: retired, out of the catalog, and sent no calls. It is **not** restored when your endpoint recovers, because nothing is routed to it any more. Re-publish the same version with the same price, endpoint and currency to restore it. The version is not deleted and your published name is never released. See [endpoint health](https://www.nexus402.dev/docs/creators/endpoint-health/), and what counts as a fault on [verifying](https://www.nexus402.dev/docs/creators/verifying/#proof). ### What to expose Nothing is required, but a cheap unauthenticated health route is worth having for your own monitoring. Do not put your tool behind it: the gateway only ever calls the endpoint you published. --- # Build a Server > We host nothing. You keep your server where you want it — we add the meter. Source: https://www.nexus402.dev/docs/creators/build-a-server/ This guide takes you from nothing to a published, paid MCP tool. You write and run the server; Nexus402 puts a meter in front of it. This page builds the server. [Host and publish](https://www.nexus402.dev/docs/creators/build-a-server/publish/) deploys it, connects it, publishes it and tests it. In your Nexus402 account On your own server 1. Sign in creator role Google, GitHub or Apple. No password. (in your Nexus402 account) 2. Claim a handle get nx_crt_ key Your name in every tool's address. The key is shown once. (in your Nexus402 account) 3. Build your endpoint A starter kit in your language checks each request is ours. (on your own server) 4. Host it anywhere, HTTPS Any host that serves HTTPS. Nothing of ours to install. (on your own server) 5. Publish price + proofs Set a fixed price per call; we check the endpoint answers. (in your Nexus402 account) 6. Get called metered, paid Each call is charged up front; you are owed your share. (in your Nexus402 account) Then, on every paid call 1. An agent calls with its key 2. Nexus402 charges the price, signs the request 3. Your endpoint checks the signature, answers 4. You are owed your share of every paid call From sign-in to your first paid call: two steps in your account, two on your own server, then publish and get called. ## The server ecosystem Developers do not connect to your server. They connect one MCP client to the Nexus402 gateway, which lists every published tool from every creator as one MCP server. When an agent calls your tool, the gateway checks the developer's key, charges your fixed price from their pre-funded wallet, and forwards the call to **your** server, signed. You answer; the gateway relays your answer and credits you the price less our margin (10% today). - **You own the infrastructure.** Your code, your host, your region, your logs, your upstream API keys. We never deploy, copy or proxy-store your server. Move it, scale it or rewrite it whenever you like; publish a new version to change its address. - **We own the meter.** Accounts, keys, wallets, caps, charging, refunds, the ledger and payouts. You write no billing code. - **The boundary is one HTTPS request.** A signed `POST` in, your result and a proof header out. That is the whole contract. The full picture, with diagrams, is [How Nexus402 works](https://www.nexus402.dev/docs/how-it-works/). ## What you are building An **MCP tool endpoint**: the part of an MCP server that runs tools. The gateway is the MCP server developers talk to, so it handles the protocol around your tools for you: | MCP message | Who answers it | | --- | --- | | `initialize`, `ping`, notifications | The gateway. Never forwarded to you | | `tools/list` | The gateway, from the description and input schema you publish with each version | | `tools/call` | **Your endpoint**, after the gateway has charged for it | > **Already have an MCP server built with an SDK?** > > Do not publish its URL as it is. An SDK server usually expects an `initialize` and a session before a `tools/call`, and it returns its own JSON-RPC envelope — which the gateway would wrap a second time. It also does not answer the hello or send the proof. > > Run [`verify-proxy`](https://github.com/Nexus-402/verify-proxy) beside it instead, and change none of its code. It is the public endpoint you publish: it checks every request exactly as the starter kits do, answers the hello and the host proof, passes each paid call to your server with the arguments untouched, and returns the result with the proof. It speaks Streamable HTTP, the older HTTP + SSE transport and stdio, and `verify-proxy tools` prints your tools ready for the publish form. Keep your server on a private address, so nothing reaches it except through the proxy. Open source under the Apache License 2.0, and tested with the starter kits’ own contract. ## Tools and setup - **A language with an HTTP server, SHA-256 and Ed25519.** There is a [tested starter kit](#starters) for Node.js, TypeScript, Python, Go, PHP, Rust, Java, C# and Ruby. Node.js, Go, PHP and Java do Ed25519 in their standard libraries, so those kits need no crypto package. - **A hostname with HTTPS on port 443** that resolves only to public addresses. Plain HTTP and private, loopback and link-local addresses are refused. - **Your creator key**, `nx_crt_…`. It is in the answer when you [claim your handle](https://www.nexus402.dev/docs/creators/build-a-server/publish/#connect), shown once. Keep it in a secret store or environment variable, never in your repository. - **The gateway's public key**, from `GET https://api.nexus402.dev/v1/signing-key`. It lists the current key first and any key being retired after it: accept a signature from any of them, and re-read the list now and then so a rotation is not an outage. ## The request you receive Every paid call is a `POST` to the exact URL you published, over HTTP/1.1. The body is the developer's MCP request, byte for byte: **The body of a tools/call** ```json {"jsonrpc":"2.0","id":7,"method":"tools/call", "params":{"name":"acme/text/word_count","arguments":{"text":"we add the meter"}}} ``` | Header | What it is | | --- | --- | | `X-Nexus-Signature` | `ed25519:` and a base64 signature over six lines: method, the host you published, path with query, timestamp, correlation id, and the lowercase hex SHA-256 of the raw body | | `X-Nexus-Timestamp` | Unix seconds. Refuse anything more than 60 seconds from your clock, either way | | `X-Correlation-ID` | An opaque id for this request (a UUID on paid calls). It is in the signature and the proof | | `X-Nexus-Creator-Key` | Your `nx_crt_` key. Compare it in constant time | | `Authorization` | Only if the developer sent their own credential for your service. Never a Nexus key: the gateway refuses to forward one | | `Content-Type` | Always `application/json` | | `MCP-Protocol-Version`, `Mcp-Session-Id`, `Accept` | Passed through when the developer's client sent them | | `X-Nexus-Test: 1` | Only on a test call you started yourself. It is not billed | The developer's Nexus key is never sent to you. Verify the signature against the host you *published*, not the inbound `Host` header, which a proxy may rewrite. The exact procedure and tested verifiers are on [Verifying a request](https://www.nexus402.dev/docs/creators/verifying/). ## The hello When you publish, the gateway sends your endpoint one signed `POST` with an **empty body** and **no creator key**, and publishes only if you answer it `2xx` with the proof. It sends the same hello later to decide whether a refusal of yours was deliberate. Verify its signature, skip the key check, run no tool, and answer `200` with the proof. Every sample here does this. ## The response you send - **Return the bare MCP result**, such as `{"content":[{"type":"text","text":"4"}]}`, with `Content-Type: application/json`. The gateway wraps it as the JSON-RPC response to the developer's request, so do not add `jsonrpc` or `id` yourself. To stream, answer `text/event-stream` with each event already a complete JSON-RPC message; that is relayed unwrapped. - **Set `X-Nexus-Proof` on every answer** to a verified request, errors included, before the status line goes out: `sha256:` and the unpadded base64url SHA-256 of `nexus-endpoint-proof-v1`, the correlation id, the timestamp and the signature header, joined by newlines. A `2xx` without a valid proof is voided: the developer is not charged and you are not paid. - **Choose the status by who should pay.** `2xx` is a paid call, even with `"isError": true` in the result. Any `4xx` or `5xx` refunds the developer and is relayed with your body. A proved `4xx` is a deliberate refusal and never counts against your endpoint; a `5xx` always does. So a developer never pays for your failure: when your tool itself fails, answer a `5xx`; when the request is wrong before any work, a `4xx`; and keep `"isError": true` for a call the caller’s input made fail after your tool did work. | Limit | Value | | --- | --- | | Connect and TLS handshake | 5 seconds | | Until your response headers | 5 seconds, and no more than 5 seconds of silence at any point | | Whole call | 120 seconds | | Response size | 10 MiB; a longer stream is cut, and the charge stands once it has started | | Redirects | Never followed | | Connections to your host | At most 64 at once | The full list, including which response headers are stripped, is on [Endpoint requirements](https://www.nexus402.dev/docs/creators/requirements/). ## Creating and exposing tools Each tool you publish is named `handle/server/tool`, for example `acme/text/word_count`, and each version of it is published with its own price, endpoint URL, description and input schema. The description and schema are what developers' agents see in `tools/list`, so write them for a model choosing a tool: say what it does, when to use it, and what each argument means. - **Server and tool names**: up to 64 characters of letters, digits, `_`, `.` and `-`, starting with a letter, digit or `_`. Keep them short: MCP clients add a prefix, and Cursor drops a tool whose combined name passes 60 characters. Clients see a tool as `handle_server_tool`, its *listed name* (every character other than letters, digits, `_` and `-` becomes `_`), so a new tool whose listed name another tool already has, ignoring case, is refused with `409 listed_name_taken`. - **One endpoint can serve several tools.** Publish each tool with the same URL and dispatch on `params.name`: its last segment is the tool. A developer who pins a version writes it on the server segment (`acme/text@v2/word_count`), so read the last segment rather than matching the whole name. - **Arguments** arrive in `params.arguments` exactly as the developer's agent sent them. Validate them against your own schema; the gateway does not. In every [starter kit](#starters), everything you change is in one function near the top of its main file (`runTool`, `run_tool` or `RunTool`). It receives the tool name and the arguments and returns a status and the MCP result; the kits ship one example tool, `word_count`. ## Authentication and configuration Two checks protect you, and you want both. The **creator key** is a shared secret: it proves the request came through your Nexus402 account. The **signature** proves the gateway sent this exact request to your host within the last minute, so a captured request cannot be used at another host and stops working after 60 seconds. It can still be replayed to you within those 60 seconds, so **make your tool’s side effects idempotent**: running the same call twice must change things once. `X-Correlation-ID` is signed and different for every paid call, so you can record it with the change and skip one already there. The samples take four settings from the environment: **Configuration** ```bash PORT=8080 # where the server listens NEXUS_REGISTERED_HOST=mcp.acme.example # the host in the URL you publish NEXUS_CREATOR_KEY=nx_crt_... # from claiming your handle; shown once NEXUS_PUBLIC_KEY= # from GET /v1/signing-key; comma-separate several ``` If your tool calls a paid upstream API, keep that credential on your server too. If each developer should bring their own, read it from the `Authorization` header the gateway passes through. ## Starter kits A complete endpoint in each of nine languages: the hello, both checks, tool dispatch and the proof, with one example tool. Pick yours, download the kit or copy its files, set the four variables and run it. Every kit refuses to start without the three `NEXUS_` ones. > **Every kit is tested on every change** > > Our test suite copies each kit’s files into an empty folder, exactly as you download them, builds it there and sends it the gateway’s real hello, a real signed call and seven forged ones, which it must refuse. The code below and in each `.zip` is the code that test ran. The kits are open source under the Apache License 2.0: use, change and ship them, commercially too; each `.zip` carries the `LICENSE` and `NOTICE`. All nine are also on GitHub at [Nexus-402/starters](https://github.com/Nexus-402/starters), a read-only copy of the code this test ran. **Node.js.** Node.js 18 or later. No dependencies. Download the Node.js kit (.zip) **Run the Node.js kit** ```bash export PORT=8080 export NEXUS_REGISTERED_HOST=mcp.you.example # the host in the URL you publish export NEXUS_CREATOR_KEY=nx_crt_... # shown once when you claim your handle export NEXUS_PUBLIC_KEY= # GET https://api.nexus402.dev/v1/signing-key node server.mjs ``` **`server.mjs` your tools are here** **server.mjs** ```javascript // A complete Nexus402 creator endpoint for Node.js 18 or later. NO DEPENDENCIES. // // Copy this file and `verify.mjs` beside it, set four environment variables, // put it behind HTTPS, and publish its URL. `../starters_test.go` copies this // kit into an empty directory, starts it and drives it with the gateway's REAL // signer, so what the creator docs show is what our gate runs. // // Nexus402 hosts nothing: this runs wherever you run it. The gateway sends it // signed MCP `tools/call` requests and meters them; `initialize`, // `tools/list` and notifications never reach you, because the gateway answers // them from your published description and input schema. // // PORT where to listen (default 8080) // NEXUS_REGISTERED_HOST the host you published, e.g. mcp.acme.example // NEXUS_CREATOR_KEY your nx_crt_ key, shown once when you claimed a handle // NEXUS_PUBLIC_KEY the gateway's Ed25519 key(s), base64, comma-separated // (GET https://api.nexus402.dev/v1/signing-key lists them) import { createServer } from "node:http"; import { publicKeyFromBase64, verifyRequest } from "./verify.mjs"; // The gateway's own cap on a request body. Anything larger did not come from it. const MAX_BODY_BYTES = 10 * 1024 * 1024; function required(name) { const value = (process.env[name] ?? "").trim(); if (value === "") { throw new Error(`${name} is not set`); } return value; } const config = { port: Number(process.env.PORT ?? 8080), registeredHost: required("NEXUS_REGISTERED_HOST"), creatorKey: required("NEXUS_CREATOR_KEY"), // More than one while the gateway rotates its key: accept any of them. publicKeys: required("NEXUS_PUBLIC_KEY") .split(",") .map((key) => publicKeyFromBase64(key.trim())), }; /** * YOUR TOOLS. The gateway sends the full published name in `params.name`, * e.g. `acme/text@v2/word_count`; the last segment is the tool. * * Return the bare MCP result object. The gateway wraps it in the JSON-RPC * envelope for the developer, so returning your own envelope would nest it. * A result with `isError: true` is still a successful, CHARGED call: use it * only when the caller's input made your tool fail after it did work. When your tool itself fails, return a 5xx; when the * request is wrong before any work, a 4xx. Both refund the caller. */ function runTool(tool, args) { switch (tool) { case "word_count": { const text = typeof args?.text === "string" ? args.text : ""; const words = text.trim() === "" ? 0 : text.trim().split(/\s+/).length; return { status: 200, result: { content: [{ type: "text", text: String(words) }] } }; } default: return { status: 404, result: { error: `unknown tool ${tool}` } }; } } function readBody(request) { return new Promise((resolve, reject) => { // ONE buffer that grows, never a list of the pieces: a body sent a byte // at a time would make that list hundreds of times the limit. let body = Buffer.allocUnsafe(64 * 1024); let size = 0; request.on("data", (chunk) => { if (size + chunk.length > MAX_BODY_BYTES) { reject(new Error("body too large")); request.destroy(); return; } if (size + chunk.length > body.length) { const larger = Buffer.allocUnsafe(Math.max(2 * body.length, size + chunk.length)); body.copy(larger, 0, 0, size); body = larger; } size += chunk.copy(body, size); }); request.on("end", () => resolve(body.subarray(0, size))); request.on("error", reject); }); } function verify(request, rawBody) { let verdict = { ok: false, reason: "no public key" }; for (const publicKey of config.publicKeys) { verdict = verifyRequest({ headers: request.headers, rawBody, method: request.method, // The request target exactly as sent: path plus query, not re-encoded. pathWithQuery: request.url, registeredHost: config.registeredHost, creatorKey: config.creatorKey, publicKey, }); if (verdict.ok) { return verdict; } } return verdict; } // Sends a JSON answer with the proof. The proof goes on EVERY answer to a // verified request, errors included: a 4xx you prove is a refusal the caller // is refunded for, not a fault against your endpoint. function answer(response, status, proof, body) { response.writeHead(status, { "Content-Type": "application/json", "X-Nexus-Proof": proof }); response.end(body === undefined ? "" : JSON.stringify(body)); } const server = createServer(async (request, response) => { if (request.method !== "POST") { response.writeHead(405, { Allow: "POST" }).end(); return; } let rawBody; try { rawBody = await readBody(request); } catch { response.writeHead(413).end(); return; } const verdict = verify(request, rawBody); if (!verdict.ok) { // No detail in the body: a reason tells a prober how close they are. console.warn(`refused: ${verdict.reason}`); response.writeHead(401, { "Content-Type": "text/plain" }).end("unauthorized"); return; } // THE HELLO: the signed, empty-body check the gateway sends when you // publish. Answer with the proof and run nothing. if (verdict.hello) { answer(response, 200, verdict.proof); return; } let call; try { call = JSON.parse(rawBody.toString("utf8")); } catch { answer(response, 400, verdict.proof, { error: "body is not JSON" }); return; } const name = typeof call?.params?.name === "string" ? call.params.name : ""; const tool = name.slice(name.lastIndexOf("/") + 1); const { status, result } = runTool(tool, call?.params?.arguments); answer(response, status, verdict.proof, result); }); server.listen(config.port, () => { console.log(`listening on :${config.port} for ${config.registeredHost}`); }); ``` **`verify.mjs` javascript** **verify.mjs** ```javascript // A complete Nexus402 request verifier for Node.js. NO DEPENDENCIES. // // Copy this file. It is not a package to import, so it can never version-skew // against the gateway — the same reasoning as `examples/creator-pingback`. // // `agreement_test.go` beside this directory drives the gateway's REAL signer // (`egress.DevSigner`, the one `cmd/gateway` uses) against this code and // refuses to pass if the two ever disagree on the canonical string. That test // is what makes this documentation rather than a guess: a verifier can be // perfectly self-consistent and still disagree with the gateway, and then // every creator who copies it gets a dead endpoint and no clue why. // // Two checks, and you want both. The creator key is a shared secret on your // server; if it leaks, anyone can impersonate Nexus402 to you and take free // tool calls. The signature is asymmetric — you hold only a public key — and // it is also what binds a request to YOUR host and to a 60-second window, so // losing it loses both. The window LIMITS a replay of the same request, it // does not stop one: make your tool's side effects idempotent. import { createHash, createPublicKey, timingSafeEqual, verify } from "node:crypto"; /** * The fixed first line of the response proof's digested bytes. * * Copy it exactly. It is part of the contract, and it exists so this digest * can never be confused with another defined over the same fields. */ export const PROOF_DOMAIN = "nexus-endpoint-proof-v1"; /** * Must match the gateway's 60 seconds. Wider accepts older replays; narrower * rejects honest requests on ordinary clock skew. */ export const SIGNATURE_WINDOW_SECONDS = 60; // An Ed25519 public key arrives as 32 raw bytes in base64. `createPublicKey` // wants DER, and for Ed25519 the SPKI header is a fixed 12-byte prefix, so // wrapping is a concatenation rather than a dependency. const SPKI_ED25519_PREFIX = Buffer.from("302a300506032b6570032100", "hex"); /** Wraps the 32 raw bytes Nexus402 gives you into a usable KeyObject. */ export function publicKeyFromBase64(base64) { const raw = Buffer.from(base64, "base64"); if (raw.length !== 32) { throw new Error(`ed25519 public key must be 32 bytes, got ${raw.length}`); } return createPublicKey({ key: Buffer.concat([SPKI_ED25519_PREFIX, raw]), format: "der", type: "spki", }); } /** * Lowercase hex SHA-256 of the RAW body bytes. * * Hash before any JSON parse or re-serialise: re-encoding changes the bytes * and the hash will not match. */ export function bodyHashHex(rawBody) { return createHash("sha256").update(rawBody).digest("hex"); } /** * The signed message: six fields joined by single newlines, in this order. * * No trailing newline, no spaces, no carriage returns. `host` is the host you * REGISTERED, never the inbound `Host` header — behind a proxy or a managed * platform router that header may have been rewritten, and a verifier reading * it will then reject every valid request. */ export function canonicalString({ method, registeredHost, pathWithQuery, timestamp, correlationId, bodySha256Hex, }) { return [method, registeredHost, pathWithQuery, timestamp, correlationId, bodySha256Hex].join("\n"); } /** * Constant-time string compare. * * `timingSafeEqual` throws when the lengths differ, and the throw is itself a * length oracle, so both sides are hashed to a fixed width first. A * byte-at-a-time `===` returns faster the earlier it finds a difference, * which leaks the key one position at a time to anyone who can measure your * response. */ export function constantTimeEquals(presented, expected) { const left = createHash("sha256").update(String(presented), "utf8").digest(); const right = createHash("sha256").update(String(expected), "utf8").digest(); return timingSafeEqual(left, right); } /** The value Nexus402 requires on EVERY response, including your own errors. */ export function proof({ correlationId, timestamp, signature }) { const digest = createHash("sha256") .update([PROOF_DOMAIN, correlationId, timestamp, signature].join("\n"), "utf8") .digest("base64url"); return `sha256:${digest}`; } /** * Verifies one inbound request. * * Returns `{ ok: true, hello, proof }` — set that proof on your response * BEFORE you write the status, because once the header block is committed * anything set afterwards is dropped in silence. On failure, * `{ ok: false, reason }`. * * THE HELLO (ADR-0143). When you publish, and again when Nexus402 checks a * refusal of yours, it sends one signed POST with an EMPTY body and NO creator * key: there is no caller yet. `hello` is true for that request. Answer it * `200` with the proof and run no tool. The signature is still verified, so a * stranger cannot fake one; the key check is what is skipped, because without * that exception the hello is refused and you can never publish. */ export function verifyRequest({ headers, rawBody, method, pathWithQuery, registeredHost, creatorKey, publicKey, nowUnixSeconds = Math.floor(Date.now() / 1000), }) { const header = (name) => headers[name] ?? headers[name.toLowerCase()] ?? ""; const hello = rawBody.length === 0; if (!hello && !constantTimeEquals(header("X-Nexus-Creator-Key"), creatorKey)) { return { ok: false, reason: "creator key mismatch" }; } const timestamp = header("X-Nexus-Timestamp"); const seconds = Number(timestamp); if (!Number.isInteger(seconds)) { return { ok: false, reason: "timestamp is not an integer" }; } // BOTH directions. Without an upper bound a future-dated request is valid // forever; without a lower one a captured request replays forever. if (Math.abs(nowUnixSeconds - seconds) > SIGNATURE_WINDOW_SECONDS) { return { ok: false, reason: "timestamp outside the 60-second window" }; } const presented = header("X-Nexus-Signature"); if (!presented.startsWith("ed25519:")) { return { ok: false, reason: "signature is not ed25519:" }; } const signatureBytes = Buffer.from(presented.slice("ed25519:".length), "base64"); if (signatureBytes.length !== 64) { return { ok: false, reason: "signature is not 64 bytes" }; } const correlationId = header("X-Correlation-ID"); const message = Buffer.from( canonicalString({ method, registeredHost, pathWithQuery, timestamp, correlationId, bodySha256Hex: bodyHashHex(rawBody), }), "utf8", ); if (!verify(null, message, publicKey, signatureBytes)) { return { ok: false, reason: "signature does not verify" }; } return { ok: true, hello, proof: proof({ correlationId, timestamp, signature: presented }) }; } ``` **`package.json` json** **package.json** ```json { "name": "nexus-endpoint", "private": true, "type": "module", "engines": { "node": ">=18" }, "scripts": { "start": "node server.mjs" } } ``` **TypeScript.** Node.js 22.18 or later, which runs TypeScript directly. No runtime dependencies. Download the TypeScript kit (.zip) **Run the TypeScript kit** ```bash npm install # only for type-checking with npm run typecheck export PORT=8080 export NEXUS_REGISTERED_HOST=mcp.you.example # the host in the URL you publish export NEXUS_CREATOR_KEY=nx_crt_... # shown once when you claim your handle export NEXUS_PUBLIC_KEY= # GET https://api.nexus402.dev/v1/signing-key node server.ts ``` **`server.ts` your tools are here** **server.ts** ```typescript // A complete Nexus402 creator endpoint in TypeScript. NO RUNTIME DEPENDENCIES. // // Node 22.18 or later runs this file as it is: `node server.ts`. Set four // environment variables, put it behind HTTPS, and publish its URL. // `../starters_test.go` starts this exact file and drives it with the // gateway's REAL signer. // // The gateway answers `initialize`, `tools/list` and notifications itself, // from the description and input schema you publish; only `tools/call` // reaches you, already charged. // // PORT where to listen (default 8080) // NEXUS_REGISTERED_HOST the host you published, e.g. mcp.acme.example // NEXUS_CREATOR_KEY your nx_crt_ key, shown once when you claimed a handle // NEXUS_PUBLIC_KEY the gateway's Ed25519 key(s), base64, comma-separated // (GET https://api.nexus402.dev/v1/signing-key lists them) import { createServer, type IncomingMessage, type ServerResponse } from "node:http"; import { publicKeyFromBase64, verifyRequest, type Verdict } from "./verify.ts"; // The gateway's own cap on a request body. Anything larger did not come from it. const MAX_BODY_BYTES = 10 * 1024 * 1024; function required(name: string): string { const value = (process.env[name] ?? "").trim(); if (value === "") { throw new Error(`${name} is not set`); } return value; } const port = Number(process.env.PORT ?? 8080); const registeredHost = required("NEXUS_REGISTERED_HOST"); const creatorKey = required("NEXUS_CREATOR_KEY"); // More than one while the gateway rotates its key: accept any of them. const publicKeys = required("NEXUS_PUBLIC_KEY") .split(",") .map((key) => publicKeyFromBase64(key.trim())); interface ToolAnswer { status: number; result: unknown; } /** * YOUR TOOLS. `tool` is the last segment of the published name * (`acme/text@v2/word_count` arrives as `word_count`). * * Return the bare MCP result. The gateway wraps it in the JSON-RPC envelope, * so your own envelope would nest. `isError: true` is still a * CHARGED call: use it only when the caller's input made your tool fail * after it did work. When your tool itself fails, return a 5xx; when the * request is wrong before any work, a 4xx. Both refund the caller. */ function runTool(tool: string, args: Record): ToolAnswer { switch (tool) { case "word_count": { const text = typeof args.text === "string" ? args.text.trim() : ""; const words = text === "" ? 0 : text.split(/\s+/).length; return { status: 200, result: { content: [{ type: "text", text: String(words) }] } }; } default: return { status: 404, result: { error: `unknown tool ${tool}` } }; } } function readBody(request: IncomingMessage): Promise { return new Promise((resolve, reject) => { // ONE buffer that grows, never a list of the pieces: a body sent a byte // at a time would make that list hundreds of times the limit. let body: Buffer = Buffer.allocUnsafe(64 * 1024); let size = 0; request.on("data", (chunk: Buffer) => { if (size + chunk.length > MAX_BODY_BYTES) { reject(new Error("body too large")); request.destroy(); return; } if (size + chunk.length > body.length) { const larger = Buffer.allocUnsafe(Math.max(2 * body.length, size + chunk.length)); body.copy(larger, 0, 0, size); body = larger; } size += chunk.copy(body, size); }); request.on("end", () => resolve(body.subarray(0, size))); request.on("error", reject); }); } function verify(request: IncomingMessage, rawBody: Buffer): Verdict { let verdict: Verdict = { ok: false, reason: "no public key" }; for (const publicKey of publicKeys) { verdict = verifyRequest( { headers: request.headers, rawBody, method: request.method ?? "", pathWithQuery: request.url ?? "" }, { registeredHost, creatorKey, publicKey }, ); if (verdict.ok) return verdict; } return verdict; } // The proof goes on EVERY answer to a verified request, errors included. function answer(response: ServerResponse, status: number, proof: string, body?: unknown): void { response.writeHead(status, { "Content-Type": "application/json", "X-Nexus-Proof": proof }); response.end(body === undefined ? "" : JSON.stringify(body)); } function argumentsOf(call: unknown): { name: string; args: Record } { const params = (call as { params?: { name?: unknown; arguments?: unknown } } | null)?.params; const name = typeof params?.name === "string" ? params.name : ""; const args = typeof params?.arguments === "object" && params.arguments !== null ? (params.arguments as Record) : {}; return { name, args }; } const server = createServer(async (request, response) => { if (request.method !== "POST") { response.writeHead(405, { Allow: "POST" }).end(); return; } let rawBody: Buffer; try { rawBody = await readBody(request); } catch { response.writeHead(413).end(); return; } const verdict = verify(request, rawBody); if (!verdict.ok) { // No detail in the body: a reason tells a prober how close they are. console.warn(`refused: ${verdict.reason}`); response.writeHead(401, { "Content-Type": "text/plain" }).end("unauthorized"); return; } // THE HELLO: answer with the proof and run nothing. if (verdict.hello) { answer(response, 200, verdict.proof); return; } let call: unknown; try { call = JSON.parse(rawBody.toString("utf8")); } catch { answer(response, 400, verdict.proof, { error: "body is not JSON" }); return; } const { name, args } = argumentsOf(call); const { status, result } = runTool(name.slice(name.lastIndexOf("/") + 1), args); answer(response, status, verdict.proof, result); }); server.listen(port, () => { console.log(`listening on :${port} for ${registeredHost}`); }); ``` **`verify.ts` typescript** **verify.ts** ```typescript // A complete Nexus402 request verifier for TypeScript. NO RUNTIME DEPENDENCIES. // // The same verifier as `../node/verify.mjs`, typed. Node 22.18 or later runs // this file directly (it strips the types), so there is no build step. // `../starters_test.go` starts the server beside it and drives it with the // gateway's REAL signer: the hello, a paid call, and forged calls. // // Two checks, and you want both. The creator key is a shared secret on your // server; if it leaks, anyone can impersonate Nexus402 to you. The signature // is asymmetric (you hold only a public key), and it binds a request to YOUR // host and to a 60-second window. The window LIMITS a replay of the same // request, it does not stop one: make your tool's side effects idempotent. import { createHash, createPublicKey, timingSafeEqual, verify, type KeyObject } from "node:crypto"; /** The fixed first line of the response proof's digested bytes. Copy exactly. */ export const PROOF_DOMAIN = "nexus-endpoint-proof-v1"; /** Must match the gateway's 60 seconds, in both directions. */ export const SIGNATURE_WINDOW_SECONDS = 60; // Ed25519 public keys arrive as 32 raw bytes in base64; createPublicKey wants // DER, and for Ed25519 the SPKI header is this fixed 12-byte prefix. const SPKI_ED25519_PREFIX = Buffer.from("302a300506032b6570032100", "hex"); export function publicKeyFromBase64(base64: string): KeyObject { const raw = Buffer.from(base64, "base64"); if (raw.length !== 32) { throw new Error(`ed25519 public key must be 32 bytes, got ${raw.length}`); } return createPublicKey({ key: Buffer.concat([SPKI_ED25519_PREFIX, raw]), format: "der", type: "spki" }); } /** Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse. */ export function bodyHashHex(rawBody: Buffer): string { return createHash("sha256").update(rawBody).digest("hex"); } /** * Six fields joined by single newlines, in this order, no trailing newline. * `registeredHost` is the host you PUBLISHED, never the inbound Host header, * which a proxy may rewrite. */ export function canonicalString( method: string, registeredHost: string, pathWithQuery: string, timestamp: string, correlationId: string, bodySha256Hex: string, ): string { // nexus:canonical-begin return [method, registeredHost, pathWithQuery, timestamp, correlationId, bodySha256Hex].join("\n"); // nexus:canonical-end } /** Constant-time compare: both sides hashed to a fixed width first. */ export function constantTimeEquals(presented: string, expected: string): boolean { const left = createHash("sha256").update(presented, "utf8").digest(); const right = createHash("sha256").update(expected, "utf8").digest(); return timingSafeEqual(left, right); } /** The value Nexus402 requires on EVERY answer to a verified request. */ export function proof(correlationId: string, timestamp: string, signature: string): string { const digest = createHash("sha256") .update([PROOF_DOMAIN, correlationId, timestamp, signature].join("\n"), "utf8") .digest("base64url"); return `sha256:${digest}`; } export type Verdict = { ok: true; hello: boolean; proof: string } | { ok: false; reason: string }; export interface InboundRequest { /** Header names in any case. */ headers: Record; rawBody: Buffer; method: string; /** The request target exactly as sent: path plus query, not re-encoded. */ pathWithQuery: string; } export interface EndpointConfig { registeredHost: string; creatorKey: string; publicKey: KeyObject; } /** * Verifies one inbound request. * * THE HELLO: when you publish, Nexus402 sends one signed POST with an EMPTY * body and NO creator key. `hello` is true for it; answer 200 with the proof * and run no tool. Its signature is still verified. */ export function verifyRequest( request: InboundRequest, config: EndpointConfig, nowUnixSeconds: number = Math.floor(Date.now() / 1000), ): Verdict { const header = (name: string): string => { const value = request.headers[name] ?? request.headers[name.toLowerCase()]; return Array.isArray(value) ? (value[0] ?? "") : (value ?? ""); }; const hello = request.rawBody.length === 0; if (!hello && !constantTimeEquals(header("X-Nexus-Creator-Key"), config.creatorKey)) { return { ok: false, reason: "creator key mismatch" }; } const timestamp = header("X-Nexus-Timestamp"); if (!/^\d+$/.test(timestamp)) { return { ok: false, reason: "timestamp is not an integer" }; } // BOTH directions: no upper bound means a future-dated request is valid // forever; no lower bound means a captured one replays forever. if (Math.abs(nowUnixSeconds - Number(timestamp)) > SIGNATURE_WINDOW_SECONDS) { return { ok: false, reason: "timestamp outside the 60-second window" }; } const presented = header("X-Nexus-Signature"); if (!presented.startsWith("ed25519:")) { return { ok: false, reason: "signature is not ed25519:" }; } const signature = Buffer.from(presented.slice("ed25519:".length), "base64"); if (signature.length !== 64) { return { ok: false, reason: "signature is not 64 bytes" }; } const correlationId = header("X-Correlation-ID"); const message = canonicalString( request.method, config.registeredHost, request.pathWithQuery, timestamp, correlationId, bodyHashHex(request.rawBody), ); if (!verify(null, Buffer.from(message, "utf8"), config.publicKey, signature)) { return { ok: false, reason: "signature does not verify" }; } return { ok: true, hello, proof: proof(correlationId, timestamp, presented) }; } ``` **`package.json` json** **package.json** ```json { "name": "nexus-endpoint", "private": true, "type": "module", "engines": { "node": ">=22.18" }, "scripts": { "start": "node server.ts", "typecheck": "tsc" }, "devDependencies": { "@types/node": "^24.19.0", "typescript": "^6.0.3" } } ``` **`tsconfig.json` json** **tsconfig.json** ```json { "compilerOptions": { "target": "es2022", "module": "nodenext", "moduleResolution": "nodenext", "strict": true, "noEmit": true, "allowImportingTsExtensions": true, "erasableSyntaxOnly": true, "verbatimModuleSyntax": true, "types": ["node"] }, "include": ["*.ts"] } ``` **Python.** Python 3.10 or later and one package, cryptography. Download the Python kit (.zip) **Run the Python kit** ```bash python3 -m venv .venv && . .venv/bin/activate pip install -r requirements.txt export PORT=8080 export NEXUS_REGISTERED_HOST=mcp.you.example # the host in the URL you publish export NEXUS_CREATOR_KEY=nx_crt_... # shown once when you claim your handle export NEXUS_PUBLIC_KEY= # GET https://api.nexus402.dev/v1/signing-key python3 server.py ``` **`server.py` your tools are here** **server.py** ```python """A complete Nexus402 creator endpoint for Python. One package: cryptography. Put `verify.py` beside this file, `pip install -r requirements.txt`, set four environment variables, put it behind HTTPS, and publish its URL. `../starters_test.go` starts this exact file and drives it with the gateway's REAL signer: the hello, a paid call, and forged calls. The gateway answers `initialize`, `tools/list` and notifications itself, from the description and input schema you publish; only `tools/call` reaches you, already charged. Standard library HTTP server, so nothing else to install; it is threaded, and meant to sit behind your HTTPS proxy or platform router. PORT where to listen (default 8080) NEXUS_REGISTERED_HOST the host you published, e.g. mcp.acme.example NEXUS_CREATOR_KEY your nx_crt_ key, shown once when you claimed a handle NEXUS_PUBLIC_KEY the gateway's Ed25519 key(s), base64, comma-separated (GET https://api.nexus402.dev/v1/signing-key lists them) """ from __future__ import annotations import json import os import sys from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from verify import verify_request # The gateway's own cap on a request body. Anything larger did not come from it. MAX_BODY_BYTES = 10 * 1024 * 1024 def required(name: str) -> str: value = os.environ.get(name, "").strip() if value == "": sys.exit(f"{name} is not set") return value PORT = int(os.environ.get("PORT", "8080")) REGISTERED_HOST = required("NEXUS_REGISTERED_HOST") CREATOR_KEY = required("NEXUS_CREATOR_KEY") # More than one while the gateway rotates its key: accept any of them. PUBLIC_KEYS = [key.strip() for key in required("NEXUS_PUBLIC_KEY").split(",") if key.strip()] def run_tool(tool: str, args: dict) -> tuple[int, dict]: """YOUR TOOLS. `tool` is the last segment of the published name (`acme/text@v2/word_count` arrives as `word_count`). Return (status, the bare MCP result). The gateway wraps the result in the JSON-RPC envelope, so your own envelope would nest. `isError: True` is still a CHARGED call: use it only when the caller's input made your tool fail after it did work. When your tool itself fails, return a 5xx; when the request is wrong before any work, a 4xx. Both refund the caller. """ if tool == "word_count": text = args.get("text") if isinstance(args.get("text"), str) else "" return 200, {"content": [{"type": "text", "text": str(len(text.split()))}]} return 404, {"error": f"unknown tool {tool}"} class Handler(BaseHTTPRequestHandler): # Seconds one read, or sending one answer, may take. Without this a caller # that stops half way keeps its thread for ever. timeout = 30 def do_POST(self) -> None: # noqa: N802 (the name http.server calls) length = int(self.headers.get("Content-Length") or 0) if length > MAX_BODY_BYTES: self.send_response(413) self.end_headers() return raw_body = self.rfile.read(length) if length > 0 else b"" headers = {name: value for name, value in self.headers.items()} ok, detail = False, "no public key" for public_key in PUBLIC_KEYS: ok, detail = verify_request( headers=headers, raw_body=raw_body, method=self.command, # The request target exactly as sent: path plus query. path_with_query=self.path, registered_host=REGISTERED_HOST, creator_key=CREATOR_KEY, public_key_base64=public_key, ) if ok: break if not ok: # No detail in the body: a reason tells a prober how close they are. print(f"refused: {detail}", file=sys.stderr) self.reply(401, None, b"unauthorized", "text/plain") return proof = detail # THE HELLO: the signed, empty-body check sent when you publish. # Answer with the proof and run nothing. if raw_body == b"": self.reply(200, proof, b"") return try: call = json.loads(raw_body) except ValueError: self.reply(400, proof, json.dumps({"error": "body is not JSON"}).encode()) return params = call.get("params") if isinstance(call, dict) else None params = params if isinstance(params, dict) else {} name = params.get("name") if isinstance(params.get("name"), str) else "" args = params.get("arguments") if isinstance(params.get("arguments"), dict) else {} status, result = run_tool(name.rsplit("/", 1)[-1], args) self.reply(status, proof, json.dumps(result).encode()) def do_GET(self) -> None: # noqa: N802 self.send_response(405) self.send_header("Allow", "POST") self.end_headers() def reply(self, status: int, proof: str | None, body: bytes, content_type: str = "application/json") -> None: # The proof goes on EVERY answer to a verified request, errors included, # and before the headers are finished. self.send_response(status) self.send_header("Content-Type", content_type) self.send_header("Content-Length", str(len(body))) if proof is not None: self.send_header("X-Nexus-Proof", proof) self.end_headers() self.wfile.write(body) def log_message(self, format: str, *args: object) -> None: # noqa: A002 # Request lines carry paths and queries a caller chose; keep them out. return class Server(ThreadingHTTPServer): # Connections waiting to be accepted. The default, 5, turns away a burst. request_queue_size = 128 if __name__ == "__main__": print(f"listening on :{PORT} for {REGISTERED_HOST}", flush=True) Server(("", PORT), Handler).serve_forever() ``` **`verify.py` python** **verify.py** ```python """A Nexus402 request verifier for Python. Machine-checked: `../starters_test.go` starts `server.py`, which uses this file, and drives it with the gateway's REAL signer -- the hello, a paid call, and forged calls that must be refused. `../field_order_test.go` also reads the canonical string between the markers below. Needs: `pip install cryptography`. """ from __future__ import annotations import hashlib import hmac import time import binascii from base64 import b64decode, urlsafe_b64encode from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey # The fixed first line of the response proof's digested bytes. Copy exactly. PROOF_DOMAIN = "nexus-endpoint-proof-v1" # Must match the gateway's 60 seconds. Wider accepts older replays; narrower # rejects honest requests on ordinary clock skew. SIGNATURE_WINDOW_SECONDS = 60 def body_hash_hex(raw_body: bytes) -> str: """Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse.""" return hashlib.sha256(raw_body).hexdigest() def canonical_string( method: str, registered_host: str, path_with_query: str, timestamp: str, correlation_id: str, body_sha256_hex: str, ) -> str: """Six fields joined by single newlines. No trailing newline.""" # nexus:canonical-begin return "\n".join( [ method, registered_host, path_with_query, timestamp, correlation_id, body_sha256_hex, ] ) # nexus:canonical-end def proof(correlation_id: str, timestamp: str, signature: str) -> str: """The value Nexus402 requires on EVERY response, including your errors.""" digest = hashlib.sha256( "\n".join([PROOF_DOMAIN, correlation_id, timestamp, signature]).encode("utf-8") ).digest() return "sha256:" + urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") def verify_request( headers: dict[str, str], raw_body: bytes, method: str, path_with_query: str, registered_host: str, creator_key: str, public_key_base64: str, now_unix_seconds: int | None = None, ) -> tuple[bool, str]: """Returns (ok, proof) on success, or (False, reason).""" now = int(time.time()) if now_unix_seconds is None else now_unix_seconds # Header names are case-insensitive, and a client may send any case. lowered = {key.lower(): value for key, value in headers.items()} def header(name: str) -> str: return lowered.get(name.lower()) or "" # THE HELLO (ADR-0143): the publish check is a signed POST with an EMPTY # body and NO creator key. Answer it 200 with the proof and run no tool. # Only the key check is skipped; the signature below is still verified. hello = len(raw_body) == 0 # Constant time. A byte-at-a-time `==` returns faster the earlier it finds # a difference, leaking the key one position at a time. if not hello and not hmac.compare_digest(header("X-Nexus-Creator-Key").encode(), creator_key.encode()): return False, "creator key mismatch" timestamp = header("X-Nexus-Timestamp") # ASCII only: isdigit() accepts digits int() does not. And few enough of # them for int(), which raises on thousands. Anyone can send either. if not (timestamp.isascii() and timestamp.isdigit() and len(timestamp) <= 18): return False, "timestamp is not an integer" # BOTH directions: without an upper bound a future-dated request is valid # forever; without a lower one a captured request replays forever. if abs(now - int(timestamp)) > SIGNATURE_WINDOW_SECONDS: return False, "timestamp outside the 60-second window" presented = header("X-Nexus-Signature") if not presented.startswith("ed25519:"): return False, "signature is not ed25519:" try: signature = b64decode(presented[len("ed25519:") :], validate=True) except (binascii.Error, ValueError): return False, "signature is not base64" if len(signature) != 64: return False, "signature is not 64 bytes" correlation_id = header("X-Correlation-ID") message = canonical_string( method, registered_host, path_with_query, timestamp, correlation_id, body_hash_hex(raw_body), ).encode("utf-8") try: Ed25519PublicKey.from_public_bytes(b64decode(public_key_base64)).verify( signature, message ) except (InvalidSignature, ValueError): return False, "signature does not verify" return True, proof(correlation_id, timestamp, presented) ``` **`requirements.txt` text** **requirements.txt** ```text cryptography==50.0.2 ``` **Go.** Go 1.22 or later. Standard library only. Download the Go kit (.zip) **Run the Go kit** ```bash go build -o endpoint . export PORT=8080 export NEXUS_REGISTERED_HOST=mcp.you.example # the host in the URL you publish export NEXUS_CREATOR_KEY=nx_crt_... # shown once when you claim your handle export NEXUS_PUBLIC_KEY= # GET https://api.nexus402.dev/v1/signing-key ./endpoint ``` **`main.go` your tools are here** **main.go** ```go // A complete Nexus402 creator endpoint for Go. Standard library only. // // Set four environment variables, put it behind HTTPS, and publish its URL. // `../starters_test.go` builds this kit from an empty directory, exactly as a // creator downloads it, and drives it with the gateway's REAL signer. // // The gateway answers `initialize`, `tools/list` and notifications itself, // from the description and input schema you publish; only `tools/call` // reaches you, already charged. // // PORT where to listen (default 8080) // NEXUS_REGISTERED_HOST the host you published, e.g. mcp.acme.example // NEXUS_CREATOR_KEY your nx_crt_ key, shown once when you claimed a handle // NEXUS_PUBLIC_KEY the gateway's Ed25519 key(s), base64, comma-separated // (GET https://api.nexus402.dev/v1/signing-key lists them) package main import ( "encoding/json" "io" "log" "net/http" "os" "strconv" "strings" "time" ) // The gateway's own cap on a request body. Anything larger did not come from it. const maxBodyBytes = 10 << 20 // runTool is YOUR TOOLS. tool is the last segment of the published name // (`acme/text@v2/word_count` arrives as `word_count`). // // Return the status and the bare MCP result. The gateway wraps the result in // the JSON-RPC envelope, so your own envelope would nest. `isError: true` is // still a CHARGED call: use it only when the caller's input made your tool fail // after it did work. When your tool itself fails, return a 5xx; when the // request is wrong before any work, a 4xx. Both refund the caller. func runTool(tool string, args map[string]any) (int, any) { switch tool { case "word_count": text, _ := args["text"].(string) words := len(strings.Fields(text)) return http.StatusOK, map[string]any{"content": []map[string]string{{"type": "text", "text": strconv.Itoa(words)}}} default: return http.StatusNotFound, map[string]string{"error": "unknown tool " + tool} } } type endpoint struct { verifier Verifier } func (e endpoint) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { w.Header().Set("Allow", http.MethodPost) w.WriteHeader(http.StatusMethodNotAllowed) return } // Past the limit this also has the server close the connection, after at // most 256 KiB more, rather than read the rest. body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes)) if err != nil { w.WriteHeader(http.StatusRequestEntityTooLarge) return } verdict, err := e.verifier.Verify(r, body, time.Now()) if err != nil { // No detail in the body: a reason tells a prober how close they are. log.Printf("refused: %v", err) http.Error(w, "unauthorized", http.StatusUnauthorized) return } // The proof goes on EVERY answer to a verified request, errors included, // and BEFORE WriteHeader: a header set afterwards is dropped in silence. w.Header().Set("X-Nexus-Proof", verdict.Proof) w.Header().Set("Content-Type", "application/json") // THE HELLO: answer with the proof and run nothing. if verdict.Hello { w.WriteHeader(http.StatusOK) return } var call struct { Params struct { Name string `json:"name"` Arguments map[string]any `json:"arguments"` } `json:"params"` } if err := json.Unmarshal(body, &call); err != nil { w.WriteHeader(http.StatusBadRequest) _ = json.NewEncoder(w).Encode(map[string]string{"error": "body is not JSON"}) return } name := call.Params.Name status, result := runTool(name[strings.LastIndex(name, "/")+1:], call.Params.Arguments) w.WriteHeader(status) _ = json.NewEncoder(w).Encode(result) } func required(name string) string { value := strings.TrimSpace(os.Getenv(name)) if value == "" { log.Fatalf("%s is not set", name) } return value } func main() { keys, err := ParsePublicKeys(required("NEXUS_PUBLIC_KEY")) if err != nil { log.Fatal(err) } verifier := Verifier{ RegisteredHost: required("NEXUS_REGISTERED_HOST"), CreatorKey: required("NEXUS_CREATOR_KEY"), PublicKeys: keys, } port := 8080 if raw := os.Getenv("PORT"); raw != "" { port, err = strconv.Atoi(raw) if err != nil || port < 1 || port > 65535 { log.Fatal("PORT must be a number between 1 and 65535") } } server := &http.Server{ Addr: ":" + strconv.Itoa(port), Handler: endpoint{verifier: verifier}, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 60 * time.Second, WriteTimeout: 130 * time.Second, } log.Printf("listening on :%d", port) log.Fatal(server.ListenAndServe()) } ``` **`verify.go` go** **verify.go** ```go package main // A complete Nexus402 request verifier for Go. Standard library only. // // `../starters_test.go` builds this kit from an empty directory and drives it // with the gateway's REAL signer: the hello, a paid call, and forged calls // that must be refused. // // Two checks, and you want both. The creator key is a shared secret on your // server; if it leaks, anyone can impersonate Nexus402 to you. The signature // is asymmetric (you hold only a public key), and it binds a request to YOUR // host and to a 60-second window. The window LIMITS a replay of the same // request, it does not stop one: make your tool's side effects idempotent. import ( "crypto/ed25519" "crypto/sha256" "crypto/subtle" "encoding/base64" "encoding/hex" "errors" "net/http" "strconv" "strings" "time" ) // ProofDomain is the fixed first line of the response proof's digested bytes. const ProofDomain = "nexus-endpoint-proof-v1" // SignatureWindow must match the gateway's 60 seconds, in both directions. const SignatureWindow = 60 * time.Second // Verdict is what a verified request concluded. type Verdict struct { // Hello is the signed, empty-body check the gateway sends when you // publish: answer it 200 with the proof and run no tool. Hello bool // Proof goes in X-Nexus-Proof on every answer to this request. Proof string } // Verifier holds what you configured. type Verifier struct { RegisteredHost string CreatorKey string PublicKeys []ed25519.PublicKey } // ParsePublicKeys reads the gateway's key list: base64, comma-separated. func ParsePublicKeys(raw string) ([]ed25519.PublicKey, error) { var keys []ed25519.PublicKey for _, part := range strings.Split(raw, ",") { decoded, err := base64.StdEncoding.DecodeString(strings.TrimSpace(part)) if err != nil || len(decoded) != ed25519.PublicKeySize { return nil, errors.New("NEXUS_PUBLIC_KEY must be base64 Ed25519 keys of 32 bytes, comma-separated") } keys = append(keys, ed25519.PublicKey(decoded)) } return keys, nil } // CanonicalString is the signed message: six fields joined by single // newlines, in this order, no trailing newline. host is the host you // PUBLISHED, never the inbound Host header, which a proxy may rewrite. func CanonicalString(method, host, pathWithQuery, timestamp, correlationID, bodySHA256Hex string) string { // nexus:canonical-begin return strings.Join([]string{method, host, pathWithQuery, timestamp, correlationID, bodySHA256Hex}, "\n") // nexus:canonical-end } // Proof is the value Nexus402 requires on every answer to a verified request. func Proof(correlationID, timestamp, signature string) string { sum := sha256.Sum256([]byte(strings.Join([]string{ProofDomain, correlationID, timestamp, signature}, "\n"))) return "sha256:" + base64.RawURLEncoding.EncodeToString(sum[:]) } // RequestTarget is the path with the query, exactly as sent. func RequestTarget(r *http.Request) string { return r.URL.RequestURI() } // Verify checks one request whose raw body has already been read. func (v Verifier) Verify(r *http.Request, body []byte, now time.Time) (Verdict, error) { hello := len(body) == 0 // Constant time: a byte-at-a-time compare leaks the key one position at // a time. The hello carries no key, so it skips only this check. presented := sha256.Sum256([]byte(r.Header.Get("X-Nexus-Creator-Key"))) expected := sha256.Sum256([]byte(v.CreatorKey)) if !hello && subtle.ConstantTimeCompare(presented[:], expected[:]) != 1 { return Verdict{}, errors.New("creator key mismatch") } timestamp := r.Header.Get("X-Nexus-Timestamp") seconds, err := strconv.ParseInt(timestamp, 10, 64) if err != nil { return Verdict{}, errors.New("timestamp is not an integer") } // BOTH directions: no upper bound means a future-dated request is valid // forever; no lower bound means a captured one replays forever. if skew := now.Sub(time.Unix(seconds, 0)); skew > SignatureWindow || skew < -SignatureWindow { return Verdict{}, errors.New("timestamp outside the 60-second window") } header := r.Header.Get("X-Nexus-Signature") encoded, found := strings.CutPrefix(header, "ed25519:") if !found { return Verdict{}, errors.New("signature lacks the ed25519 prefix") } signature, err := base64.StdEncoding.DecodeString(encoded) if err != nil || len(signature) != ed25519.SignatureSize { return Verdict{}, errors.New("signature is not 64 bytes of base64") } correlationID := r.Header.Get("X-Correlation-ID") sum := sha256.Sum256(body) message := []byte(CanonicalString(r.Method, v.RegisteredHost, RequestTarget(r), timestamp, correlationID, hex.EncodeToString(sum[:]))) // More than one key while the gateway rotates: accept any of them. for _, key := range v.PublicKeys { if ed25519.Verify(key, message, signature) { return Verdict{Hello: hello, Proof: Proof(correlationID, timestamp, header)}, nil } } return Verdict{}, errors.New("signature does not verify") } ``` **`go.mod` go.mod** **go.mod** ```go.mod module example.com/nexus-endpoint go 1.22 ``` **PHP.** PHP 8.1 or later with sodium, which is bundled since 7.2. No packages. Download the PHP kit (.zip) **Run the PHP kit** ```bash export PORT=8080 export NEXUS_REGISTERED_HOST=mcp.you.example # the host in the URL you publish export NEXUS_CREATOR_KEY=nx_crt_... # shown once when you claim your handle export NEXUS_PUBLIC_KEY= # GET https://api.nexus402.dev/v1/signing-key php -S 127.0.0.1:8080 index.php # local testing only; in production use PHP-FPM behind a web server with a 10 MiB body limit ``` **`index.php` your tools are here** **index.php** ```php $args * @return array{0: int, 1: array} */ function run_tool(string $tool, array $args): array { switch ($tool) { case 'word_count': $text = is_string($args['text'] ?? null) ? trim($args['text']) : ''; $words = $text === '' ? 0 : count(preg_split('/\s+/u', $text) ?: []); return [200, ['content' => [['type' => 'text', 'text' => (string) $words]]]]; default: return [404, ['error' => "unknown tool {$tool}"]]; } } function required(string $name): string { $value = trim((string) getenv($name)); if ($value === '') { error_log("{$name} is not set"); http_response_code(500); exit; } return $value; } /** @param array|null $body */ function answer(int $status, ?string $proof, ?array $body): void { // The proof goes on EVERY answer to a verified request, errors included. http_response_code($status); header('Content-Type: application/json'); if ($proof !== null) { header('X-Nexus-Proof: ' . $proof); } if ($body !== null) { echo json_encode($body, JSON_UNESCAPED_SLASHES); } } if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') { http_response_code(405); header('Allow: POST'); exit; } $registeredHost = required('NEXUS_REGISTERED_HOST'); $creatorKey = required('NEXUS_CREATOR_KEY'); // More than one while the gateway rotates its key: accept any of them. $publicKeys = array_filter(array_map('trim', explode(',', required('NEXUS_PUBLIC_KEY')))); $rawBody = (string) file_get_contents('php://input', false, null, 0, MAX_BODY_BYTES + 1); if (strlen($rawBody) > MAX_BODY_BYTES) { http_response_code(413); exit; } // Header names are case-insensitive; the verifier reads them lowercased. $headers = array_change_key_case(getallheaders(), CASE_LOWER); $verdict = [false, 'no public key']; foreach ($publicKeys as $publicKey) { $verdict = nexus_verify_request( $headers, $rawBody, $_SERVER['REQUEST_METHOD'], // The request target exactly as sent: path plus query. (string) ($_SERVER['REQUEST_URI'] ?? ''), $registeredHost, $creatorKey, $publicKey, ); if ($verdict[0]) { break; } } [$ok, $detail] = $verdict; if (!$ok) { // No detail in the body: a reason tells a prober how close they are. error_log("refused: {$detail}"); http_response_code(401); header('Content-Type: text/plain'); echo 'unauthorized'; exit; } $proof = $detail; // THE HELLO: the signed, empty-body check sent when you publish. Answer with // the proof and run nothing. if ($rawBody === '') { answer(200, $proof, null); exit; } $call = json_decode($rawBody, true); if (!is_array($call)) { answer(400, $proof, ['error' => 'body is not JSON']); exit; } $params = is_array($call['params'] ?? null) ? $call['params'] : []; $name = is_string($params['name'] ?? null) ? $params['name'] : ''; $args = is_array($params['arguments'] ?? null) ? $params['arguments'] : []; $slash = strrpos($name, '/'); [$status, $result] = run_tool($slash === false ? $name : substr($name, $slash + 1), $args); answer($status, $proof, $result); ``` **`verify.php` php** **verify.php** ```php $headers * @return array{0: bool, 1: string} [true, proof] or [false, reason] */ function nexus_verify_request( array $headers, string $rawBody, string $method, string $pathWithQuery, string $registeredHost, string $creatorKey, string $publicKeyBase64, ?int $nowUnixSeconds = null, ): array { $now = $nowUnixSeconds ?? time(); // Header names are case-insensitive, and a client may send any case. $lowered = array_change_key_case($headers, CASE_LOWER); $header = static function (string $name) use ($lowered): string { return (string) ($lowered[strtolower($name)] ?? ''); }; // THE HELLO (ADR-0143): the publish check is a signed POST with an EMPTY // body and NO creator key. Answer it 200 with the proof and run no tool. // Only the key check is skipped; the signature below is still verified. $hello = $rawBody === ''; // Constant time. A byte-at-a-time compare returns faster the earlier it // finds a difference, leaking the key one position at a time. if (!$hello && !hash_equals($creatorKey, $header('X-Nexus-Creator-Key'))) { return [false, 'creator key mismatch']; } $timestamp = $header('X-Nexus-Timestamp'); if (preg_match('/^\d+$/', $timestamp) !== 1) { return [false, 'timestamp is not an integer']; } // BOTH directions. Without an upper bound a future-dated request is valid // forever; without a lower one a captured request replays forever. if (abs($now - (int) $timestamp) > NEXUS_SIGNATURE_WINDOW_SECONDS) { return [false, 'timestamp outside the 60-second window']; } $presented = $header('X-Nexus-Signature'); if (!str_starts_with($presented, 'ed25519:')) { return [false, 'signature is not ed25519:']; } $signature = base64_decode(substr($presented, strlen('ed25519:')), true); if ($signature === false || strlen($signature) !== 64) { return [false, 'signature is not 64 bytes']; } $publicKey = base64_decode($publicKeyBase64, true); if ($publicKey === false || strlen($publicKey) !== 32) { return [false, 'public key is not 32 bytes']; } $correlationId = $header('X-Correlation-ID'); $message = nexus_canonical_string( $method, $registeredHost, $pathWithQuery, $timestamp, $correlationId, nexus_body_hash_hex($rawBody), ); if (!sodium_crypto_sign_verify_detached($signature, $message, $publicKey)) { return [false, 'signature does not verify']; } return [true, nexus_proof($correlationId, $timestamp, $presented)]; } ``` **Rust.** Rust 1.85 or later. Crates: hyper, hyper-util, http-body-util, tokio, ed25519-dalek, sha2, base64, subtle, serde_json. Download the Rust kit (.zip) **Run the Rust kit** ```bash cargo build --release export PORT=8080 export NEXUS_REGISTERED_HOST=mcp.you.example # the host in the URL you publish export NEXUS_CREATOR_KEY=nx_crt_... # shown once when you claim your handle export NEXUS_PUBLIC_KEY= # GET https://api.nexus402.dev/v1/signing-key ./target/release/nexus-endpoint ``` **`main.rs` your tools are here** **main.rs** ```rust //! A complete Nexus402 creator endpoint for Rust. //! //! Set four environment variables, put it behind HTTPS, and publish its URL. //! `../starters_test.go` builds this kit from an empty directory, exactly as a //! creator downloads it, and drives it with the gateway's REAL signer. //! //! The gateway answers `initialize`, `tools/list` and notifications itself, //! from the description and input schema you publish; only `tools/call` //! reaches you, already charged. //! //! PORT where to listen (default 8080) //! NEXUS_REGISTERED_HOST the host you published, e.g. mcp.acme.example //! NEXUS_CREATOR_KEY your nx_crt_ key, shown once when you claimed a handle //! NEXUS_PUBLIC_KEY the gateway's Ed25519 key(s), base64, comma-separated //! (GET https://api.nexus402.dev/v1/signing-key lists them) mod verify; use http_body_util::{BodyExt, Full}; use hyper::body::{Bytes, Incoming}; use hyper::header::{HeaderMap, HeaderValue, ALLOW, CONTENT_TYPE}; use hyper::server::conn::http1; use hyper::service::service_fn; use hyper::{Method, Request, Response, StatusCode}; use hyper_util::rt::{TokioIo, TokioTimer}; use serde_json::{json, Value}; use std::convert::Infallible; use std::sync::Arc; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use tokio::net::{TcpListener, TcpStream}; use tokio::sync::Semaphore; use tokio::time::{sleep, timeout}; use verify::Endpoint; /// The gateway's own cap on a request body. Anything larger did not come from it. const MAX_BODY_BYTES: usize = 10 * 1024 * 1024; // A stranger can open a connection and send bytes before anything is verified. // So only this many connections are served at once (the next one waits), and // each has DEADLINES, which a slow trickle of bytes does not extend. The // gateway opens at most 64 connections to you and gives a call 120 seconds. const MAX_CONNECTIONS: usize = 100; const HEADERS_DEADLINE: Duration = Duration::from_secs(10); const BODY_DEADLINE: Duration = Duration::from_secs(30); /// The whole connection, your tool and the answer included. const CONNECTION_DEADLINE: Duration = Duration::from_secs(180); /// YOUR TOOLS. `tool` is the last segment of the published name /// (`acme/text@v2/word_count` arrives as `word_count`). /// /// Return the status and the bare MCP result. The gateway wraps the result in /// the JSON-RPC envelope, so your own envelope would nest. `isError: true` is /// still a CHARGED call: use it only when the caller's input made your tool fail /// after it did work. When your tool itself fails, return a 5xx; when the /// request is wrong before any work, a 4xx. Both refund the caller. fn run_tool(tool: &str, args: &Value) -> (u16, Value) { match tool { "word_count" => { let text = args.get("text").and_then(Value::as_str).unwrap_or(""); let words = text.split_whitespace().count(); (200, json!({ "content": [{ "type": "text", "text": words.to_string() }] })) } _ => (404, json!({ "error": format!("unknown tool {tool}") })), } } fn required(name: &str) -> String { let value = std::env::var(name).unwrap_or_default().trim().to_string(); if value.is_empty() { eprintln!("{name} is not set"); std::process::exit(1); } value } type Answer = Response>; fn header<'a>(headers: &'a HeaderMap, name: &str) -> &'a str { headers.get(name).and_then(|value| value.to_str().ok()).unwrap_or("") } /// The answer to a request that is NOT verified, so it carries no proof. fn refuse(status: StatusCode, body: &'static str) -> Answer { let mut answer = Response::new(Full::from(body)); *answer.status_mut() = status; answer } /// The proof goes on EVERY answer to a verified request, errors included. fn answer(status: u16, proof: &str, body: Option<&Value>) -> Answer { let bytes = body.map(|b| b.to_string().into_bytes()).unwrap_or_default(); Response::builder() .status(StatusCode::from_u16(status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)) .header(CONTENT_TYPE, "application/json") .header("X-Nexus-Proof", proof) .body(Full::from(bytes)) .expect("the proof is ASCII") } /// Reads the body into ONE buffer, counting as it goes. It never holds more /// than the limit, whatever length the request claims and however small the /// pieces it arrives in. async fn read_body(mut body: Incoming) -> Result, StatusCode> { let mut raw_body = Vec::new(); while let Some(frame) = body.frame().await { let frame = frame.map_err(|_| StatusCode::BAD_REQUEST)?; if let Some(data) = frame.data_ref() { if raw_body.len() + data.len() > MAX_BODY_BYTES { return Err(StatusCode::PAYLOAD_TOO_LARGE); } raw_body.extend_from_slice(data); } } Ok(raw_body) } async fn handle(request: Request, endpoints: &[Endpoint]) -> Answer { if request.method() != Method::POST { let mut not_allowed = refuse(StatusCode::METHOD_NOT_ALLOWED, ""); not_allowed.headers_mut().insert(ALLOW, HeaderValue::from_static("POST")); return not_allowed; } let (head, body) = request.into_parts(); let raw_body = match timeout(BODY_DEADLINE, read_body(body)).await { Ok(Ok(raw_body)) => raw_body, Ok(Err(status)) => return refuse(status, ""), Err(_) => return refuse(StatusCode::REQUEST_TIMEOUT, ""), }; let inbound = verify::Request { creator_key_header: header(&head.headers, "X-Nexus-Creator-Key"), signature_header: header(&head.headers, "X-Nexus-Signature"), timestamp_header: header(&head.headers, "X-Nexus-Timestamp"), correlation_id: header(&head.headers, "X-Correlation-ID"), raw_body: &raw_body, method: head.method.as_str(), // The request target exactly as sent: path plus query. path_with_query: head.uri.path_and_query().map_or("/", |target| target.as_str()), }; let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs() as i64).unwrap_or(0); let mut verdict = Err("no public key".to_string()); for endpoint in endpoints { verdict = endpoint.verify(&inbound, now); if verdict.is_ok() { break; } } let proof = match verdict { Ok(proof) => proof, Err(reason) => { // No detail in the body: a reason tells a prober how close they are. eprintln!("refused: {reason}"); return refuse(StatusCode::UNAUTHORIZED, "unauthorized"); } }; // THE HELLO: the signed, empty-body check sent when you publish. // Answer with the proof and run nothing. if raw_body.is_empty() { return answer(200, &proof, None); } let Ok(call) = serde_json::from_slice::(&raw_body) else { return answer(400, &proof, Some(&json!({ "error": "body is not JSON" }))); }; // run_tool may block, so it runs on a thread of its own, never on one that // serves connections. let ran = tokio::task::spawn_blocking(move || { let params = call.get("params").cloned().unwrap_or(Value::Null); let name = params.get("name").and_then(Value::as_str).unwrap_or(""); let tool = name.rsplit('/').next().unwrap_or(""); let args = params.get("arguments").cloned().unwrap_or_else(|| json!({})); run_tool(tool, &args) }); match ran.await { Ok((status, result)) => answer(status, &proof, Some(&result)), // run_tool panicked: your tool's failure, so the caller is refunded. Err(_) => answer(500, &proof, Some(&json!({ "error": "the tool failed" }))), } } async fn serve(stream: TcpStream, endpoints: Arc>) { let service = service_fn(|request| async { Ok::<_, Infallible>(handle(request, &endpoints).await) }); let connection = http1::Builder::new() .timer(TokioTimer::new()) .header_read_timeout(HEADERS_DEADLINE) // One request per connection, so an idle one does not keep its place. .keep_alive(false) .serve_connection(TokioIo::new(stream), service); // An error here is the connection itself failing: there is no one to tell. let _ = timeout(CONNECTION_DEADLINE, connection).await; } #[tokio::main] async fn main() { let port = std::env::var("PORT").unwrap_or_else(|_| "8080".into()); let registered_host = required("NEXUS_REGISTERED_HOST"); let creator_key = required("NEXUS_CREATOR_KEY"); // More than one while the gateway rotates its key: accept any of them. let endpoints: Vec = required("NEXUS_PUBLIC_KEY") .split(',') .map(|key| Endpoint { registered_host: registered_host.clone(), creator_key: creator_key.clone(), public_key_base64: key.trim().to_string(), }) .collect(); let endpoints = Arc::new(endpoints); let listener = TcpListener::bind(format!("0.0.0.0:{port}")).await.expect("listen"); println!("listening on :{port} for {registered_host}"); let places = Arc::new(Semaphore::new(MAX_CONNECTIONS)); loop { // Take a place BEFORE accepting; it is given back when the connection ends. let place = Arc::clone(&places).acquire_owned().await.expect("never closed"); match listener.accept().await { Ok((stream, _)) => { let endpoints = Arc::clone(&endpoints); tokio::spawn(async move { serve(stream, endpoints).await; drop(place); }); } Err(error) => { // Too many open files, for example: let some close first. eprintln!("accept: {error}"); sleep(Duration::from_millis(100)).await; } } } } ``` **`verify.rs` rust** **verify.rs** ```rust //! A Nexus402 request verifier for Rust. //! //! Machine-checked: `../starters_test.go` builds `main.rs`, which uses this //! file, and drives it with the gateway's REAL signer -- the hello, a paid //! call, and forged calls that must be refused. `../field_order_test.go` also //! reads the canonical string between the markers below. //! //! Needs: `ed25519-dalek`, `sha2`, `base64`, `subtle`. use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; use base64::Engine; use ed25519_dalek::{Signature, Verifier, VerifyingKey}; use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq; /// The fixed first line of the response proof's digested bytes. Copy exactly. pub const PROOF_DOMAIN: &str = "nexus-endpoint-proof-v1"; /// Must match the gateway's 60 seconds. Wider accepts older replays; /// narrower rejects honest requests on ordinary clock skew. pub const SIGNATURE_WINDOW_SECONDS: i64 = 60; /// Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse. pub fn body_hash_hex(raw_body: &[u8]) -> String { let digest = Sha256::digest(raw_body); digest.iter().map(|byte| format!("{byte:02x}")).collect() } /// Six fields joined by single newlines. No trailing newline. pub fn canonical_string( method: &str, registered_host: &str, path_with_query: &str, timestamp: &str, correlation_id: &str, body_sha256_hex: &str, ) -> String { // nexus:canonical-begin [ method, registered_host, path_with_query, timestamp, correlation_id, body_sha256_hex, ] .join("\n") // nexus:canonical-end } /// The value Nexus402 requires on EVERY response, including your own errors. pub fn proof(correlation_id: &str, timestamp: &str, signature: &str) -> String { let message = [PROOF_DOMAIN, correlation_id, timestamp, signature].join("\n"); let digest = Sha256::digest(message.as_bytes()); format!("sha256:{}", URL_SAFE_NO_PAD.encode(digest)) } pub struct Request<'a> { pub creator_key_header: &'a str, pub signature_header: &'a str, pub timestamp_header: &'a str, pub correlation_id: &'a str, pub raw_body: &'a [u8], pub method: &'a str, pub path_with_query: &'a str, } pub struct Endpoint { pub registered_host: String, pub creator_key: String, pub public_key_base64: String, } impl Endpoint { /// `Ok(proof)` on success; `Err(reason)` otherwise. pub fn verify(&self, request: &Request<'_>, now_unix_seconds: i64) -> Result { // THE HELLO (ADR-0143): the publish check is a signed POST with an // EMPTY body and NO creator key. Answer it 200 with the proof and run // no tool. Only the key check is skipped; the signature is verified. let hello = request.raw_body.is_empty(); // Constant time: a byte-at-a-time compare returns faster the earlier // it finds a difference, leaking the key one position at a time. let presented_key = request.creator_key_header.as_bytes(); if !hello && presented_key.ct_eq(self.creator_key.as_bytes()).unwrap_u8() != 1 { return Err("creator key mismatch".into()); } // Digits only, so never a sign; `parse` refuses none and too many. // Nothing is verified yet: anyone can send any timestamp. let timestamp = request.timestamp_header; if !timestamp.bytes().all(|byte| byte.is_ascii_digit()) { return Err("timestamp is not an integer".into()); } let seconds: i64 = timestamp .parse() .map_err(|_| "timestamp is not an integer".to_string())?; // BOTH directions. Without an upper bound a future-dated request is // valid forever; without a lower one a capture replays forever. // `abs_diff` cannot overflow, as a subtraction followed by `abs` can. if now_unix_seconds.abs_diff(seconds) > SIGNATURE_WINDOW_SECONDS.unsigned_abs() { return Err("timestamp outside the 60-second window".into()); } let encoded = request .signature_header .strip_prefix("ed25519:") .ok_or("signature is not ed25519:")?; let raw = STANDARD .decode(encoded) .map_err(|_| "signature is not base64".to_string())?; let bytes: [u8; 64] = raw .try_into() .map_err(|_| "signature is not 64 bytes".to_string())?; let key_bytes: [u8; 32] = STANDARD .decode(&self.public_key_base64) .map_err(|_| "public key is not base64".to_string())? .try_into() .map_err(|_| "public key is not 32 bytes".to_string())?; let key = VerifyingKey::from_bytes(&key_bytes).map_err(|error| error.to_string())?; let message = canonical_string( request.method, &self.registered_host, request.path_with_query, request.timestamp_header, request.correlation_id, &body_hash_hex(request.raw_body), ); key.verify(message.as_bytes(), &Signature::from_bytes(&bytes)) .map_err(|_| "signature does not verify".to_string())?; Ok(proof( request.correlation_id, request.timestamp_header, request.signature_header, )) } } ``` **`Cargo.toml` toml** **Cargo.toml** ```toml [package] name = "nexus-endpoint" version = "0.1.0" edition = "2021" rust-version = "1.85" [[bin]] name = "nexus-endpoint" path = "main.rs" [dependencies] base64 = "0.22" ed25519-dalek = "2.1" serde_json = "1" sha2 = "0.10" subtle = "2.6" # The HTTP server: hyper, on tokio. It puts a deadline on a request's headers, # and tokio puts one on its body. http-body-util = "0.1" hyper = { version = "1", features = ["http1", "server"] } hyper-util = { version = "0.1", features = ["tokio"] } tokio = { version = "1", features = ["macros", "net", "rt-multi-thread", "sync", "time"] } ``` **Java.** Java 17 or later and Maven. One library, Jackson, for JSON; Ed25519 is in the JDK. Download the Java kit (.zip) **Run the Java kit** ```bash mvn -q package export PORT=8080 export NEXUS_REGISTERED_HOST=mcp.you.example # the host in the URL you publish export NEXUS_CREATOR_KEY=nx_crt_... # shown once when you claim your handle export NEXUS_PUBLIC_KEY= # GET https://api.nexus402.dev/v1/signing-key java -jar target/nexus-endpoint.jar ``` **`src/main/java/endpoint/Server.java` your tools are here** **src/main/java/endpoint/Server.java** ```java package endpoint; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpServer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.InetSocketAddress; import java.nio.charset.StandardCharsets; import java.security.PublicKey; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Executors; /** * A complete Nexus402 creator endpoint for Java 17 or later. One library, * Jackson, for JSON; the HTTP server and Ed25519 are in the JDK. * *

{@code mvn -q package && java -jar target/nexus-endpoint.jar}. Set four * environment variables, put it behind HTTPS, and publish its URL. * {@code ../starters_test.go} builds this kit from an empty directory and drives * it with the gateway's REAL signer. * *

The gateway answers {@code initialize}, {@code tools/list} and * notifications itself, from the description and input schema you publish; * only {@code tools/call} reaches you, already charged. * *

 *   PORT                    where to listen (default 8080)
 *   NEXUS_REGISTERED_HOST   the host you published, e.g. mcp.acme.example
 *   NEXUS_CREATOR_KEY       your nx_crt_ key, shown once when you claimed a handle
 *   NEXUS_PUBLIC_KEY        the gateway's Ed25519 key(s), base64, comma-separated
 *                           (GET https://api.nexus402.dev/v1/signing-key lists them)
 * 
*/ public final class Server { /** The gateway's own cap on a request body. Anything larger did not come from it. */ private static final int MAX_BODY_BYTES = 10 * 1024 * 1024; private static final ObjectMapper JSON = new ObjectMapper(); /** A status and the bare MCP result. */ record ToolAnswer(int status, Object result) {} /** * YOUR TOOLS. {@code tool} is the last segment of the published name * ({@code acme/text@v2/word_count} arrives as {@code word_count}). * *

Return the bare MCP result. The gateway wraps it in the JSON-RPC * envelope, so your own envelope would nest. {@code isError: true} is still * a CHARGED call: use it only when the caller's input made your tool fail * after it did work. When your tool itself fails, return a 5xx; when the * request is wrong before any work, a 4xx. Both refund the caller. */ static ToolAnswer runTool(String tool, JsonNode args) { switch (tool) { case "word_count": { String text = args.path("text").isTextual() ? args.path("text").asText().trim() : ""; int words = text.isEmpty() ? 0 : text.split("\\s+").length; return new ToolAnswer(200, Map.of("content", List.of(Map.of("type", "text", "text", String.valueOf(words))))); } default: return new ToolAnswer(404, Map.of("error", "unknown tool " + tool)); } } private final String registeredHost; private final String creatorKey; private final List publicKeys; private Server(String registeredHost, String creatorKey, List publicKeys) { this.registeredHost = registeredHost; this.creatorKey = creatorKey; this.publicKeys = publicKeys; } private static String required(String name) { String value = System.getenv(name) == null ? "" : System.getenv(name).trim(); if (value.isEmpty()) { System.err.println(name + " is not set"); System.exit(1); } return value; } public static void main(String[] args) throws Exception { String portValue = System.getenv("PORT"); int port = portValue == null || portValue.isBlank() ? 8080 : Integer.parseInt(portValue.trim()); String registeredHost = required("NEXUS_REGISTERED_HOST"); String creatorKey = required("NEXUS_CREATOR_KEY"); // More than one while the gateway rotates its key: accept any of them. List keys = new ArrayList<>(); for (String key : required("NEXUS_PUBLIC_KEY").split(",")) { keys.add(Verify.publicKeyFromBase64(key)); } Server endpoint = new Server(registeredHost, creatorKey, keys); // Seconds a whole request, headers and body, may take to ARRIVE; your tool's // time is not counted. The default is no limit at all, so a caller that // stops half way would keep its thread for ever. Set before the first // HttpServer is created, which is when the JDK reads it. System.setProperty("sun.net.httpserver.maxReqTime", "30"); HttpServer server = HttpServer.create(new InetSocketAddress(port), 0); server.createContext("/", endpoint::handle); server.setExecutor(Executors.newCachedThreadPool()); server.start(); System.out.println("listening on :" + port + " for " + registeredHost); } private void handle(HttpExchange exchange) throws IOException { try { if (!"POST".equals(exchange.getRequestMethod())) { exchange.getResponseHeaders().set("Allow", "POST"); exchange.sendResponseHeaders(405, -1); return; } // NOT closed here. Closing an unfinished body makes the JDK read up to // 64 KiB more and wait for it, so an oversized request got no prompt 413. // A body read to its end needs no closing. InputStream in = exchange.getRequestBody(); byte[] rawBody = in.readNBytes(MAX_BODY_BYTES + 1); if (rawBody.length > MAX_BODY_BYTES) { // The rest of the body is unread, so this connection cannot be reused. exchange.getResponseHeaders().set("Connection", "close"); exchange.sendResponseHeaders(413, -1); return; } Map headers = new HashMap<>(); exchange.getRequestHeaders().forEach((name, values) -> headers.put(name.toLowerCase(), values.get(0))); // The request target exactly as sent: path plus query, still encoded. String target = exchange.getRequestURI().getRawPath(); if (exchange.getRequestURI().getRawQuery() != null) { target += "?" + exchange.getRequestURI().getRawQuery(); } long now = System.currentTimeMillis() / 1000; Verify.Verdict verdict = Verify.Verdict.refused("no public key"); for (PublicKey key : publicKeys) { verdict = Verify.verifyRequest(headers, rawBody, "POST", target, registeredHost, creatorKey, key, now); if (verdict.ok()) { break; } } if (!verdict.ok()) { // No detail in the body: a reason tells a prober how close they are. System.err.println("refused: " + verdict.reason()); send(exchange, 401, null, "unauthorized".getBytes(StandardCharsets.UTF_8), "text/plain"); return; } // THE HELLO: the signed, empty-body check sent when you publish. // Answer with the proof and run nothing. if (verdict.hello()) { send(exchange, 200, verdict.proof(), new byte[0], "application/json"); return; } JsonNode call; try { call = JSON.readTree(rawBody); } catch (IOException notJson) { send(exchange, 400, verdict.proof(), JSON.writeValueAsBytes(Map.of("error", "body is not JSON")), "application/json"); return; } String name = call.path("params").path("name").asText(""); ToolAnswer answer = runTool(name.substring(name.lastIndexOf('/') + 1), call.path("params").path("arguments")); send(exchange, answer.status(), verdict.proof(), JSON.writeValueAsBytes(answer.result()), "application/json"); } finally { exchange.close(); } } // The proof goes on EVERY answer to a verified request, errors included, and // before sendResponseHeaders: a header set afterwards is never sent. private static void send(HttpExchange exchange, int status, String proof, byte[] body, String contentType) throws IOException { exchange.getResponseHeaders().set("Content-Type", contentType); if (proof != null) { exchange.getResponseHeaders().set("X-Nexus-Proof", proof); } exchange.sendResponseHeaders(status, body.length == 0 ? -1 : body.length); if (body.length > 0) { try (OutputStream out = exchange.getResponseBody()) { out.write(body); } } } } ``` **`src/main/java/endpoint/Verify.java` java** **src/main/java/endpoint/Verify.java** ```java package endpoint; import java.nio.charset.StandardCharsets; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import java.util.HexFormat; import java.util.Map; /** * A complete Nexus402 request verifier for Java 17 or later. Ed25519 is in the * JDK, so this file needs no library. * *

Machine-checked: {@code ../starters_test.go} builds this kit from an empty * directory and drives it with the gateway's REAL signer -- the hello, a paid * call, and forged calls that must be refused. * *

Two checks, and you want both. The creator key is a shared secret on your * server; if it leaks, anyone can impersonate Nexus402 to you. The signature is * asymmetric (you hold only a public key), and it binds a request to YOUR host * and to a 60-second window. The window LIMITS a replay of the same request, it * does not stop one: make your tool's side effects idempotent. */ public final class Verify { /** The fixed first line of the response proof's digested bytes. Copy exactly. */ public static final String PROOF_DOMAIN = "nexus-endpoint-proof-v1"; /** Must match the gateway's 60 seconds, in both directions. */ public static final long SIGNATURE_WINDOW_SECONDS = 60; // Ed25519 keys arrive as 32 raw bytes; the JDK wants X.509 SPKI, whose // Ed25519 header is this fixed 12-byte prefix. private static final byte[] SPKI_ED25519_PREFIX = HexFormat.of().parseHex("302a300506032b6570032100"); /** {@code ok} with the proof and whether it is the hello, or a reason. */ public record Verdict(boolean ok, boolean hello, String proof, String reason) { static Verdict refused(String reason) { return new Verdict(false, false, "", reason); } } private Verify() {} /** Wraps the 32 raw bytes Nexus402 gives you into a JDK public key. */ public static PublicKey publicKeyFromBase64(String base64) throws Exception { byte[] raw = Base64.getDecoder().decode(base64.trim()); if (raw.length != 32) { throw new IllegalArgumentException("ed25519 public key must be 32 bytes, got " + raw.length); } byte[] der = new byte[SPKI_ED25519_PREFIX.length + raw.length]; System.arraycopy(SPKI_ED25519_PREFIX, 0, der, 0, SPKI_ED25519_PREFIX.length); System.arraycopy(raw, 0, der, SPKI_ED25519_PREFIX.length, raw.length); return KeyFactory.getInstance("Ed25519").generatePublic(new X509EncodedKeySpec(der)); } /** Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse. */ public static String bodyHashHex(byte[] rawBody) { return HexFormat.of().formatHex(sha256(rawBody)); } /** * Six fields joined by single newlines, in this order, no trailing newline. * {@code registeredHost} is the host you PUBLISHED, never the inbound Host * header, which a proxy may rewrite. */ public static String canonicalString( String method, String registeredHost, String pathWithQuery, String timestamp, String correlationId, String bodySha256Hex) { // nexus:canonical-begin return String.join("\n", method, registeredHost, pathWithQuery, timestamp, correlationId, bodySha256Hex); // nexus:canonical-end } /** The value Nexus402 requires on EVERY answer to a verified request. */ public static String proof(String correlationId, String timestamp, String signature) { byte[] digest = sha256(String.join("\n", PROOF_DOMAIN, correlationId, timestamp, signature).getBytes(StandardCharsets.UTF_8)); return "sha256:" + Base64.getUrlEncoder().withoutPadding().encodeToString(digest); } /** * Verifies one request. {@code headers} must be keyed by LOWERCASE name. * *

THE HELLO: when you publish, Nexus402 sends one signed POST with an EMPTY * body and NO creator key. {@code hello} is true for it; answer 200 with the * proof and run no tool. Its signature is still verified. */ public static Verdict verifyRequest( Map headers, byte[] rawBody, String method, String pathWithQuery, String registeredHost, String creatorKey, PublicKey publicKey, long nowUnixSeconds) { boolean hello = rawBody.length == 0; // Constant time: MessageDigest.isEqual does not stop at the first // difference, so it leaks nothing about where the keys differ. byte[] presentedKey = sha256(headers.getOrDefault("x-nexus-creator-key", "").getBytes(StandardCharsets.UTF_8)); byte[] expectedKey = sha256(creatorKey.getBytes(StandardCharsets.UTF_8)); if (!hello && !MessageDigest.isEqual(presentedKey, expectedKey)) { return Verdict.refused("creator key mismatch"); } String timestamp = headers.getOrDefault("x-nexus-timestamp", ""); if (!timestamp.matches("\\d{1,18}")) { return Verdict.refused("timestamp is not an integer"); } // BOTH directions: no upper bound means a future-dated request is valid // forever; no lower bound means a captured one replays forever. if (Math.abs(nowUnixSeconds - Long.parseLong(timestamp)) > SIGNATURE_WINDOW_SECONDS) { return Verdict.refused("timestamp outside the 60-second window"); } String presented = headers.getOrDefault("x-nexus-signature", ""); if (!presented.startsWith("ed25519:")) { return Verdict.refused("signature is not ed25519:"); } byte[] signature; try { signature = Base64.getDecoder().decode(presented.substring("ed25519:".length())); } catch (IllegalArgumentException notBase64) { return Verdict.refused("signature is not base64"); } if (signature.length != 64) { return Verdict.refused("signature is not 64 bytes"); } String correlationId = headers.getOrDefault("x-correlation-id", ""); String message = canonicalString(method, registeredHost, pathWithQuery, timestamp, correlationId, bodyHashHex(rawBody)); try { Signature verifier = Signature.getInstance("Ed25519"); verifier.initVerify(publicKey); verifier.update(message.getBytes(StandardCharsets.UTF_8)); if (!verifier.verify(signature)) { return Verdict.refused("signature does not verify"); } } catch (Exception invalid) { return Verdict.refused("signature does not verify"); } return new Verdict(true, hello, proof(correlationId, timestamp, presented), ""); } private static byte[] sha256(byte[] bytes) { try { return MessageDigest.getInstance("SHA-256").digest(bytes); } catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); } } } ``` **`pom.xml` xml** **pom.xml** ```xml 4.0.0 example nexus-endpoint 0.1.0 jar 17 UTF-8 com.fasterxml.jackson.core jackson-databind 2.21.7 nexus-endpoint org.apache.maven.plugins maven-compiler-plugin 3.13.0 org.apache.maven.plugins maven-shade-plugin 3.6.0 package shade false endpoint.Server ``` **C# / .NET.** .NET 8 or later. One package, BouncyCastle.Cryptography, because .NET has no built-in Ed25519. Download the C# / .NET kit (.zip) **Run the C# / .NET kit** ```bash export PORT=8080 export NEXUS_REGISTERED_HOST=mcp.you.example # the host in the URL you publish export NEXUS_CREATOR_KEY=nx_crt_... # shown once when you claim your handle export NEXUS_PUBLIC_KEY= # GET https://api.nexus402.dev/v1/signing-key dotnet run -c Release ``` **`Program.cs` your tools are here** **Program.cs** ```csharp // A complete Nexus402 creator endpoint for C# / .NET 8 or later. // // `dotnet run -c Release`. Set four environment variables, put it behind // HTTPS, and publish its URL. `../starters_test.go` builds this kit from an // empty directory and drives it with the gateway's REAL signer. // // The gateway answers `initialize`, `tools/list` and notifications itself, // from the description and input schema you publish; only `tools/call` // reaches you, already charged. // // PORT where to listen (default 8080) // NEXUS_REGISTERED_HOST the host you published, e.g. mcp.acme.example // NEXUS_CREATOR_KEY your nx_crt_ key, shown once when you claimed a handle // NEXUS_PUBLIC_KEY the gateway's Ed25519 key(s), base64, comma-separated // (GET https://api.nexus402.dev/v1/signing-key lists them) using System.Text.Json; using System.Text.Json.Nodes; using Microsoft.AspNetCore.Http.Features; using NexusEndpoint; // The gateway's own cap on a request body. Anything larger did not come from it. const int MaxBodyBytes = 10 * 1024 * 1024; static string Required(string name) { var value = (Environment.GetEnvironmentVariable(name) ?? "").Trim(); if (value.Length == 0) { Console.Error.WriteLine($"{name} is not set"); Environment.Exit(1); } return value; } // YOUR TOOLS. `tool` is the last segment of the published name // (`acme/text@v2/word_count` arrives as `word_count`). // // Return the status and the bare MCP result. The gateway wraps the result in // the JSON-RPC envelope, so your own envelope would nest. `isError: true` is // still a CHARGED call: use it only when the caller's input made your tool fail // after it did work. When your tool itself fails, return a 5xx; when the // request is wrong before any work, a 4xx. Both refund the caller. static (int Status, object Result) RunTool(string tool, JsonNode? args) { switch (tool) { case "word_count": var text = args?["text"] is JsonValue value && value.TryGetValue(out string? s) ? s.Trim() : ""; var words = text.Length == 0 ? 0 : text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries).Length; return (200, new { content = new[] { new { type = "text", text = words.ToString() } } }); default: return (404, new { error = $"unknown tool {tool}" }); } } var port = Environment.GetEnvironmentVariable("PORT") is { Length: > 0 } p ? int.Parse(p) : 8080; var registeredHost = Required("NEXUS_REGISTERED_HOST"); var creatorKey = Required("NEXUS_CREATOR_KEY"); // More than one while the gateway rotates its key: accept any of them. var publicKeys = Required("NEXUS_PUBLIC_KEY").Split(',').Select(Verify.PublicKeyFromBase64).ToList(); var builder = WebApplication.CreateSlimBuilder(args); builder.Logging.ClearProviders(); builder.WebHost.ConfigureKestrel(options => { options.ListenAnyIP(port); options.Limits.MaxRequestBodySize = MaxBodyBytes; }); var app = builder.Build(); // The proof goes on EVERY answer to a verified request, errors included. static async Task Answer(HttpContext context, int status, string? proof, byte[] body, string contentType = "application/json") { context.Response.StatusCode = status; context.Response.ContentType = contentType; if (proof is not null) { context.Response.Headers["X-Nexus-Proof"] = proof; } await context.Response.Body.WriteAsync(body); } app.Run(async context => { if (!HttpMethods.IsPost(context.Request.Method)) { context.Response.Headers.Allow = "POST"; context.Response.StatusCode = 405; return; } byte[] rawBody; try { using var buffer = new MemoryStream(); await context.Request.Body.CopyToAsync(buffer); rawBody = buffer.ToArray(); } catch (BadHttpRequestException) { context.Response.StatusCode = 413; return; } string Header(string name) => context.Request.Headers.TryGetValue(name, out var v) ? v.ToString() : ""; // The request target exactly as sent: path plus query, still encoded. // Request.Path is DECODED, so it would not match what the gateway signed. var target = context.Features.Get()?.RawTarget ?? ""; var now = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); var verdict = Verdict.Refused("no public key"); foreach (var key in publicKeys) { verdict = Verify.VerifyRequest(Header, rawBody, context.Request.Method, target, registeredHost, creatorKey, key, now); if (verdict.Ok) { break; } } if (!verdict.Ok) { // No detail in the body: a reason tells a prober how close they are. Console.Error.WriteLine($"refused: {verdict.Reason}"); await Answer(context, 401, null, "unauthorized"u8.ToArray(), "text/plain"); return; } // THE HELLO: the signed, empty-body check sent when you publish. // Answer with the proof and run nothing. if (verdict.Hello) { await Answer(context, 200, verdict.Proof, []); return; } JsonNode? call; try { call = JsonNode.Parse(rawBody); } catch (JsonException) { await Answer(context, 400, verdict.Proof, JsonSerializer.SerializeToUtf8Bytes(new { error = "body is not JSON" })); return; } var name = call?["params"]?["name"] is JsonValue n && n.TryGetValue(out string? s) ? s : ""; var (status, result) = RunTool(name[(name.LastIndexOf('/') + 1)..], call?["params"]?["arguments"]); await Answer(context, status, verdict.Proof, JsonSerializer.SerializeToUtf8Bytes(result)); }); Console.WriteLine($"listening on :{port} for {registeredHost}"); app.Run(); ``` **`Verify.cs` csharp** **Verify.cs** ```csharp // A complete Nexus402 request verifier for C# / .NET 8 or later. // // .NET has no built-in Ed25519, so this uses BouncyCastle.Cryptography for // that one check; SHA-256 and the constant-time compare are in the runtime. // `../starters_test.go` builds this kit from an empty directory and drives it // with the gateway's REAL signer -- the hello, a paid call, and forged calls // that must be refused. // // Two checks, and you want both. The creator key is a shared secret on your // server; if it leaks, anyone can impersonate Nexus402 to you. The signature // is asymmetric (you hold only a public key), and it binds a request to YOUR // host and to a 60-second window. The window LIMITS a replay of the same // request, it does not stop one: make your tool's side effects idempotent. using System.Security.Cryptography; using System.Text; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Signers; namespace NexusEndpoint; ///

Ok with the proof and whether it is the hello, or a reason. public sealed record Verdict(bool Ok, bool Hello, string Proof, string Reason) { public static Verdict Refused(string reason) => new(false, false, "", reason); } public static class Verify { /// The fixed first line of the response proof's digested bytes. Copy exactly. public const string ProofDomain = "nexus-endpoint-proof-v1"; /// Must match the gateway's 60 seconds, in both directions. public const long SignatureWindowSeconds = 60; /// Reads the 32 raw bytes Nexus402 gives you, base64. public static Ed25519PublicKeyParameters PublicKeyFromBase64(string base64) { var raw = Convert.FromBase64String(base64.Trim()); if (raw.Length != 32) { throw new ArgumentException($"ed25519 public key must be 32 bytes, got {raw.Length}"); } return new Ed25519PublicKeyParameters(raw, 0); } /// Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse. public static string BodyHashHex(byte[] rawBody) => Convert.ToHexString(SHA256.HashData(rawBody)).ToLowerInvariant(); /// /// Six fields joined by single newlines, in this order, no trailing newline. /// registeredHost is the host you PUBLISHED, never the inbound Host header, /// which a proxy may rewrite. /// public static string CanonicalString( string method, string registeredHost, string pathWithQuery, string timestamp, string correlationId, string bodySha256Hex) { // nexus:canonical-begin return string.Join("\n", method, registeredHost, pathWithQuery, timestamp, correlationId, bodySha256Hex); // nexus:canonical-end } /// The value Nexus402 requires on EVERY answer to a verified request. public static string Proof(string correlationId, string timestamp, string signature) { var digest = SHA256.HashData(Encoding.UTF8.GetBytes(string.Join("\n", ProofDomain, correlationId, timestamp, signature))); return "sha256:" + Convert.ToBase64String(digest).TrimEnd('=').Replace('+', '-').Replace('/', '_'); } /// /// Verifies one request. THE HELLO: when you publish, Nexus402 sends one /// signed POST with an EMPTY body and NO creator key. Hello is true for it; /// answer 200 with the proof and run no tool. Its signature is still verified. /// public static Verdict VerifyRequest( Func header, byte[] rawBody, string method, string pathWithQuery, string registeredHost, string creatorKey, Ed25519PublicKeyParameters publicKey, long nowUnixSeconds) { var hello = rawBody.Length == 0; // Constant time: FixedTimeEquals does not stop at the first difference. var presentedKey = SHA256.HashData(Encoding.UTF8.GetBytes(header("X-Nexus-Creator-Key"))); var expectedKey = SHA256.HashData(Encoding.UTF8.GetBytes(creatorKey)); if (!hello && !CryptographicOperations.FixedTimeEquals(presentedKey, expectedKey)) { return Verdict.Refused("creator key mismatch"); } var timestamp = header("X-Nexus-Timestamp"); if (timestamp.Length == 0 || timestamp.Length > 18 || !timestamp.All(char.IsAsciiDigit)) { return Verdict.Refused("timestamp is not an integer"); } // BOTH directions: no upper bound means a future-dated request is valid // forever; no lower bound means a captured one replays forever. if (Math.Abs(nowUnixSeconds - long.Parse(timestamp)) > SignatureWindowSeconds) { return Verdict.Refused("timestamp outside the 60-second window"); } var presented = header("X-Nexus-Signature"); if (!presented.StartsWith("ed25519:", StringComparison.Ordinal)) { return Verdict.Refused("signature is not ed25519:"); } byte[] signature; try { signature = Convert.FromBase64String(presented["ed25519:".Length..]); } catch (FormatException) { return Verdict.Refused("signature is not base64"); } if (signature.Length != 64) { return Verdict.Refused("signature is not 64 bytes"); } var correlationId = header("X-Correlation-ID"); var message = Encoding.UTF8.GetBytes( CanonicalString(method, registeredHost, pathWithQuery, timestamp, correlationId, BodyHashHex(rawBody))); var verifier = new Ed25519Signer(); verifier.Init(false, publicKey); verifier.BlockUpdate(message, 0, message.Length); if (!verifier.VerifySignature(signature)) { return Verdict.Refused("signature does not verify"); } return new Verdict(true, hello, Proof(correlationId, timestamp, presented), ""); } } ``` **`NexusEndpoint.csproj` xml** **NexusEndpoint.csproj** ```xml net8.0 enable enable NexusEndpoint true ``` **Ruby.** Ruby 3.1 or later. One gem, webrick; Ed25519 comes from Ruby's own OpenSSL. Download the Ruby kit (.zip) **Run the Ruby kit** ```bash bundle install export PORT=8080 export NEXUS_REGISTERED_HOST=mcp.you.example # the host in the URL you publish export NEXUS_CREATOR_KEY=nx_crt_... # shown once when you claim your handle export NEXUS_PUBLIC_KEY= # GET https://api.nexus402.dev/v1/signing-key bundle exec ruby server.rb ``` **`server.rb` your tools are here** **server.rb** ```ruby # frozen_string_literal: true # A complete Nexus402 creator endpoint for Ruby 3.1 or later. One gem: webrick. # # `bundle install && bundle exec ruby server.rb`. Set four environment # variables, put it behind HTTPS, and publish its URL. `../starters_test.go` # serves this exact file and drives it with the gateway's REAL signer. # # The gateway answers `initialize`, `tools/list` and notifications itself, # from the description and input schema you publish; only `tools/call` # reaches you, already charged. # # PORT where to listen (default 8080) # NEXUS_REGISTERED_HOST the host you published, e.g. mcp.acme.example # NEXUS_CREATOR_KEY your nx_crt_ key, shown once when you claimed a handle # NEXUS_PUBLIC_KEY the gateway's Ed25519 key(s), base64, comma-separated # (GET https://api.nexus402.dev/v1/signing-key lists them) require "json" require "webrick" require_relative "verify" # The gateway's own cap on a request body. Anything larger did not come from it. MAX_BODY_BYTES = 10 * 1024 * 1024 # A stranger can open a connection and send bytes before anything is verified. # So only this many connections are served at once (the next one waits), and # each has deadlines. WEBrick's own RequestTimeout covers ONE read at a time, # which a slow trickle of bytes never reaches; the other two cover all the # headers and the whole body. The gateway opens at most 64 connections to you. MAX_CONNECTIONS = 100 READ_SECONDS = 10 HEADERS_SECONDS = 10 BODY_SECONDS = 30 def required(name) value = ENV.fetch(name, "").strip abort "#{name} is not set" if value.empty? value end # YOUR TOOLS. `tool` is the last segment of the published name # (`acme/text@v2/word_count` arrives as `word_count`). # # Return [status, the bare MCP result]. The gateway wraps the result in the # JSON-RPC envelope, so your own envelope would nest. `isError: true` is # still a CHARGED call: use it only when the caller's input made your tool fail # after it did work. When your tool itself fails, return a 5xx; when the # request is wrong before any work, a 4xx. Both refund the caller. def run_tool(tool, args) case tool when "word_count" text = args["text"].is_a?(String) ? args["text"] : "" [200, { content: [{ type: "text", text: text.split.length.to_s }] }] else [404, { error: "unknown tool #{tool}" }] end end PORT = Integer(ENV.fetch("PORT", "8080")) REGISTERED_HOST = required("NEXUS_REGISTERED_HOST") CREATOR_KEY = required("NEXUS_CREATOR_KEY") # More than one while the gateway rotates its key: accept any of them. PUBLIC_KEYS = required("NEXUS_PUBLIC_KEY").split(",").map { |key| NexusVerify.public_key_from_base64(key) } # The proof goes on EVERY answer to a verified request, errors included. def answer(response, status, proof, body) response.status = status response["Content-Type"] = "application/json" response["X-Nexus-Proof"] = proof response.body = body.nil? ? "" : JSON.generate(body) end class DeadlineRequest < WEBrick::HTTPRequest def parse(socket = nil) WEBrick::Utils.timeout(HEADERS_SECONDS, WEBrick::HTTPStatus::RequestTimeout) { super } end # One request per connection. An idle one would keep its place, and before # WEBrick reuses a connection it READS whatever is left of the last body, # however large; a connection it will close is closed without that. def keep_alive? false end # The raw body, or nil once it passes the limit. `body` with a block hands # over each piece, at most 64 KiB and chunked encoding decoded, and keeps # none of it; without a block it keeps them all, however many there are. def body_within(limit) return nil if self["content-length"].to_i > limit raw_body = String.new(encoding: Encoding::BINARY) WEBrick::Utils.timeout(BODY_SECONDS, WEBrick::HTTPStatus::RequestTimeout) do body do |piece| return nil if raw_body.bytesize + piece.bytesize > limit raw_body << piece end end raw_body end end class EndpointServer < WEBrick::HTTPServer def create_request(config) DeadlineRequest.new(config) end end class Endpoint < WEBrick::HTTPServlet::AbstractServlet def do_GET(_request, response) # rubocop:disable Naming/MethodName response.status = 405 response["Allow"] = "POST" end def do_POST(request, response) # rubocop:disable Naming/MethodName raw_body = request.body_within(MAX_BODY_BYTES) if raw_body.nil? response.status = 413 return end header = ->(name) { request[name] } verdict = NexusVerify::Verdict.new(ok: false, reason: "no public key") PUBLIC_KEYS.each do |public_key| verdict = NexusVerify.verify_request( header: header, raw_body: raw_body, method: request.request_method, # The request target exactly as sent: path plus query, still encoded. path_with_query: request.unparsed_uri, registered_host: REGISTERED_HOST, creator_key: CREATOR_KEY, public_key: public_key ) break if verdict.ok end unless verdict.ok # No detail in the body: a reason tells a prober how close they are. warn "refused: #{verdict.reason}" response.status = 401 response["Content-Type"] = "text/plain" response.body = "unauthorized" return end # THE HELLO: the signed, empty-body check sent when you publish. # Answer with the proof and run nothing. return answer(response, 200, verdict.proof, nil) if verdict.hello begin call = JSON.parse(raw_body) rescue JSON::ParserError return answer(response, 400, verdict.proof, { error: "body is not JSON" }) end params = call.is_a?(Hash) && call["params"].is_a?(Hash) ? call["params"] : {} name = params["name"].is_a?(String) ? params["name"] : "" args = params["arguments"].is_a?(Hash) ? params["arguments"] : {} status, result = run_tool(name.split("/").last.to_s, args) answer(response, status, verdict.proof, result) end end server = EndpointServer.new( Port: PORT, BindAddress: "0.0.0.0", MaxClients: MAX_CONNECTIONS, RequestTimeout: READ_SECONDS, # Request lines carry paths and queries a caller chose; keep them out. AccessLog: [], Logger: WEBrick::Log.new($stderr, WEBrick::Log::WARN) ) server.mount("/", Endpoint) trap("INT") { server.shutdown } trap("TERM") { server.shutdown } puts "listening on :#{PORT} for #{REGISTERED_HOST}" $stdout.flush server.start ``` **`verify.rb` ruby** **verify.rb** ```ruby # frozen_string_literal: true # A complete Nexus402 request verifier for Ruby 3.1 or later. # # Ed25519 comes from Ruby's own OpenSSL (openssl gem 3.0, OpenSSL 1.1.1 or # later), so this file # needs no gem. `../starters_test.go` serves `server.rb`, which uses this file, # and drives it with the gateway's REAL signer -- the hello, a paid call, and # forged calls that must be refused. # # Two checks, and you want both. The creator key is a shared secret on your # server; if it leaks, anyone can impersonate Nexus402 to you. The signature # is asymmetric (you hold only a public key), and it binds a request to YOUR # host and to a 60-second window. The window LIMITS a replay of the same # request, it does not stop one: make your tool's side effects idempotent. require "digest" require "openssl" module NexusVerify # The fixed first line of the response proof's digested bytes. Copy exactly. PROOF_DOMAIN = "nexus-endpoint-proof-v1" # Must match the gateway's 60 seconds, in both directions. SIGNATURE_WINDOW_SECONDS = 60 # Ed25519 keys arrive as 32 raw bytes; OpenSSL wants DER SPKI, whose Ed25519 # header is this fixed 12-byte prefix. SPKI_ED25519_PREFIX = ["302a300506032b6570032100"].pack("H*") Verdict = Struct.new(:ok, :hello, :proof, :reason, keyword_init: true) module_function # Wraps the 32 raw bytes Nexus402 gives you into an OpenSSL key. def public_key_from_base64(base64) raw = base64.strip.unpack1("m0") raise ArgumentError, "ed25519 public key must be 32 bytes, got #{raw.bytesize}" unless raw.bytesize == 32 OpenSSL::PKey.read(SPKI_ED25519_PREFIX + raw) end # Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse. def body_hash_hex(raw_body) Digest::SHA256.hexdigest(raw_body) end # Six fields joined by single newlines, in this order, no trailing newline. # registered_host is the host you PUBLISHED, never the inbound Host header, # which a proxy may rewrite. def canonical_string(method, registered_host, path_with_query, timestamp, correlation_id, body_sha256_hex) # nexus:canonical-begin [method, registered_host, path_with_query, timestamp, correlation_id, body_sha256_hex].join("\n") # nexus:canonical-end end # The value Nexus402 requires on EVERY answer to a verified request. def proof(correlation_id, timestamp, signature) digest = Digest::SHA256.digest([PROOF_DOMAIN, correlation_id, timestamp, signature].join("\n")) # base64url without padding. "sha256:#{[digest].pack("m0").tr("+/", "-_").delete("=")}" end # Verifies one request. `header` is a lambda taking a header name, in any case. # # THE HELLO: when you publish, Nexus402 sends one signed POST with an EMPTY # body and NO creator key. `hello` is true for it; answer 200 with the proof # and run no tool. Its signature is still verified. def verify_request(header:, raw_body:, method:, path_with_query:, registered_host:, creator_key:, public_key:, now_unix_seconds: Time.now.to_i) hello = raw_body.empty? # Constant time: secure_compare does not stop at the first difference. presented_key = Digest::SHA256.digest(header.call("X-Nexus-Creator-Key").to_s) expected_key = Digest::SHA256.digest(creator_key) if !hello && !OpenSSL.fixed_length_secure_compare(presented_key, expected_key) return Verdict.new(ok: false, reason: "creator key mismatch") end timestamp = header.call("X-Nexus-Timestamp").to_s return Verdict.new(ok: false, reason: "timestamp is not an integer") unless timestamp.match?(/\A\d{1,18}\z/) # BOTH directions: no upper bound means a future-dated request is valid # forever; no lower bound means a captured one replays forever. if (now_unix_seconds - timestamp.to_i).abs > SIGNATURE_WINDOW_SECONDS return Verdict.new(ok: false, reason: "timestamp outside the 60-second window") end presented = header.call("X-Nexus-Signature").to_s return Verdict.new(ok: false, reason: "signature is not ed25519:") unless presented.start_with?("ed25519:") begin signature = presented.delete_prefix("ed25519:").unpack1("m0") rescue ArgumentError return Verdict.new(ok: false, reason: "signature is not base64") end return Verdict.new(ok: false, reason: "signature is not 64 bytes") unless signature.bytesize == 64 correlation_id = header.call("X-Correlation-ID").to_s message = canonical_string(method, registered_host, path_with_query, timestamp, correlation_id, body_hash_hex(raw_body)) verified = begin public_key.verify(nil, signature, message) rescue OpenSSL::PKey::PKeyError false end return Verdict.new(ok: false, reason: "signature does not verify") unless verified Verdict.new(ok: true, hello: hello, proof: proof(correlation_id, timestamp, presented)) end end ``` **`Gemfile` ruby** **Gemfile** ```ruby # frozen_string_literal: true source "https://rubygems.org" # The HTTP server. Ed25519, SHA-256 and JSON come with Ruby itself. gem "webrick", "~> 1.9" ``` ## What to try once a call lands These four cases teach the system faster than a working call does: | Do this | Expect | | --- | --- | | Return a `500` | The developer is refunded automatically and you are not paid: the failure happened before any byte reached them | | Sleep 10 seconds before the first byte | Cut at 5 seconds idle. The developer gets `502 Upstream_Unavailable` and is refunded | | Return a `302` with a `Location` | Clamped to `502` and the header stripped. We never follow a redirect | | Send a request with the wrong creator key yourself | Your endpoint answers `401` with no proof, which shows the check works before you rely on it | > **Next: put it online** > > Your server works locally. [Host and publish](https://www.nexus402.dev/docs/creators/build-a-server/publish/) covers where to run it, connecting it to your account, publishing a priced version, free calls, and testing and troubleshooting it. --- # Host and publish > Run your server wherever you like, connect it to your account, publish a priced version, and test it end to end. Source: https://www.nexus402.dev/docs/creators/build-a-server/publish/ This is part two of [Build a Server](https://www.nexus402.dev/docs/creators/build-a-server/). You have an endpoint that answers the hello and returns a result with a proof; now it goes online and into the catalogue. We host nothing, so the first step is yours. ## Deployment and hosting Any host works if it meets four conditions: 1. **HTTPS on port 443** with a valid certificate, at a hostname whose every address is public. One private address in the DNS answer and the gateway refuses to dial. 2. **Fast first bytes.** Response headers within 5 seconds of the request, and no silence longer than 5 seconds; the whole call within 120. 3. **The raw request body** reaches your code unchanged, because the signature covers its exact bytes. Do not let a framework parse and re-serialise JSON before you verify. 4. **`/.well-known/` at the root of the host is served as is**, with no redirect, for the one-time host proof. | Option | Fits when | Watch for | | --- | --- | --- | | A virtual server with a reverse proxy that obtains certificates (Caddy, nginx with Let's Encrypt) | You want full control and steady latency | Keep the proxy from buffering or rewriting the body, and forward `/.well-known/` | | A container platform (Cloud Run, Fly.io, Render, Railway, App Runner) | You want HTTPS and scaling handled for you | Scale-to-zero cold starts can exceed the 5-second header limit; keep one instance warm | | A serverless function (Vercel, Netlify, AWS Lambda behind a function URL) | Traffic is bursty and calls are short | Wrap the same logic in the platform's handler; read the body as raw bytes; mind cold starts and the platform's own time limit | Whatever you choose, the gateway sees one URL. To move hosts later, publish a new version at the new URL: a published version's endpoint never changes. ## Connect your account 1. **Sign in** to the app with Google, GitHub or Apple and choose the creator role. There is no password. 2. **Claim a handle** in Creator settings: 3 to 39 characters of lowercase letters, digits and `-`, starting with a letter or digit. One per account, and it is never released, so nobody can later take your name and the calls meant for you. 3. **Save the creator key** from the claim answer, `nx_crt_…`. It is shown once; we keep only a derived value. If you lose it, rotate it in Creator settings, where we email you a code to confirm it is you. The gateway sends the new key within 30 seconds, so calls fail until your server accepts it: deploy it straight away, and accept the previous key too for a minute after. 4. **Set `NEXUS_CREATOR_KEY`** and `NEXUS_PUBLIC_KEY` on your server and deploy it. ## Register and publish a version Open **Publish a version** in the app. The wizard has five steps, and checks each one with the server's own rules before you continue: | Step | What you set | | --- | --- | | Basics | The server and tool names, the version (`v` and digits, such as `v1`), and a category | | Endpoint | The HTTPS URL of your server, up to 2,048 characters | | Pricing | The price per call, more than $0 and up to $5.00 by default, and, for a new tool, any free calls | | Schema and docs | A description (up to 4,096 characters), the input schema as a JSON object, example arguments, an optional example output, and what changed | | Review | Everything once more. Nothing here can change after publishing | The example output is optional: a JSON object of up to 16 KiB showing what one call with your example arguments returns, such as `{"content":[{"type":"text","text":"..."}]}`. It is shown on your tool's page as text, beside the example arguments, and is never run. When you confirm, the server checks, in this order: 1. **Host proof**, the first time you publish at a host. The answer is `403 host_proof_required` with a URL and a line of text: serve that text as the whole body at that URL, then publish again. Once a version is live at the host, the file can go. Details are on [the quickstart](https://www.nexus402.dev/docs/creators/quickstart/#host-proof). 2. **Publish code**, only when you move an existing tool to a host it has never used: a code is emailed to you, so a stolen session cannot redirect your tool's calls. 3. **The hello**: one signed, empty-body request to your endpoint, which must answer `2xx` with the proof. The version is then published, and gateways pick it up within about five minutes. A price more than twice what unpinned callers were paying waits seven days before unpinned callers reach it; developers who pin the version reach it at once. > **A version is permanent** > > Its price, endpoint and text never change. A fix or a new price ships as `v2`; `v1` keeps routing for anyone pinned to it until you retire it, and retiring stops its calls. See [Versions are immutable](https://www.nexus402.dev/docs/creators/versions/). ## Free calls Give every account a number of free calls of a tool per UTC day, week or month, from 0 (off, the default) to 1,000. Set it on the pricing step when you publish a new tool, or later on the tool's page; it belongs to the tool, so every version shares it and a new version keeps it. You earn nothing on a free call, and it reaches your endpoint exactly like a paid one. A new account that has never paid can take free calls only while it holds trial credit, so one person making many accounts cannot drain your allowance. Your dashboard shows the free calls each tool served in the last 30 days. ## Testing 1. **Before publishing**, test `runTool` on its own with ordinary unit tests: the signature cannot be produced without the gateway's private key, so the network path is tested from the gateway. 2. **Send test request** on the tool's page in the app sends your endpoint the hello and then one signed `tools/call` with your example arguments and `X-Nexus-Test: 1`, and shows what came back. Nobody is charged. It runs at most ten times an hour. 3. **A real call**: make a developer key on your own account and call the tool as a developer would. It is a real charge at your price, and earnings from your own account are held longer than others. **Call your published tool as a developer** ```bash curl -s https://api.nexus402.dev/v1/mcp \ -H "X-Nexus-Api-Key: $NEXUS402_API_KEY" \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call", "params":{"name":"acme/text/word_count","arguments":{"text":"we add the meter"}}}' ``` Then watch the tool's page: [endpoint health](https://www.nexus402.dev/docs/creators/endpoint-health/) shows failures and the last call delivered, and your dashboard shows calls served. ## Debugging and troubleshooting Your own logs are the first place to look: the samples log why they refused a request, and never say why in the answer. | What you see | Cause | Fix | | --- | --- | --- | | `403 host_proof_required` on publish | First publish at this host | Serve the challenge text at the challenge URL, then publish again | | `422 endpoint_hello_failed` | Your endpoint did not answer the empty-body hello with `2xx` and the proof. Most often: the key check ran first and refused it | Answer an empty body before the key check, as the samples do. Check the URL and that the server is up | | `409 endpoint_taken` | Another creator already publishes at that host | Use a hostname of your own; a subdomain is enough | | `409 listed_name_taken` | MCP clients see tools as `handle_server_tool`, and another tool already has this one's, ignoring case. The message names it | Choose a different server or tool name | | `409 version_exists` | That version is already published | Publish the next version | | `400 price_above_ceiling` | The price is over the per-call ceiling ($5.00 by default) | Lower the price | | Log: "signature does not verify" | Verifying against the inbound `Host`, a re-serialised body, or an old public key | Use the published host, the raw body bytes, and every key from `/v1/signing-key` | | Log: "timestamp outside the 60-second window" | Your clock is wrong | Run time synchronisation (NTP) | | Log: "creator key mismatch" | An old or mistyped key, often after a rotation | Deploy the current key; accept the previous one during the overlap | | Developers get `502 Upstream_Unavailable` | A timeout, a `5xx`, a refused dial, or a `2xx` without a valid proof | Check response time and the proof header; they were not charged | | The version disappeared from the catalogue | Twenty failures in a row de-list it | Fix the endpoint, then publish the same version with the same price and endpoint to restore it | > **Getting paid** > > Calls settle in five-minute rollups. To withdraw, connect Stripe in the app; see [When you earn](https://www.nexus402.dev/docs/creators/settlement/) and [Payouts](https://www.nexus402.dev/docs/creators/payouts/). --- # Verifying a request > Two checks, the proof you must return, and a complete verifier in nine languages. Source: https://www.nexus402.dev/docs/creators/verifying/ Two checks, and **you want both**. The first is a header comparison you can write in a line. The second is not redundancy — it is what makes the first one survive a leak, it stops a captured request being used at somebody else’s endpoint, and it limits a replay at yours to 60 seconds. It does not stop a replay within them, so make your tool’s side effects idempotent. ## The creator key A paid call carries your key in `X-Nexus-Creator-Key`. Compare it in constant time against the value you stored. Two requests carry no key at all, by design: [the hello](#hello), and the host-proof `GET` for `/.well-known/nexus402-challenge/`. The gateway also reloads creator keys every 30 seconds, so just after you claim a handle a paid call can arrive without one, and just after you rotate it can carry the previous key. Every one of these is still signed, which is the check below. **The creator-key check — Python** ``` import hmac, os EXPECTED = os.environ["NEXUS_CREATOR_KEY"].encode() def authorized(headers) -> bool: presented = headers.get("X-Nexus-Creator-Key", "").encode() return hmac.compare_digest(presented, EXPECTED) ``` **The creator-key check — Node.js** ``` import { createHash, timingSafeEqual } from "node:crypto"; const EXPECTED = process.env.NEXUS_CREATOR_KEY; // timingSafeEqual THROWS when the lengths differ, and that throw is itself a // length oracle — so hash both sides to a fixed width first. const fingerprint = (value) => createHash("sha256").update(String(value), "utf8").digest(); export function authorized(headers) { const presented = headers["x-nexus-creator-key"] ?? ""; return timingSafeEqual(fingerprint(presented), fingerprint(EXPECTED)); } ``` **The creator-key check — Go** ``` var expected = []byte(os.Getenv("NEXUS_CREATOR_KEY")) func authorized(r *http.Request) bool { presented := []byte(r.Header.Get("X-Nexus-Creator-Key")) return subtle.ConstantTimeCompare(presented, expected) == 1 } ``` **The creator-key check — Rust** ``` use subtle::ConstantTimeEq; fn authorized(headers: &HeaderMap, expected: &str) -> bool { let presented = headers .get("x-nexus-creator-key") .and_then(|value| value.to_str().ok()) .unwrap_or_default(); presented.as_bytes().ct_eq(expected.as_bytes()).unwrap_u8() == 1 } ``` **The creator-key check — PHP** ``` **Constant time, not ==** > > A byte-at-a-time comparison returns faster the earlier it finds a difference, which leaks the key one position at a time to anyone who can measure your response. Use your language's constant-time compare: `hmac.compare_digest`, `crypto.timingSafeEqual`, `subtle.ConstantTimeCompare`. ## The Ed25519 signature The creator key is a **shared secret** sitting on your server, in an environment variable, possibly in a log. If it leaks, anyone can impersonate Nexus402 to you and take free tool calls. The signature is asymmetric: you hold only a public key, so there is nothing on your side worth stealing. The public key is served by `GET /v1/signing-key` as a list, newest first: the first is the key we sign with now, and any others are being retired. Accept a signature that verifies against **any** key in the list, and re-read it periodically (it is cacheable for five minutes) so a rotation is not an outage. The current key is also returned as `signing_public_key` when you claim a handle and when you publish. Three headers carry it: **Signature headers** ```text X-Nexus-Signature: ed25519: X-Nexus-Timestamp: X-Correlation-ID: ``` Treat the correlation id as an opaque string. On a paid call it is a UUID; the hello, your own endpoint test and the host proof use ids starting `hello-` or `nexus-hello-`, `test-` and `host-`. Sign and digest it exactly as received. The signed message is exactly six fields joined by single newlines: **The canonical string** ```text \n\n\n\n\n ``` ### The host, and the mistake everyone makes > **Use the host you REGISTERED, never the inbound Host header** > > The signature covers the host the gateway sent. Behind a proxy, a load balancer or a managed platform router, the `Host` your process sees may have been rewritten — and a verifier reading that header will then reject every valid request. > > The registered host is a constant you already have in configuration. Our reference endpoint refuses to start if you give it a public key without one — and refuses to start without a public key at all unless you ask for that explicitly — specifically so both are found at deploy time rather than in production. Why is the host signed at all? Because every creator verifies with the same platform key. Without the host, a request we signed for one creator would also verify at another creator's endpoint on the same path — letting one creator replay our signature at yours and collect your tool's output unpaid. Three things keep creators apart: the host in the signed message, one creator per host (proven when you publish), and your own creator key on every call. Check all three: a verifier that skips the creator key and reads the host from the incoming request instead of your configuration is the one combination this does not protect. ### Three more things that silently weaken the check - **Hash the raw body bytes**, before any JSON parse or re-serialise. Re-encoding changes the bytes and the hash will not match. - **Enforce the 60-second window in both directions.** Without an upper bound a future-dated request is valid forever; without a lower one a captured request replays forever. - **Join with `\\n` and nothing else.** No trailing newline, no spaces, no carriage returns. ### The proof you must return — required Verifying tells you the request is ours. The proof tells us your server is yours. Return `X-Nexus-Proof` on **every** response, including your own errors — without it we will not publish your tool, and once published we will not pay you for a call. **The bytes you digest, newline-separated, in this order** ``` nexus-endpoint-proof-v1 ``` Send it as `X-Nexus-Proof: sha256:` followed by the digest in base64url with no padding. Copy the first line exactly: it is part of the contract, and it exists so this digest can never be confused with another we may define over the same fields. > **Set it BEFORE you write the status** > > Once you call your framework’s equivalent of `WriteHeader`, the header block is committed and anything set afterwards is dropped in silence — which looks exactly like never having implemented this. You store nothing: the digest is bound to the correlation id and timestamp of the request in front of you, so a value captured from one call cannot be replayed on another. **Your 4xx is still your 4xx.** How a response counts against you: - **Any `5xx`** is a fault of your endpoint, proof or no proof. - **A `4xx` with the proof** never is. It is your rejection of the caller — a bad argument, a failed bring-your-own-auth — and is relayed to them. - **A `4xx` or `2xx` without the proof** is a fault only if our own [hello](#hello) to your endpoint fails too. A body limit or a proxy in front of a working server answers without the proof, and the caller chose that body, so we ask your server directly before blaming it. - **A `2xx` without a valid proof** is never a sale, whoever is to blame: the developer gets `502`, is not charged, and you are not paid. Twenty consecutive faults de-list the version; see [endpoint health](https://www.nexus402.dev/docs/creators/endpoint-health/). **What it does not prove.** It proves your server received and parsed a signed request. It is not authentication and not proof of identity: anyone holding the request can compute the digest. The signature check above is the real one, and you should keep doing it. The proof exists so that a parked domain or an unrelated API cannot be published as a tool and paid for answering `200 OK`. > **A working implementation, tested against our real signer** > > Every [starter kit](https://www.nexus402.dev/docs/creators/build-a-server/#starters) does all of this. Our tests drive the gateway's actual signing code against each one, so if the signed message ever changes the kits break in our build before they reach you. ## The hello When you publish, and later whenever we need to judge a response of yours that came back without the proof, the gateway sends your published URL one signed `POST` with an **empty body**, **no** `X-Nexus-Creator-Key` and **no** `Authorization`. There is no caller, so there is nothing to bill and nobody's credential to forward. - **Still verify the signature.** It is signed exactly like a paid call. - **Skip the creator-key check** for an empty body. A server that refuses the hello for lacking the key can never publish. - **Run no tool.** Answer `2xx` with `X-Nexus-Proof`; the body is never read. The complete verifiers below already do this: an empty body skips the key check and still verifies the signature. The Node one returns `{ ok, hello, proof }`, and `hello` is true for this request. ## A complete verifier Both checks, the 60-second window in both directions, and the response proof — in one file you can copy. Each is the verifier inside its language’s [starter kit](https://www.nexus402.dev/docs/creators/build-a-server/#starters), which adds the server around it. > **All nine are machine-checked against our real signer** > > Our test suite builds each language’s starter kit from an empty folder and sends it the gateway’s real hello, a real signed call and seven forged ones: a bad signature, the wrong or a missing creator key, a changed body, another path, a stale timestamp and an unprefixed signature. Every kit must answer the first two with the proof and refuse the rest. That runs on every change, so a verifier here cannot drift from the gateway. **examples/verifiers — Node.js** ``` // A complete Nexus402 request verifier for Node.js. NO DEPENDENCIES. // // Copy this file. It is not a package to import, so it can never version-skew // against the gateway — the same reasoning as `examples/creator-pingback`. // // `agreement_test.go` beside this directory drives the gateway's REAL signer // (`egress.DevSigner`, the one `cmd/gateway` uses) against this code and // refuses to pass if the two ever disagree on the canonical string. That test // is what makes this documentation rather than a guess: a verifier can be // perfectly self-consistent and still disagree with the gateway, and then // every creator who copies it gets a dead endpoint and no clue why. // // Two checks, and you want both. The creator key is a shared secret on your // server; if it leaks, anyone can impersonate Nexus402 to you and take free // tool calls. The signature is asymmetric — you hold only a public key — and // it is also what binds a request to YOUR host and to a 60-second window, so // losing it loses both. The window LIMITS a replay of the same request, it // does not stop one: make your tool's side effects idempotent. import { createHash, createPublicKey, timingSafeEqual, verify } from "node:crypto"; /** * The fixed first line of the response proof's digested bytes. * * Copy it exactly. It is part of the contract, and it exists so this digest * can never be confused with another defined over the same fields. */ export const PROOF_DOMAIN = "nexus-endpoint-proof-v1"; /** * Must match the gateway's 60 seconds. Wider accepts older replays; narrower * rejects honest requests on ordinary clock skew. */ export const SIGNATURE_WINDOW_SECONDS = 60; // An Ed25519 public key arrives as 32 raw bytes in base64. `createPublicKey` // wants DER, and for Ed25519 the SPKI header is a fixed 12-byte prefix, so // wrapping is a concatenation rather than a dependency. const SPKI_ED25519_PREFIX = Buffer.from("302a300506032b6570032100", "hex"); /** Wraps the 32 raw bytes Nexus402 gives you into a usable KeyObject. */ export function publicKeyFromBase64(base64) { const raw = Buffer.from(base64, "base64"); if (raw.length !== 32) { throw new Error(`ed25519 public key must be 32 bytes, got ${raw.length}`); } return createPublicKey({ key: Buffer.concat([SPKI_ED25519_PREFIX, raw]), format: "der", type: "spki", }); } /** * Lowercase hex SHA-256 of the RAW body bytes. * * Hash before any JSON parse or re-serialise: re-encoding changes the bytes * and the hash will not match. */ export function bodyHashHex(rawBody) { return createHash("sha256").update(rawBody).digest("hex"); } /** * The signed message: six fields joined by single newlines, in this order. * * No trailing newline, no spaces, no carriage returns. `host` is the host you * REGISTERED, never the inbound `Host` header — behind a proxy or a managed * platform router that header may have been rewritten, and a verifier reading * it will then reject every valid request. */ export function canonicalString({ method, registeredHost, pathWithQuery, timestamp, correlationId, bodySha256Hex, }) { return [method, registeredHost, pathWithQuery, timestamp, correlationId, bodySha256Hex].join("\n"); } /** * Constant-time string compare. * * `timingSafeEqual` throws when the lengths differ, and the throw is itself a * length oracle, so both sides are hashed to a fixed width first. A * byte-at-a-time `===` returns faster the earlier it finds a difference, * which leaks the key one position at a time to anyone who can measure your * response. */ export function constantTimeEquals(presented, expected) { const left = createHash("sha256").update(String(presented), "utf8").digest(); const right = createHash("sha256").update(String(expected), "utf8").digest(); return timingSafeEqual(left, right); } /** The value Nexus402 requires on EVERY response, including your own errors. */ export function proof({ correlationId, timestamp, signature }) { const digest = createHash("sha256") .update([PROOF_DOMAIN, correlationId, timestamp, signature].join("\n"), "utf8") .digest("base64url"); return `sha256:${digest}`; } /** * Verifies one inbound request. * * Returns `{ ok: true, hello, proof }` — set that proof on your response * BEFORE you write the status, because once the header block is committed * anything set afterwards is dropped in silence. On failure, * `{ ok: false, reason }`. * * THE HELLO (ADR-0143). When you publish, and again when Nexus402 checks a * refusal of yours, it sends one signed POST with an EMPTY body and NO creator * key: there is no caller yet. `hello` is true for that request. Answer it * `200` with the proof and run no tool. The signature is still verified, so a * stranger cannot fake one; the key check is what is skipped, because without * that exception the hello is refused and you can never publish. */ export function verifyRequest({ headers, rawBody, method, pathWithQuery, registeredHost, creatorKey, publicKey, nowUnixSeconds = Math.floor(Date.now() / 1000), }) { const header = (name) => headers[name] ?? headers[name.toLowerCase()] ?? ""; const hello = rawBody.length === 0; if (!hello && !constantTimeEquals(header("X-Nexus-Creator-Key"), creatorKey)) { return { ok: false, reason: "creator key mismatch" }; } const timestamp = header("X-Nexus-Timestamp"); const seconds = Number(timestamp); if (!Number.isInteger(seconds)) { return { ok: false, reason: "timestamp is not an integer" }; } // BOTH directions. Without an upper bound a future-dated request is valid // forever; without a lower one a captured request replays forever. if (Math.abs(nowUnixSeconds - seconds) > SIGNATURE_WINDOW_SECONDS) { return { ok: false, reason: "timestamp outside the 60-second window" }; } const presented = header("X-Nexus-Signature"); if (!presented.startsWith("ed25519:")) { return { ok: false, reason: "signature is not ed25519:" }; } const signatureBytes = Buffer.from(presented.slice("ed25519:".length), "base64"); if (signatureBytes.length !== 64) { return { ok: false, reason: "signature is not 64 bytes" }; } const correlationId = header("X-Correlation-ID"); const message = Buffer.from( canonicalString({ method, registeredHost, pathWithQuery, timestamp, correlationId, bodySha256Hex: bodyHashHex(rawBody), }), "utf8", ); if (!verify(null, message, publicKey, signatureBytes)) { return { ok: false, reason: "signature does not verify" }; } return { ok: true, hello, proof: proof({ correlationId, timestamp, signature: presented }) }; } ``` **examples/verifiers — TypeScript** ``` // A complete Nexus402 request verifier for TypeScript. NO RUNTIME DEPENDENCIES. // // The same verifier as `../node/verify.mjs`, typed. Node 22.18 or later runs // this file directly (it strips the types), so there is no build step. // `../starters_test.go` starts the server beside it and drives it with the // gateway's REAL signer: the hello, a paid call, and forged calls. // // Two checks, and you want both. The creator key is a shared secret on your // server; if it leaks, anyone can impersonate Nexus402 to you. The signature // is asymmetric (you hold only a public key), and it binds a request to YOUR // host and to a 60-second window. The window LIMITS a replay of the same // request, it does not stop one: make your tool's side effects idempotent. import { createHash, createPublicKey, timingSafeEqual, verify, type KeyObject } from "node:crypto"; /** The fixed first line of the response proof's digested bytes. Copy exactly. */ export const PROOF_DOMAIN = "nexus-endpoint-proof-v1"; /** Must match the gateway's 60 seconds, in both directions. */ export const SIGNATURE_WINDOW_SECONDS = 60; // Ed25519 public keys arrive as 32 raw bytes in base64; createPublicKey wants // DER, and for Ed25519 the SPKI header is this fixed 12-byte prefix. const SPKI_ED25519_PREFIX = Buffer.from("302a300506032b6570032100", "hex"); export function publicKeyFromBase64(base64: string): KeyObject { const raw = Buffer.from(base64, "base64"); if (raw.length !== 32) { throw new Error(`ed25519 public key must be 32 bytes, got ${raw.length}`); } return createPublicKey({ key: Buffer.concat([SPKI_ED25519_PREFIX, raw]), format: "der", type: "spki" }); } /** Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse. */ export function bodyHashHex(rawBody: Buffer): string { return createHash("sha256").update(rawBody).digest("hex"); } /** * Six fields joined by single newlines, in this order, no trailing newline. * `registeredHost` is the host you PUBLISHED, never the inbound Host header, * which a proxy may rewrite. */ export function canonicalString( method: string, registeredHost: string, pathWithQuery: string, timestamp: string, correlationId: string, bodySha256Hex: string, ): string { // nexus:canonical-begin return [method, registeredHost, pathWithQuery, timestamp, correlationId, bodySha256Hex].join("\n"); // nexus:canonical-end } /** Constant-time compare: both sides hashed to a fixed width first. */ export function constantTimeEquals(presented: string, expected: string): boolean { const left = createHash("sha256").update(presented, "utf8").digest(); const right = createHash("sha256").update(expected, "utf8").digest(); return timingSafeEqual(left, right); } /** The value Nexus402 requires on EVERY answer to a verified request. */ export function proof(correlationId: string, timestamp: string, signature: string): string { const digest = createHash("sha256") .update([PROOF_DOMAIN, correlationId, timestamp, signature].join("\n"), "utf8") .digest("base64url"); return `sha256:${digest}`; } export type Verdict = { ok: true; hello: boolean; proof: string } | { ok: false; reason: string }; export interface InboundRequest { /** Header names in any case. */ headers: Record; rawBody: Buffer; method: string; /** The request target exactly as sent: path plus query, not re-encoded. */ pathWithQuery: string; } export interface EndpointConfig { registeredHost: string; creatorKey: string; publicKey: KeyObject; } /** * Verifies one inbound request. * * THE HELLO: when you publish, Nexus402 sends one signed POST with an EMPTY * body and NO creator key. `hello` is true for it; answer 200 with the proof * and run no tool. Its signature is still verified. */ export function verifyRequest( request: InboundRequest, config: EndpointConfig, nowUnixSeconds: number = Math.floor(Date.now() / 1000), ): Verdict { const header = (name: string): string => { const value = request.headers[name] ?? request.headers[name.toLowerCase()]; return Array.isArray(value) ? (value[0] ?? "") : (value ?? ""); }; const hello = request.rawBody.length === 0; if (!hello && !constantTimeEquals(header("X-Nexus-Creator-Key"), config.creatorKey)) { return { ok: false, reason: "creator key mismatch" }; } const timestamp = header("X-Nexus-Timestamp"); if (!/^\d+$/.test(timestamp)) { return { ok: false, reason: "timestamp is not an integer" }; } // BOTH directions: no upper bound means a future-dated request is valid // forever; no lower bound means a captured one replays forever. if (Math.abs(nowUnixSeconds - Number(timestamp)) > SIGNATURE_WINDOW_SECONDS) { return { ok: false, reason: "timestamp outside the 60-second window" }; } const presented = header("X-Nexus-Signature"); if (!presented.startsWith("ed25519:")) { return { ok: false, reason: "signature is not ed25519:" }; } const signature = Buffer.from(presented.slice("ed25519:".length), "base64"); if (signature.length !== 64) { return { ok: false, reason: "signature is not 64 bytes" }; } const correlationId = header("X-Correlation-ID"); const message = canonicalString( request.method, config.registeredHost, request.pathWithQuery, timestamp, correlationId, bodyHashHex(request.rawBody), ); if (!verify(null, Buffer.from(message, "utf8"), config.publicKey, signature)) { return { ok: false, reason: "signature does not verify" }; } return { ok: true, hello, proof: proof(correlationId, timestamp, presented) }; } ``` **examples/verifiers — Python** ``` """A Nexus402 request verifier for Python. Machine-checked: `../starters_test.go` starts `server.py`, which uses this file, and drives it with the gateway's REAL signer -- the hello, a paid call, and forged calls that must be refused. `../field_order_test.go` also reads the canonical string between the markers below. Needs: `pip install cryptography`. """ from __future__ import annotations import hashlib import hmac import time import binascii from base64 import b64decode, urlsafe_b64encode from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey # The fixed first line of the response proof's digested bytes. Copy exactly. PROOF_DOMAIN = "nexus-endpoint-proof-v1" # Must match the gateway's 60 seconds. Wider accepts older replays; narrower # rejects honest requests on ordinary clock skew. SIGNATURE_WINDOW_SECONDS = 60 def body_hash_hex(raw_body: bytes) -> str: """Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse.""" return hashlib.sha256(raw_body).hexdigest() def canonical_string( method: str, registered_host: str, path_with_query: str, timestamp: str, correlation_id: str, body_sha256_hex: str, ) -> str: """Six fields joined by single newlines. No trailing newline.""" # nexus:canonical-begin return "\n".join( [ method, registered_host, path_with_query, timestamp, correlation_id, body_sha256_hex, ] ) # nexus:canonical-end def proof(correlation_id: str, timestamp: str, signature: str) -> str: """The value Nexus402 requires on EVERY response, including your errors.""" digest = hashlib.sha256( "\n".join([PROOF_DOMAIN, correlation_id, timestamp, signature]).encode("utf-8") ).digest() return "sha256:" + urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") def verify_request( headers: dict[str, str], raw_body: bytes, method: str, path_with_query: str, registered_host: str, creator_key: str, public_key_base64: str, now_unix_seconds: int | None = None, ) -> tuple[bool, str]: """Returns (ok, proof) on success, or (False, reason).""" now = int(time.time()) if now_unix_seconds is None else now_unix_seconds # Header names are case-insensitive, and a client may send any case. lowered = {key.lower(): value for key, value in headers.items()} def header(name: str) -> str: return lowered.get(name.lower()) or "" # THE HELLO (ADR-0143): the publish check is a signed POST with an EMPTY # body and NO creator key. Answer it 200 with the proof and run no tool. # Only the key check is skipped; the signature below is still verified. hello = len(raw_body) == 0 # Constant time. A byte-at-a-time `==` returns faster the earlier it finds # a difference, leaking the key one position at a time. if not hello and not hmac.compare_digest(header("X-Nexus-Creator-Key").encode(), creator_key.encode()): return False, "creator key mismatch" timestamp = header("X-Nexus-Timestamp") # ASCII only: isdigit() accepts digits int() does not. And few enough of # them for int(), which raises on thousands. Anyone can send either. if not (timestamp.isascii() and timestamp.isdigit() and len(timestamp) <= 18): return False, "timestamp is not an integer" # BOTH directions: without an upper bound a future-dated request is valid # forever; without a lower one a captured request replays forever. if abs(now - int(timestamp)) > SIGNATURE_WINDOW_SECONDS: return False, "timestamp outside the 60-second window" presented = header("X-Nexus-Signature") if not presented.startswith("ed25519:"): return False, "signature is not ed25519:" try: signature = b64decode(presented[len("ed25519:") :], validate=True) except (binascii.Error, ValueError): return False, "signature is not base64" if len(signature) != 64: return False, "signature is not 64 bytes" correlation_id = header("X-Correlation-ID") message = canonical_string( method, registered_host, path_with_query, timestamp, correlation_id, body_hash_hex(raw_body), ).encode("utf-8") try: Ed25519PublicKey.from_public_bytes(b64decode(public_key_base64)).verify( signature, message ) except (InvalidSignature, ValueError): return False, "signature does not verify" return True, proof(correlation_id, timestamp, presented) ``` **examples/verifiers — Go** ``` package main // A complete Nexus402 request verifier for Go. Standard library only. // // `../starters_test.go` builds this kit from an empty directory and drives it // with the gateway's REAL signer: the hello, a paid call, and forged calls // that must be refused. // // Two checks, and you want both. The creator key is a shared secret on your // server; if it leaks, anyone can impersonate Nexus402 to you. The signature // is asymmetric (you hold only a public key), and it binds a request to YOUR // host and to a 60-second window. The window LIMITS a replay of the same // request, it does not stop one: make your tool's side effects idempotent. import ( "crypto/ed25519" "crypto/sha256" "crypto/subtle" "encoding/base64" "encoding/hex" "errors" "net/http" "strconv" "strings" "time" ) // ProofDomain is the fixed first line of the response proof's digested bytes. const ProofDomain = "nexus-endpoint-proof-v1" // SignatureWindow must match the gateway's 60 seconds, in both directions. const SignatureWindow = 60 * time.Second // Verdict is what a verified request concluded. type Verdict struct { // Hello is the signed, empty-body check the gateway sends when you // publish: answer it 200 with the proof and run no tool. Hello bool // Proof goes in X-Nexus-Proof on every answer to this request. Proof string } // Verifier holds what you configured. type Verifier struct { RegisteredHost string CreatorKey string PublicKeys []ed25519.PublicKey } // ParsePublicKeys reads the gateway's key list: base64, comma-separated. func ParsePublicKeys(raw string) ([]ed25519.PublicKey, error) { var keys []ed25519.PublicKey for _, part := range strings.Split(raw, ",") { decoded, err := base64.StdEncoding.DecodeString(strings.TrimSpace(part)) if err != nil || len(decoded) != ed25519.PublicKeySize { return nil, errors.New("NEXUS_PUBLIC_KEY must be base64 Ed25519 keys of 32 bytes, comma-separated") } keys = append(keys, ed25519.PublicKey(decoded)) } return keys, nil } // CanonicalString is the signed message: six fields joined by single // newlines, in this order, no trailing newline. host is the host you // PUBLISHED, never the inbound Host header, which a proxy may rewrite. func CanonicalString(method, host, pathWithQuery, timestamp, correlationID, bodySHA256Hex string) string { // nexus:canonical-begin return strings.Join([]string{method, host, pathWithQuery, timestamp, correlationID, bodySHA256Hex}, "\n") // nexus:canonical-end } // Proof is the value Nexus402 requires on every answer to a verified request. func Proof(correlationID, timestamp, signature string) string { sum := sha256.Sum256([]byte(strings.Join([]string{ProofDomain, correlationID, timestamp, signature}, "\n"))) return "sha256:" + base64.RawURLEncoding.EncodeToString(sum[:]) } // RequestTarget is the path with the query, exactly as sent. func RequestTarget(r *http.Request) string { return r.URL.RequestURI() } // Verify checks one request whose raw body has already been read. func (v Verifier) Verify(r *http.Request, body []byte, now time.Time) (Verdict, error) { hello := len(body) == 0 // Constant time: a byte-at-a-time compare leaks the key one position at // a time. The hello carries no key, so it skips only this check. presented := sha256.Sum256([]byte(r.Header.Get("X-Nexus-Creator-Key"))) expected := sha256.Sum256([]byte(v.CreatorKey)) if !hello && subtle.ConstantTimeCompare(presented[:], expected[:]) != 1 { return Verdict{}, errors.New("creator key mismatch") } timestamp := r.Header.Get("X-Nexus-Timestamp") seconds, err := strconv.ParseInt(timestamp, 10, 64) if err != nil { return Verdict{}, errors.New("timestamp is not an integer") } // BOTH directions: no upper bound means a future-dated request is valid // forever; no lower bound means a captured one replays forever. if skew := now.Sub(time.Unix(seconds, 0)); skew > SignatureWindow || skew < -SignatureWindow { return Verdict{}, errors.New("timestamp outside the 60-second window") } header := r.Header.Get("X-Nexus-Signature") encoded, found := strings.CutPrefix(header, "ed25519:") if !found { return Verdict{}, errors.New("signature lacks the ed25519 prefix") } signature, err := base64.StdEncoding.DecodeString(encoded) if err != nil || len(signature) != ed25519.SignatureSize { return Verdict{}, errors.New("signature is not 64 bytes of base64") } correlationID := r.Header.Get("X-Correlation-ID") sum := sha256.Sum256(body) message := []byte(CanonicalString(r.Method, v.RegisteredHost, RequestTarget(r), timestamp, correlationID, hex.EncodeToString(sum[:]))) // More than one key while the gateway rotates: accept any of them. for _, key := range v.PublicKeys { if ed25519.Verify(key, message, signature) { return Verdict{Hello: hello, Proof: Proof(correlationID, timestamp, header)}, nil } } return Verdict{}, errors.New("signature does not verify") } ``` **examples/verifiers — PHP** ``` $headers * @return array{0: bool, 1: string} [true, proof] or [false, reason] */ function nexus_verify_request( array $headers, string $rawBody, string $method, string $pathWithQuery, string $registeredHost, string $creatorKey, string $publicKeyBase64, ?int $nowUnixSeconds = null, ): array { $now = $nowUnixSeconds ?? time(); // Header names are case-insensitive, and a client may send any case. $lowered = array_change_key_case($headers, CASE_LOWER); $header = static function (string $name) use ($lowered): string { return (string) ($lowered[strtolower($name)] ?? ''); }; // THE HELLO (ADR-0143): the publish check is a signed POST with an EMPTY // body and NO creator key. Answer it 200 with the proof and run no tool. // Only the key check is skipped; the signature below is still verified. $hello = $rawBody === ''; // Constant time. A byte-at-a-time compare returns faster the earlier it // finds a difference, leaking the key one position at a time. if (!$hello && !hash_equals($creatorKey, $header('X-Nexus-Creator-Key'))) { return [false, 'creator key mismatch']; } $timestamp = $header('X-Nexus-Timestamp'); if (preg_match('/^\d+$/', $timestamp) !== 1) { return [false, 'timestamp is not an integer']; } // BOTH directions. Without an upper bound a future-dated request is valid // forever; without a lower one a captured request replays forever. if (abs($now - (int) $timestamp) > NEXUS_SIGNATURE_WINDOW_SECONDS) { return [false, 'timestamp outside the 60-second window']; } $presented = $header('X-Nexus-Signature'); if (!str_starts_with($presented, 'ed25519:')) { return [false, 'signature is not ed25519:']; } $signature = base64_decode(substr($presented, strlen('ed25519:')), true); if ($signature === false || strlen($signature) !== 64) { return [false, 'signature is not 64 bytes']; } $publicKey = base64_decode($publicKeyBase64, true); if ($publicKey === false || strlen($publicKey) !== 32) { return [false, 'public key is not 32 bytes']; } $correlationId = $header('X-Correlation-ID'); $message = nexus_canonical_string( $method, $registeredHost, $pathWithQuery, $timestamp, $correlationId, nexus_body_hash_hex($rawBody), ); if (!sodium_crypto_sign_verify_detached($signature, $message, $publicKey)) { return [false, 'signature does not verify']; } return [true, nexus_proof($correlationId, $timestamp, $presented)]; } ``` **examples/verifiers — Rust** ``` //! A Nexus402 request verifier for Rust. //! //! Machine-checked: `../starters_test.go` builds `main.rs`, which uses this //! file, and drives it with the gateway's REAL signer -- the hello, a paid //! call, and forged calls that must be refused. `../field_order_test.go` also //! reads the canonical string between the markers below. //! //! Needs: `ed25519-dalek`, `sha2`, `base64`, `subtle`. use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD}; use base64::Engine; use ed25519_dalek::{Signature, Verifier, VerifyingKey}; use sha2::{Digest, Sha256}; use subtle::ConstantTimeEq; /// The fixed first line of the response proof's digested bytes. Copy exactly. pub const PROOF_DOMAIN: &str = "nexus-endpoint-proof-v1"; /// Must match the gateway's 60 seconds. Wider accepts older replays; /// narrower rejects honest requests on ordinary clock skew. pub const SIGNATURE_WINDOW_SECONDS: i64 = 60; /// Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse. pub fn body_hash_hex(raw_body: &[u8]) -> String { let digest = Sha256::digest(raw_body); digest.iter().map(|byte| format!("{byte:02x}")).collect() } /// Six fields joined by single newlines. No trailing newline. pub fn canonical_string( method: &str, registered_host: &str, path_with_query: &str, timestamp: &str, correlation_id: &str, body_sha256_hex: &str, ) -> String { // nexus:canonical-begin [ method, registered_host, path_with_query, timestamp, correlation_id, body_sha256_hex, ] .join("\n") // nexus:canonical-end } /// The value Nexus402 requires on EVERY response, including your own errors. pub fn proof(correlation_id: &str, timestamp: &str, signature: &str) -> String { let message = [PROOF_DOMAIN, correlation_id, timestamp, signature].join("\n"); let digest = Sha256::digest(message.as_bytes()); format!("sha256:{}", URL_SAFE_NO_PAD.encode(digest)) } pub struct Request<'a> { pub creator_key_header: &'a str, pub signature_header: &'a str, pub timestamp_header: &'a str, pub correlation_id: &'a str, pub raw_body: &'a [u8], pub method: &'a str, pub path_with_query: &'a str, } pub struct Endpoint { pub registered_host: String, pub creator_key: String, pub public_key_base64: String, } impl Endpoint { /// `Ok(proof)` on success; `Err(reason)` otherwise. pub fn verify(&self, request: &Request<'_>, now_unix_seconds: i64) -> Result { // THE HELLO (ADR-0143): the publish check is a signed POST with an // EMPTY body and NO creator key. Answer it 200 with the proof and run // no tool. Only the key check is skipped; the signature is verified. let hello = request.raw_body.is_empty(); // Constant time: a byte-at-a-time compare returns faster the earlier // it finds a difference, leaking the key one position at a time. let presented_key = request.creator_key_header.as_bytes(); if !hello && presented_key.ct_eq(self.creator_key.as_bytes()).unwrap_u8() != 1 { return Err("creator key mismatch".into()); } // Digits only, so never a sign; `parse` refuses none and too many. // Nothing is verified yet: anyone can send any timestamp. let timestamp = request.timestamp_header; if !timestamp.bytes().all(|byte| byte.is_ascii_digit()) { return Err("timestamp is not an integer".into()); } let seconds: i64 = timestamp .parse() .map_err(|_| "timestamp is not an integer".to_string())?; // BOTH directions. Without an upper bound a future-dated request is // valid forever; without a lower one a capture replays forever. // `abs_diff` cannot overflow, as a subtraction followed by `abs` can. if now_unix_seconds.abs_diff(seconds) > SIGNATURE_WINDOW_SECONDS.unsigned_abs() { return Err("timestamp outside the 60-second window".into()); } let encoded = request .signature_header .strip_prefix("ed25519:") .ok_or("signature is not ed25519:")?; let raw = STANDARD .decode(encoded) .map_err(|_| "signature is not base64".to_string())?; let bytes: [u8; 64] = raw .try_into() .map_err(|_| "signature is not 64 bytes".to_string())?; let key_bytes: [u8; 32] = STANDARD .decode(&self.public_key_base64) .map_err(|_| "public key is not base64".to_string())? .try_into() .map_err(|_| "public key is not 32 bytes".to_string())?; let key = VerifyingKey::from_bytes(&key_bytes).map_err(|error| error.to_string())?; let message = canonical_string( request.method, &self.registered_host, request.path_with_query, request.timestamp_header, request.correlation_id, &body_hash_hex(request.raw_body), ); key.verify(message.as_bytes(), &Signature::from_bytes(&bytes)) .map_err(|_| "signature does not verify".to_string())?; Ok(proof( request.correlation_id, request.timestamp_header, request.signature_header, )) } } ``` **examples/verifiers — Java** ``` package endpoint; import java.nio.charset.StandardCharsets; import java.security.KeyFactory; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.security.Signature; import java.security.spec.X509EncodedKeySpec; import java.util.Base64; import java.util.HexFormat; import java.util.Map; /** * A complete Nexus402 request verifier for Java 17 or later. Ed25519 is in the * JDK, so this file needs no library. * *

Machine-checked: {@code ../starters_test.go} builds this kit from an empty * directory and drives it with the gateway's REAL signer -- the hello, a paid * call, and forged calls that must be refused. * *

Two checks, and you want both. The creator key is a shared secret on your * server; if it leaks, anyone can impersonate Nexus402 to you. The signature is * asymmetric (you hold only a public key), and it binds a request to YOUR host * and to a 60-second window. The window LIMITS a replay of the same request, it * does not stop one: make your tool's side effects idempotent. */ public final class Verify { /** The fixed first line of the response proof's digested bytes. Copy exactly. */ public static final String PROOF_DOMAIN = "nexus-endpoint-proof-v1"; /** Must match the gateway's 60 seconds, in both directions. */ public static final long SIGNATURE_WINDOW_SECONDS = 60; // Ed25519 keys arrive as 32 raw bytes; the JDK wants X.509 SPKI, whose // Ed25519 header is this fixed 12-byte prefix. private static final byte[] SPKI_ED25519_PREFIX = HexFormat.of().parseHex("302a300506032b6570032100"); /** {@code ok} with the proof and whether it is the hello, or a reason. */ public record Verdict(boolean ok, boolean hello, String proof, String reason) { static Verdict refused(String reason) { return new Verdict(false, false, "", reason); } } private Verify() {} /** Wraps the 32 raw bytes Nexus402 gives you into a JDK public key. */ public static PublicKey publicKeyFromBase64(String base64) throws Exception { byte[] raw = Base64.getDecoder().decode(base64.trim()); if (raw.length != 32) { throw new IllegalArgumentException("ed25519 public key must be 32 bytes, got " + raw.length); } byte[] der = new byte[SPKI_ED25519_PREFIX.length + raw.length]; System.arraycopy(SPKI_ED25519_PREFIX, 0, der, 0, SPKI_ED25519_PREFIX.length); System.arraycopy(raw, 0, der, SPKI_ED25519_PREFIX.length, raw.length); return KeyFactory.getInstance("Ed25519").generatePublic(new X509EncodedKeySpec(der)); } /** Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse. */ public static String bodyHashHex(byte[] rawBody) { return HexFormat.of().formatHex(sha256(rawBody)); } /** * Six fields joined by single newlines, in this order, no trailing newline. * {@code registeredHost} is the host you PUBLISHED, never the inbound Host * header, which a proxy may rewrite. */ public static String canonicalString( String method, String registeredHost, String pathWithQuery, String timestamp, String correlationId, String bodySha256Hex) { // nexus:canonical-begin return String.join("\n", method, registeredHost, pathWithQuery, timestamp, correlationId, bodySha256Hex); // nexus:canonical-end } /** The value Nexus402 requires on EVERY answer to a verified request. */ public static String proof(String correlationId, String timestamp, String signature) { byte[] digest = sha256(String.join("\n", PROOF_DOMAIN, correlationId, timestamp, signature).getBytes(StandardCharsets.UTF_8)); return "sha256:" + Base64.getUrlEncoder().withoutPadding().encodeToString(digest); } /** * Verifies one request. {@code headers} must be keyed by LOWERCASE name. * *

THE HELLO: when you publish, Nexus402 sends one signed POST with an EMPTY * body and NO creator key. {@code hello} is true for it; answer 200 with the * proof and run no tool. Its signature is still verified. */ public static Verdict verifyRequest( Map headers, byte[] rawBody, String method, String pathWithQuery, String registeredHost, String creatorKey, PublicKey publicKey, long nowUnixSeconds) { boolean hello = rawBody.length == 0; // Constant time: MessageDigest.isEqual does not stop at the first // difference, so it leaks nothing about where the keys differ. byte[] presentedKey = sha256(headers.getOrDefault("x-nexus-creator-key", "").getBytes(StandardCharsets.UTF_8)); byte[] expectedKey = sha256(creatorKey.getBytes(StandardCharsets.UTF_8)); if (!hello && !MessageDigest.isEqual(presentedKey, expectedKey)) { return Verdict.refused("creator key mismatch"); } String timestamp = headers.getOrDefault("x-nexus-timestamp", ""); if (!timestamp.matches("\\d{1,18}")) { return Verdict.refused("timestamp is not an integer"); } // BOTH directions: no upper bound means a future-dated request is valid // forever; no lower bound means a captured one replays forever. if (Math.abs(nowUnixSeconds - Long.parseLong(timestamp)) > SIGNATURE_WINDOW_SECONDS) { return Verdict.refused("timestamp outside the 60-second window"); } String presented = headers.getOrDefault("x-nexus-signature", ""); if (!presented.startsWith("ed25519:")) { return Verdict.refused("signature is not ed25519:"); } byte[] signature; try { signature = Base64.getDecoder().decode(presented.substring("ed25519:".length())); } catch (IllegalArgumentException notBase64) { return Verdict.refused("signature is not base64"); } if (signature.length != 64) { return Verdict.refused("signature is not 64 bytes"); } String correlationId = headers.getOrDefault("x-correlation-id", ""); String message = canonicalString(method, registeredHost, pathWithQuery, timestamp, correlationId, bodyHashHex(rawBody)); try { Signature verifier = Signature.getInstance("Ed25519"); verifier.initVerify(publicKey); verifier.update(message.getBytes(StandardCharsets.UTF_8)); if (!verifier.verify(signature)) { return Verdict.refused("signature does not verify"); } } catch (Exception invalid) { return Verdict.refused("signature does not verify"); } return new Verdict(true, hello, proof(correlationId, timestamp, presented), ""); } private static byte[] sha256(byte[] bytes) { try { return MessageDigest.getInstance("SHA-256").digest(bytes); } catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); } } } ``` **examples/verifiers — C# / .NET** ``` // A complete Nexus402 request verifier for C# / .NET 8 or later. // // .NET has no built-in Ed25519, so this uses BouncyCastle.Cryptography for // that one check; SHA-256 and the constant-time compare are in the runtime. // `../starters_test.go` builds this kit from an empty directory and drives it // with the gateway's REAL signer -- the hello, a paid call, and forged calls // that must be refused. // // Two checks, and you want both. The creator key is a shared secret on your // server; if it leaks, anyone can impersonate Nexus402 to you. The signature // is asymmetric (you hold only a public key), and it binds a request to YOUR // host and to a 60-second window. The window LIMITS a replay of the same // request, it does not stop one: make your tool's side effects idempotent. using System.Security.Cryptography; using System.Text; using Org.BouncyCastle.Crypto.Parameters; using Org.BouncyCastle.Crypto.Signers; namespace NexusEndpoint; ///

Ok with the proof and whether it is the hello, or a reason. public sealed record Verdict(bool Ok, bool Hello, string Proof, string Reason) { public static Verdict Refused(string reason) => new(false, false, "", reason); } public static class Verify { /// The fixed first line of the response proof's digested bytes. Copy exactly. public const string ProofDomain = "nexus-endpoint-proof-v1"; /// Must match the gateway's 60 seconds, in both directions. public const long SignatureWindowSeconds = 60; /// Reads the 32 raw bytes Nexus402 gives you, base64. public static Ed25519PublicKeyParameters PublicKeyFromBase64(string base64) { var raw = Convert.FromBase64String(base64.Trim()); if (raw.Length != 32) { throw new ArgumentException($"ed25519 public key must be 32 bytes, got {raw.Length}"); } return new Ed25519PublicKeyParameters(raw, 0); } /// Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse. public static string BodyHashHex(byte[] rawBody) => Convert.ToHexString(SHA256.HashData(rawBody)).ToLowerInvariant(); /// /// Six fields joined by single newlines, in this order, no trailing newline. /// registeredHost is the host you PUBLISHED, never the inbound Host header, /// which a proxy may rewrite. /// public static string CanonicalString( string method, string registeredHost, string pathWithQuery, string timestamp, string correlationId, string bodySha256Hex) { // nexus:canonical-begin return string.Join("\n", method, registeredHost, pathWithQuery, timestamp, correlationId, bodySha256Hex); // nexus:canonical-end } /// The value Nexus402 requires on EVERY answer to a verified request. public static string Proof(string correlationId, string timestamp, string signature) { var digest = SHA256.HashData(Encoding.UTF8.GetBytes(string.Join("\n", ProofDomain, correlationId, timestamp, signature))); return "sha256:" + Convert.ToBase64String(digest).TrimEnd('=').Replace('+', '-').Replace('/', '_'); } /// /// Verifies one request. THE HELLO: when you publish, Nexus402 sends one /// signed POST with an EMPTY body and NO creator key. Hello is true for it; /// answer 200 with the proof and run no tool. Its signature is still verified. /// public static Verdict VerifyRequest( Func header, byte[] rawBody, string method, string pathWithQuery, string registeredHost, string creatorKey, Ed25519PublicKeyParameters publicKey, long nowUnixSeconds) { var hello = rawBody.Length == 0; // Constant time: FixedTimeEquals does not stop at the first difference. var presentedKey = SHA256.HashData(Encoding.UTF8.GetBytes(header("X-Nexus-Creator-Key"))); var expectedKey = SHA256.HashData(Encoding.UTF8.GetBytes(creatorKey)); if (!hello && !CryptographicOperations.FixedTimeEquals(presentedKey, expectedKey)) { return Verdict.Refused("creator key mismatch"); } var timestamp = header("X-Nexus-Timestamp"); if (timestamp.Length == 0 || timestamp.Length > 18 || !timestamp.All(char.IsAsciiDigit)) { return Verdict.Refused("timestamp is not an integer"); } // BOTH directions: no upper bound means a future-dated request is valid // forever; no lower bound means a captured one replays forever. if (Math.Abs(nowUnixSeconds - long.Parse(timestamp)) > SignatureWindowSeconds) { return Verdict.Refused("timestamp outside the 60-second window"); } var presented = header("X-Nexus-Signature"); if (!presented.StartsWith("ed25519:", StringComparison.Ordinal)) { return Verdict.Refused("signature is not ed25519:"); } byte[] signature; try { signature = Convert.FromBase64String(presented["ed25519:".Length..]); } catch (FormatException) { return Verdict.Refused("signature is not base64"); } if (signature.Length != 64) { return Verdict.Refused("signature is not 64 bytes"); } var correlationId = header("X-Correlation-ID"); var message = Encoding.UTF8.GetBytes( CanonicalString(method, registeredHost, pathWithQuery, timestamp, correlationId, BodyHashHex(rawBody))); var verifier = new Ed25519Signer(); verifier.Init(false, publicKey); verifier.BlockUpdate(message, 0, message.Length); if (!verifier.VerifySignature(signature)) { return Verdict.Refused("signature does not verify"); } return new Verdict(true, hello, Proof(correlationId, timestamp, presented), ""); } } ``` **examples/verifiers — Ruby** ``` # frozen_string_literal: true # A complete Nexus402 request verifier for Ruby 3.1 or later. # # Ed25519 comes from Ruby's own OpenSSL (openssl gem 3.0, OpenSSL 1.1.1 or # later), so this file # needs no gem. `../starters_test.go` serves `server.rb`, which uses this file, # and drives it with the gateway's REAL signer -- the hello, a paid call, and # forged calls that must be refused. # # Two checks, and you want both. The creator key is a shared secret on your # server; if it leaks, anyone can impersonate Nexus402 to you. The signature # is asymmetric (you hold only a public key), and it binds a request to YOUR # host and to a 60-second window. The window LIMITS a replay of the same # request, it does not stop one: make your tool's side effects idempotent. require "digest" require "openssl" module NexusVerify # The fixed first line of the response proof's digested bytes. Copy exactly. PROOF_DOMAIN = "nexus-endpoint-proof-v1" # Must match the gateway's 60 seconds, in both directions. SIGNATURE_WINDOW_SECONDS = 60 # Ed25519 keys arrive as 32 raw bytes; OpenSSL wants DER SPKI, whose Ed25519 # header is this fixed 12-byte prefix. SPKI_ED25519_PREFIX = ["302a300506032b6570032100"].pack("H*") Verdict = Struct.new(:ok, :hello, :proof, :reason, keyword_init: true) module_function # Wraps the 32 raw bytes Nexus402 gives you into an OpenSSL key. def public_key_from_base64(base64) raw = base64.strip.unpack1("m0") raise ArgumentError, "ed25519 public key must be 32 bytes, got #{raw.bytesize}" unless raw.bytesize == 32 OpenSSL::PKey.read(SPKI_ED25519_PREFIX + raw) end # Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse. def body_hash_hex(raw_body) Digest::SHA256.hexdigest(raw_body) end # Six fields joined by single newlines, in this order, no trailing newline. # registered_host is the host you PUBLISHED, never the inbound Host header, # which a proxy may rewrite. def canonical_string(method, registered_host, path_with_query, timestamp, correlation_id, body_sha256_hex) # nexus:canonical-begin [method, registered_host, path_with_query, timestamp, correlation_id, body_sha256_hex].join("\n") # nexus:canonical-end end # The value Nexus402 requires on EVERY answer to a verified request. def proof(correlation_id, timestamp, signature) digest = Digest::SHA256.digest([PROOF_DOMAIN, correlation_id, timestamp, signature].join("\n")) # base64url without padding. "sha256:#{[digest].pack("m0").tr("+/", "-_").delete("=")}" end # Verifies one request. `header` is a lambda taking a header name, in any case. # # THE HELLO: when you publish, Nexus402 sends one signed POST with an EMPTY # body and NO creator key. `hello` is true for it; answer 200 with the proof # and run no tool. Its signature is still verified. def verify_request(header:, raw_body:, method:, path_with_query:, registered_host:, creator_key:, public_key:, now_unix_seconds: Time.now.to_i) hello = raw_body.empty? # Constant time: secure_compare does not stop at the first difference. presented_key = Digest::SHA256.digest(header.call("X-Nexus-Creator-Key").to_s) expected_key = Digest::SHA256.digest(creator_key) if !hello && !OpenSSL.fixed_length_secure_compare(presented_key, expected_key) return Verdict.new(ok: false, reason: "creator key mismatch") end timestamp = header.call("X-Nexus-Timestamp").to_s return Verdict.new(ok: false, reason: "timestamp is not an integer") unless timestamp.match?(/\A\d{1,18}\z/) # BOTH directions: no upper bound means a future-dated request is valid # forever; no lower bound means a captured one replays forever. if (now_unix_seconds - timestamp.to_i).abs > SIGNATURE_WINDOW_SECONDS return Verdict.new(ok: false, reason: "timestamp outside the 60-second window") end presented = header.call("X-Nexus-Signature").to_s return Verdict.new(ok: false, reason: "signature is not ed25519:") unless presented.start_with?("ed25519:") begin signature = presented.delete_prefix("ed25519:").unpack1("m0") rescue ArgumentError return Verdict.new(ok: false, reason: "signature is not base64") end return Verdict.new(ok: false, reason: "signature is not 64 bytes") unless signature.bytesize == 64 correlation_id = header.call("X-Correlation-ID").to_s message = canonical_string(method, registered_host, path_with_query, timestamp, correlation_id, body_hash_hex(raw_body)) verified = begin public_key.verify(nil, signature, message) rescue OpenSSL::PKey::PKeyError false end return Verdict.new(ok: false, reason: "signature does not verify") unless verified Verdict.new(ok: true, hello: hello, proof: proof(correlation_id, timestamp, presented)) end end ``` --- # A published version is immutable > Price, endpoint and schema are frozen at publish. Here is why, and how to ship a change. Source: https://www.nexus402.dev/docs/creators/versions/ A published version is frozen. Price, endpoint and input schema cannot be edited after publish — not by you, not by us, not by an operator. > **This is enforced by the database, not by a policy** > > A trigger refuses the update. It is not a check someone can forget to run, and there is no administrative override, because an override is a thing that gets used. ## Why A developer who pinned `acme/payments@v1/charge` made a decision about cost and behaviour. If you could change the price of that version, their spend would change without their consent; if you could change the endpoint, their traffic would move without their knowledge. Immutability is what makes a pinned version a promise rather than a suggestion. ## How to change anything Publish a new version. **Shipping a change** ```text v1 price 50000 endpoint https://old.acme.example/mcp <- stays exactly as published v2 price 75000 endpoint https://new.acme.example/mcp <- the change acme/payments/charge resolves to v2 (unpinned: highest published) acme/payments@v1/charge resolves to v1 (pinned: unchanged until retired) ``` The pin goes on the MCP server segment: `acme/payments@v1/charge`, not after the tool name. Developers who pinned `v1` keep the behaviour and price they chose. Developers who did not pin get `v2` once the gateway picks up the next registry sync, normally within a minute. There is no migration to run, because nothing anyone depends on has changed. The one thing that waits is a large price rise. ### A large price rise waits seven days for unpinned callers Stock MCP clients cannot pin, so an unpinned caller would otherwise pay whatever the newest version costs. A version priced at **more than twice the lowest price unpinned callers paid at any point in the last seven days** is therefore held from unpinned callers for **seven days**; they keep reaching the current version meanwhile. Developers who pin the new version reach it as soon as it is callable. The publish answer tells you when this applies: `unpinned_from` is the time unpinned callers start reaching it, and `price_notice` says the same in words. A price can therefore at most double per notice period for unpinned callers, however many versions you publish. ## Retiring a version Retiring marks a version as no longer offered. It stops appearing in the catalog and stops being the answer to an unpinned name. - **A retired version is not deleted.** Its history, its earnings and its journal rows remain. - **Re-publishing restores it** rather than creating a duplicate, so a retire is reversible — if you submit the same price, endpoint and currency it was published with. A different price or endpoint is refused for that version and ships as a new one. - **A version an operator removed is the exception.** Re-publishing it is refused with `publish_blocked_by_operator`; the reason is on your tools page, and only an operator can re-list it. - **The name is never released.** Retiring a version does not free the handle or the tool name for anyone else. > **Retiring stops every call to that version, pinned or not** > > Once the gateway picks up the next registry sync, a call that names a retired version answers `404 Unknown_Version` and charges nothing. Unpinned callers move to the highest remaining `PUBLISHED` version; developers who pinned the retired one are refused until they change their pin. Retire a version only when you are ready for that. --- # When calls do not arrive > How to tell a quiet week from a broken deployment, and what happens if you stay broken. Source: https://www.nexus402.dev/docs/creators/endpoint-health/ The hardest failure to debug is the one that looks like nothing. If calls stop arriving, you cannot tell from your own logs whether nobody wanted your tool this week or whether every request has been failing for three days. So we show you. ## Where to look Your **Tools** page lists every version you have published, and each one carries an **Endpoint** column. It has four states, and they are four different facts rather than four degrees of one. | State | What it means | What to do | | --- | --- | --- | | **Answering** | The last call reached you and you delivered it. The timestamp is when. | Nothing. | | **Never called** | No call has ever reached this version. That is *not* the same as working — nothing has tested it. | Check that the version is `PUBLISHED` and that your endpoint URL is right. Call it yourself first. | | **Failing** | That many calls in a row were your endpoint's fault. The count resets to zero when a settlement batch (five minutes) passes with calls and no fault. | Fix the endpoint. Traffic is still being routed to you. | | **De-listed** | After repeated failures we removed the version from the public catalog. It receives **no calls at all**. | Re-publish, once your endpoint answers. Submitting the same version with the *same* price, endpoint and currency restores it; a changed price or endpoint ships as a new version. | You do not have to keep checking. An [alert](https://www.nexus402.dev/docs/developers/alerts/) sends `endpoint.failing` when a version starts failing and `version.delisted` when it is de-listed, to a signed webhook of yours or to a Slack or Discord channel. > **Fixing your server is not enough on its own** > > Repairing the endpoint does not re-list the version, because we have no way to learn that you did — nothing is routed to a de-listed endpoint, so nothing can discover that it works again. **You have to tell us, by publishing.** > > Submitting the *same* version again, with the same price, endpoint and currency, restores it and resets its failure count to zero. Only those three are compared; the description and schema you send are ignored, and the version keeps the ones it was published with. That is not a loophole in immutability: nothing about the version changed, so only its status moves. If the fix changed your price or your endpoint, that is a new version instead. A version an operator removed is not restored this way. > > The reset is deliberate and goes both ways. A restored version that kept its old run of failures would be de-listed again on the next sweep, which would look like the restore silently failing; and clearing the status without clearing the record would make the version permanently immune to de-listing — published again and never examined a second time, however often it failed. ## What counts as a failure A failure is a call the gateway attributes to your endpoint. In practice that is one of: - a connection that could not be made, or TLS that did not complete; - no first byte within five seconds — the clock is on your *first* byte, not on finishing, so a slow stream is fine and a slow start is not; - any `5xx`, with or without the proof; - a response without a valid `X-Nexus-Proof` — a `2xx`, a `4xx` or a redirect — but **only if our own [hello](https://www.nexus402.dev/docs/creators/verifying/#hello) to your endpoint fails too**. A `4xx` that carries the proof **never counts**: it is your deliberate rejection of a caller, and a caller could otherwise de-list you with twenty bad requests. A proof-less `2xx` is never a sale, though, whether or not it counts here: the developer gets a `502` and you are not paid. See [the proof](https://www.nexus402.dev/docs/creators/verifying/#proof). ## What it costs you > **Nothing, and that is the point** > > A call that fails before any byte reaches the developer is **refunded to them and never earns you anything**. There is no penalty, no fee and no deduction — the charge is simply voided, as if it had not happened. See [when you earn](https://www.nexus402.dev/docs/creators/settlement/). > > So this page is about *lost traffic*, not lost money. We deliberately do not show you a “you could have earned” figure: it would be a number about a payment that was correctly never owed, and the only thing it could start is an argument. Once bytes have streamed, the charge stands even if your stream then breaks. The work was done and partly delivered, so the failure count will not move for that call. ## What we do not tell you **We record that a call failed, not why.** The gateway knows whether it got no first byte, or a connection error, or an unrelayable response — and we keep only the fact of the failure and its time. We would rather say so than imply a diagnosis we do not have. The count is also *consecutive* failures. It answers “is my endpoint broken right now”, and it deliberately does not answer “how many calls did I lose this month” — one success resets it to zero. If your endpoint is flapping, the count will look healthy between flaps; the *last delivered* timestamp is the more honest signal there. ## A checklist when it says Failing 1. **Call your own endpoint** from somewhere that is not your machine, over HTTPS, with a real certificate. A certificate your laptop trusts and nothing else is the most common cause. 2. **Check the first byte.** If you do work before writing anything, write a header or a keep-alive first. Five seconds of silence is a failure however fast the rest is. 3. **Check the creator key version.** If you rotated and deployed only the new key, calls carrying the previous one are refused by your own server, and the gateway can send the previous key for up to 30 seconds after a rotation. A proof-less `401` like that is *not* counted here while your hello still passes — so those calls are lost without the count moving. Accept both keys through the overlap window. See [verifying a request](https://www.nexus402.dev/docs/creators/verifying/#key). 4. **Check the registered host.** Signature verification uses the host you registered, not the `Host` header that arrived. Behind a proxy those differ, and verifying against the inbound one works in testing and fails in production. 5. **Compare against a starter kit.** Each is built and tested in our CI against the gateway's real signing code, so it is a known-good baseline rather than a sample. See [the starter kits](https://www.nexus402.dev/docs/creators/build-a-server/#starters). ## Verified badges on your profile Your public creator page can show up to three verified badges. Each one states one fact we checked, from records we already hold, and is checked again every time the page is read: a badge appears when its fact holds and disappears when it stops holding. Every creator who meets one shows it; nobody applies for them and nobody can buy them. | Badge | What we checked | | --- | --- | | **Domain verified** | Every live version's endpoint host served the `/.well-known/nexus402-challenge/` file we fetched before you first published at that host. A host you first published at before that check existed (9 November 2026) does not count, because no check ran for it. | | **Identity verified by Stripe** | Your Stripe Connect payout account has finished onboarding and Stripe reports payouts enabled. Stripe ran the checks; we hold none of the details. See [payouts](https://www.nexus402.dev/docs/creators/payouts/). | | **Healthy endpoint** | Every live version is **Answering** (above), and each of your live tools succeeded on at least 99% of at least 50 calls over the last 30 days, counting only failures at your endpoint and leaving out calls you paid for yourself. A version never called yet withholds it. | > **What a badge does not mean** > > None of these badges says a tool is safe, good, or endorsed by Nexus402. They do not describe what your tool does with a request. “Healthy endpoint” sits beside each tool's own 30-day numbers rather than replacing them, and the numbers remain the measure. > **Payouts** > > Endpoint health decides whether calls reach you, not whether you can withdraw what they earned. Payouts are live through Stripe Connect, with a cap on the total paid each UTC day — see [payouts](https://www.nexus402.dev/docs/creators/payouts/). --- # When you earn > A call settles when it completes, we owe you the published price less our margin (10% by default, falling as your lifetime sales grow), and the first byte is the boundary. Source: https://www.nexus402.dev/docs/creators/settlement/ A call that completes settles to your payable balance. We sell the call at the published price and owe you that price less our 10% margin. ## When a call earns | What happened | Do you earn? | | --- | --- | | Your endpoint returned a `2xx` with a valid `X-Nexus-Proof` | **Yes**, the published price less our 10% margin | | Your endpoint returned a `2xx` without a valid proof | **No.** It is not a sale: the developer gets `502` and is not charged. See [the proof](https://www.nexus402.dev/docs/creators/verifying/#proof) | | The call was one of your [free calls](https://www.nexus402.dev/docs/creators/build-a-server/publish/#free-calls) | **No.** Nobody is charged, so there is nothing to share. It reaches your endpoint like a paid call and is counted on your dashboard | | You failed before any byte reached the developer | **No.** They are refunded automatically | | You failed after the first byte reached them | **Yes.** They received part of the work and you did it | | The developer's wallet was empty | **No.** The call never reached you — they got a 402 | | The developer cancelled mid-stream | **Yes.** A client hanging up is not your failure | | Our infrastructure failed to authorize the call | **No.** The call never reached you and nobody was charged | > **The boundary is the first byte, and it is not arbitrary** > > Before the first byte, nothing of value has been delivered and a refund costs nobody anything. After it, the work has been done and partially delivered — refunding then would make every long-running tool unprofitable to offer, because a client that disconnects late would undo the whole call. ## When you can withdraw it What a call earns is owed at once but becomes withdrawable in stages, because a developer's card payment can be disputed for months after it settles. The rules, each a fixed term of the Creator Agreement: - **Your creator hold** starts at **14 days** from each earning. Every **7** consecutive days without a counted chargeback shortens it by one day, down to a floor of **2 days**; each counted chargeback adds a day back and restarts that clock. - **Recent and new money waits longer.** An earning paid from a developer top-up less than 14 days old, or from a developer account less than 30 days old, is held until those pass. - **A 5% reserve.** Once an earning is released, 5% of it stays held until 120 days after it settled. - **New creators are capped.** For your first nine weeks you can withdraw at most **$500.00 in any 7 days**; the excess waits for the window to move. - **Disputes.** While a dispute over a top-up that paid for your calls is open, the linked share is reserved. If it is lost and the top-up was paid less than **120 days** before the dispute opened, that share is clawed back from what we owe you; a debt it leaves is repaid from later earnings before anything is withdrawable. `GET /v1/creator/money?handle=acme`, with your handle, shows all of it: `payable_micro`, `withdrawable_micro`, `held_micro`, `dispute_reserved_micro` and `debt_micro`, every held part with its `reason` and `release_at`, your current hold and when it next shortens, and every dispute and debt movement. The app reads the same figures. ## How it is recorded Every charge becomes a double-entry row in a ledger that is append-only: database triggers refuse updates and deletes. A correction is a new entry, never an edit. Charges are batched into five-minute rollups rather than written one row per call. What we owe you therefore appears within a few minutes rather than instantly, and the figure you see is the sum of settled rollups. ## Our 10% margin We buy the right to route each call from you and resell it at the published price. For a completed call we owe you that price less our margin, 10% by default or lower on [the creator ladder](#ladder), truncated toward zero in integer micro-USD. The margin is ours on our own sale — it is never taken out of money of yours that we hold — so the figure you are shown is the wholesale total we owe you and does not itemise it. ## The creator ladder Our margin falls as your **lifetime paid sales** grow, and never below 8% by this rule. Lifetime paid sales are the prices developers paid for your paid calls, on all your tools, since you started, less refunds, voids and what chargebacks took back. Free calls and trial credit are not sales, and calls your own account makes to your own tools do not count. The rungs today: Loading the current rungs… - **A rung is yours for good.** We count your sales once a day; when they reach a rung, your margin is at most that rung's rate from the next five-minute boundary at least ten minutes later. Later refunds never take it back, and you never move back up. - **You pay the lower rate.** If you already pay less under an agreement with us, or during a [founding](https://www.nexus402.dev/founding/) or promotional period, you keep the lower one; when such a period ends, your rung applies if it is lower than the rate it returns to. - **A change to the rungs only ever lowers anyone.** A rung you have reached stands even if we later make it harder to reach. The Earnings page in the app shows your rung and how far you are from the next. We email you when you reach one. The **withdrawal** fee is separate and is borne by you, deducted from the amount you withdraw. It is quoted before you confirm. See [payouts](https://www.nexus402.dev/docs/creators/payouts/). --- # Payouts > Connect Stripe, the $5 minimum, the fee you bear, and the daily cap. Source: https://www.nexus402.dev/docs/creators/payouts/ > **How payouts are sent** > > Payouts go through Stripe Connect. Nexus402 is the merchant of record under Stripe. The total paid out to all creators each UTC day is capped, so on a busy day your withdrawal may wait until the next day. It is never failed because of the cap. Earnings accrue whether or not you have connected a payout account. Connecting one is only needed to withdraw. ## Connecting Stripe 1. Start onboarding from your creator page. We create a Stripe Express account and hand you a link. 2. Complete Stripe's onboarding. They collect and hold your bank details — **we never see or store them.** We hold a reference and the capability flags Stripe reports. 3. Confirm the destination with the code we email you. Until that code is confirmed, the destination cannot be used. > **Why a destination needs an emailed code** > > Changing where money is sent is the single most valuable action an attacker could take with a hijacked session. A step-up code means a stolen session alone is not enough — they would also need your inbox. ## Where we can pay The payout form lists the countries this platform can pay, and only those. The list comes from Stripe and depends on the country the platform itself is registered in: today that is **the United States only**. That is narrower than Stripe's general country list, and the reason is the kind of account we open for you. It can receive transfers and nothing else, and Stripe does not allow that kind of account outside the platform's own country — we checked, and Stripe refused to create one in India, Brazil, the UK, Germany and Canada. If your country is not listed, payouts are not available to you yet, and we tell you before you onboard rather than at your first withdrawal. There is no other payout method. **Supported payout countries:** - United States ## Requesting a withdrawal - **Each withdrawal needs its own emailed code**, bound to that amount: a code requested for $5.00 cannot authorize anything else, and it works once. The email never states the amount. - The minimum is **$5.00**, enforced at the request, at execution and by the database. - You can withdraw only what is **withdrawable now**. Recent earnings are held for a while and a small reserve longer; [when you can withdraw it](https://www.nexus402.dev/docs/creators/settlement/#holds) has the rules, and the amount is re-checked at execution. - The **withdrawal fee is yours** and is deducted from the amount: currently 3% of the amount plus $0.40. It is quoted before you confirm, and if it changes you are shown the new fee before your next withdrawal. - **One withdrawal at a time** per creator. A second request while one is in flight is refused rather than queued. - A request **records an intent and moves nothing.** Execution is a separate, gated step. - To hear when it is paid, add an [alert](https://www.nexus402.dev/docs/developers/alerts/) for `withdrawal.paid`: a signed webhook carries the amount, the fee and what you received; Slack and Discord say only that it was paid. ## What protects the money The parts worth knowing, because they explain why a withdrawal can be refused for reasons that look opaque: - The amount is **re-derived from the ledger** at execution, never taken from the request and never from a cache. A disagreement between the cache and the ledger refuses the withdrawal outright. - The payout destination is **re-read** at execution, because a Stripe capability can be withdrawn between your request and the transfer. - A transfer is **idempotent and, on a retry, retrieved rather than recreated** — so a repair after a crash cannot pay you twice. - Transferring is the only irreversible direction in this system, which is why it has more gates than anything else here. ## Your handle stays yours A creator handle is never transferred to another account, and neither are its earnings or its payout destination. A handle has exactly one owner for its lifetime, because a session that could hand a handle to someone else could hand them its money too.