# 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=<base64>                # 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=<base64>                # 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=<base64>                # 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<string, unknown>): 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<Buffer> {
  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<string, unknown> } {
  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<string, unknown>) : {};
  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<string, string | string[] | undefined>;
  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=<base64>                # 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=<base64>                # 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=<base64>                # 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
<?php

declare(strict_types=1);

/**
 * A complete Nexus402 creator endpoint for PHP. NO PACKAGES: sodium has been
 * bundled with PHP since 7.2.
 *
 * Put `verify.php` beside this file, set four environment variables, route
 * every request to this file behind HTTPS, and publish its URL. Locally:
 * `php -S 127.0.0.1:8080 index.php`, and ONLY locally: PHP's development server
 * reads a whole body into memory before this file runs, so one request can
 * stop it. In production use PHP-FPM behind a web server that limits a body
 * to 10 MiB (nginx: `client_max_body_size 10m;`) and how long it may take to
 * arrive. `../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.
 *
 *   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 __DIR__ . '/verify.php';

// The gateway's own cap on a request body. Anything larger did not come from it.
const MAX_BODY_BYTES = 10 * 1024 * 1024;

/**
 * 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.
 *
 * @param array<string, mixed> $args
 * @return array{0: int, 1: array<string, mixed>}
 */
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<string, mixed>|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
<?php

declare(strict_types=1);

/**
 * A Nexus402 request verifier for PHP.
 *
 * Machine-checked: `../starters_test.go` serves `index.php`, 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 NO third-party package: `sodium` has been bundled with PHP since
 * 7.2. If `sodium_crypto_sign_verify_detached` is missing, your build was
 * compiled without it, or the extension is not enabled in php.ini.
 */

/** The fixed first line of the response proof's digested bytes. Copy exactly. */
const NEXUS_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.
 */
const NEXUS_SIGNATURE_WINDOW_SECONDS = 60;

/** Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse. */
function nexus_body_hash_hex(string $rawBody): string
{
    return hash('sha256', $rawBody);
}

/** Six fields joined by single newlines. No trailing newline. */
function nexus_canonical_string(
    string $method,
    string $registeredHost,
    string $pathWithQuery,
    string $timestamp,
    string $correlationId,
    string $bodySha256Hex,
): string {
    // nexus:canonical-begin
    return implode("\n", [
        $method,
        $registeredHost,
        $pathWithQuery,
        $timestamp,
        $correlationId,
        $bodySha256Hex,
    ]);
    // nexus:canonical-end
}

/** The value Nexus402 requires on EVERY response, including your own errors. */
function nexus_proof(string $correlationId, string $timestamp, string $signature): string
{
    $message = implode("\n", [NEXUS_PROOF_DOMAIN, $correlationId, $timestamp, $signature]);
    $digest = hash('sha256', $message, true);

    // base64url without padding.
    return 'sha256:' . rtrim(strtr(base64_encode($digest), '+/', '-_'), '=');
}

/**
 * @param array<string, string> $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=<base64>                # 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<Full<Bytes>>;

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<Vec<u8>, 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<Incoming>, 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::<Value>(&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<Vec<Endpoint>>) {
    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<Endpoint> = 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<String, String> {
        // 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=<base64>                # 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.
 *
 * <p>{@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.
 *
 * <p>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.
 *
 * <pre>
 *   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)
 * </pre>
 */
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}).
   *
   * <p>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<PublicKey> publicKeys;

  private Server(String registeredHost, String creatorKey, List<PublicKey> 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<PublicKey> 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<String, String> 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.
 *
 * <p>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.
 *
 * <p>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.
   *
   * <p>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<String, String> 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
<?xml version="1.0" encoding="UTF-8"?>
<!-- The Nexus402 creator endpoint for Java. `mvn -q package` builds one
     runnable jar, target/nexus-endpoint.jar, with Jackson inside it. -->
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>example</groupId>
  <artifactId>nexus-endpoint</artifactId>
  <version>0.1.0</version>
  <packaging>jar</packaging>

  <properties>
    <maven.compiler.release>17</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.21.7</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>nexus-endpoint</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.13.0</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>3.6.0</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals><goal>shade</goal></goals>
            <configuration>
              <createDependencyReducedPom>false</createDependencyReducedPom>
              <transformers>
                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                  <mainClass>endpoint.Server</mainClass>
                </transformer>
              </transformers>
            </configuration>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
</project>
```

**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=<base64>                # 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<IHttpRequestFeature>()?.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;

/// <summary>Ok with the proof and whether it is the hello, or a reason.</summary>
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
{
    /// <summary>The fixed first line of the response proof's digested bytes. Copy exactly.</summary>
    public const string ProofDomain = "nexus-endpoint-proof-v1";

    /// <summary>Must match the gateway's 60 seconds, in both directions.</summary>
    public const long SignatureWindowSeconds = 60;

    /// <summary>Reads the 32 raw bytes Nexus402 gives you, base64.</summary>
    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);
    }

    /// <summary>Lowercase hex SHA-256 of the RAW body bytes, before any JSON parse.</summary>
    public static string BodyHashHex(byte[] rawBody) => Convert.ToHexString(SHA256.HashData(rawBody)).ToLowerInvariant();

    /// <summary>
    /// 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.
    /// </summary>
    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
    }

    /// <summary>The value Nexus402 requires on EVERY answer to a verified request.</summary>
    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('/', '_');
    }

    /// <summary>
    /// 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.
    /// </summary>
    public static Verdict VerifyRequest(
        Func<string, string> 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
<!-- The Nexus402 creator endpoint for .NET. `dotnet run -c Release`. -->
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>net8.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <RootNamespace>NexusEndpoint</RootNamespace>
    <InvariantGlobalization>true</InvariantGlobalization>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="BouncyCastle.Cryptography" Version="2.6.2" />
  </ItemGroup>
</Project>
```

**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=<base64>                # 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.
