🌐Build an Off-Chain Tool
An off-chain tool is an HTTP service that the Nexus runtime invokes during a workflow execution. It is where you wrap an external API, run an LLM, or do any computation the chain cannot perform directly. By the end of this guide you will have a working tool that returns a crypto spot price, and you will understand how a tool is scaffolded, run, validated, registered, invoked, and versioned.
The architecture figure separates the Tool's HTTP boundary from the on-chain workflow: the Toolkit owns schema and transport encoding, the Leader sends one resolved vertex request, and only the canonical result/evidence becomes durable workflow state. Keep provider credentials inside the off-chain runtime; the chain stores the registered contract and submitted evidence, not the secret.
For a tool that mutates on-chain state or moves assets, build an on-chain tool instead. To make the verification path explicit, see Verify an off-chain tool result.
Prerequisites
A Bash/POSIX-compatible shell plus
jq,curl, and coreutils-compatiblesha256sum,stat, andmktempfor the documented checks. Node.js 18 or later is needed only for the hosted Nexus API tutorial or its React example.Verify the shell tools with the Developer Setup check before using the commands below.
A working Rust toolchain and the Nexus CLI on your
PATH.A configured Nexus environment pointing at your target network (localnet, testnet, or mainnet). Confirm it with
nexus conf; the full CLI surface is in the CLI reference.Complete Developer Setup's protected-signer gate before using this registration/mutation path. Without provider-approved protected import and
nexus conf set --helpverification, stop at query-only SDK/Explorer/API inspection and do not run Nexus mutation commands.After that gate is complete, configure a signer SUI address balance for default CLI transaction/reserve funding; verify with
nexus gas balanceand fund it withnexus gas deposit. Supply an owned SUI gas coin only when the command explicitly accepts a gas-coin flag.An owned
Coin<US>for Tool collateral before registration. The required amount is network/deployment-specific; obtain it through the supported wallet/operator path and inspect the owned coin plus the Tool registration requirement before signing. The priority-fee vault guide documents the owned-coin/readback boundary; do not invent an acquisition command or substitute address-balance SUI.Network access for the first dependency acquisition, or a complete Cargo registry/Git cache that can satisfy the graph after this project's manifest and lockfile exist.
How an off-chain tool works
The sequence is the end-to-end contract behind the later code: readiness and metadata are checked before invocation, provider work stays off chain, and the workflow—not the HTTP response alone—decides whether the result advances the DAG or enters a failure/recovery path.
Your tool implements the NexusTool trait from the Nexus toolkit. The toolkit runtime turns that implementation into an HTTP server exposing three endpoints:
GET /health— liveness and readiness of the tool and its dependencies.GET /meta— the tool's metadata: FQN, input schema, output schema, timeout.POST /invoke— runs the tool's logic against one input and returns one output.
The runtime calls these endpoints; you never call /invoke by hand in production. The state flow at a tool vertex is:
The leader gathers the vertex's resolved input ports in the Tool schema's declared order and computes their canonical commitment.
It sends
POST /invoke; when a Leader signing key is configured, it signs that canonical input hash and includes the execution-derived nonce in v3 headers.The Toolkit checks the signed canonical hash when signed HTTP is required, invokes your Rust
Output, and encodes the selected variant and named ports as exact ordered BCS.The leader decodes that canonical result and submits it with the evidence required by the vertex, where its ports become values for downstream edges.
So the variant you return selects which downstream edges fire, and the ports in that variant become the values flowing along those edges.
The FQN and metadata model
Every tool is identified by a fully qualified name (FQN) of the shape domain.name@version, for example xyz.taluslabs.exchanges.coinbase.spot-price@1. The rules the parser enforces:
Splitting by
.yields at least three parts; the first parts joined form the domain, and the final part before@is the name.Each part matches
[a-z][a-z0-9_-]+— lowercase, at least two characters, and never starting with a digit,-, or_.The version is a positive integer;
0is rejected.
The fqn! macro validates the string at compile time, so a malformed FQN fails to build rather than failing at registration.
Everything the network needs to discover and call your tool lives in its metadata, served from GET /meta:
fqn
The tool's fully qualified name.
url
The base URL the runtime invokes.
description
Human-readable summary.
timeout
How long the runtime waits for /invoke (milliseconds on the wire).
input_schema
JSON Schema (draft 2020-12) generated from your Input.
output_schema
JSON Schema generated from your Output enum.
The toolkit derives both schemas from your Rust types — you never write JSON Schema by hand.
Step 1 — Scaffold the project
Create a new Rust tool project with the CLI:
This generates a buildable project: a Cargo.toml with the default Nexus dependencies and a src/main.rs with a template NexusTool implementation and a bootstrap! call. Add your own README when the Tool needs operator or deployment instructions.
Our example calls an external HTTP API, so add the two dependencies the template does not ship with under its existing [dependencies] table; do not create a second table. Edit Cargo.toml:
The v2.1.1 Rust scaffold source template emits nexus-sdk = "2.1.1" and nexus-toolkit = "2.1.1". Replace those generated version requirements with the exact registry dependencies below before creating or reviewing the lockfile so the guide, SDK, and Toolkit use one implementation.
Step 1a — Generate and acquire the locked dependency graph
The scaffold's nexus-sdk, nexus-toolkit, and external HTTP dependencies resolve from crates.io. Create or review Cargo.lock only after the scaffold and every dependency edit are complete: keep a supplied, reviewed lockfile; otherwise run cargo generate-lockfile from the project directory.
--locked prevents Cargo from changing Cargo.lock; it does not make dependency acquisition network-free. After a successful locked fetch, a disconnected environment can reuse the same cache with:
Offline mode works only when the exact registry packages and checksums required by this project's Cargo.lock are already cached. If lock generation or cargo fetch --locked fails because a registry, proxy, or credential is unavailable, fix that network/cache boundary or provide a complete matching cache/vendor directory, rerun the locked fetch, and only then use offline checks; do not report an offline build as successful after Cargo says a dependency is missing.
After the locked check, run the complete published five-test module from Step 5 with cargo test --locked from the consumer Tool directory. Toolkit integration and TLS tests are separate: a consumer manifest cannot select a dependency package with -p nexus-toolkit, so clone the pinned public SDK repository and run those tests from that source directory.
Step 1b — Verify the v2.1.1 SDK source
The consumer Tool and the SDK source are two different Cargo contexts. The consumer test proves the five Tool tests against the exact lockfile; the public SDK source proves Toolkit behavior and the TLS stalled-handshake regression. Ensure its registry/Git dependencies can be fetched, and run these commands from the selected public source directory:
The public SDK source needs the normal Rust toolchain, Cargo registry/Git access for the first fetch, and the selected revision's lockfile/cache; use a writable CARGO_HOME when the default cache is read-only. Do not run the -p nexus-toolkit commands from the generated consumer Tool directory.
Step 2 — Design the input and output schemas
The tool's input and output types are its interface: each Input field becomes an input port, and each Output enum variant becomes an output variant whose fields become output ports.
Conventions worth calling out:
InputderivesDeserializeandJsonSchema.#[serde(deny_unknown_fields)]rejects malformed inputs early.Outputmust be anenumso the generated schema has a top-leveloneOf; the toolkit runtime enforces this. DeriveSerializeandJsonSchema, and use#[serde(rename_all = "snake_case")]so variants serialize asok/err.Name error variants with an
errprefix. Nexus treatserr-prefixed variants specially and always forwards their ports on-chain, so downstream vertices can branch on the failure.Keep ports flat and stable — return
errrather than anokwith optional fields when you cannot produce the requested data.
Step 3 — Implement the NexusTool trait
The interesting method is invoke: it performs the outbound request and maps both success and failure onto output variants. Keep the production Coinbase URL behind a constructor seam so tests can inject a deterministic local upstream without changing the Tool schema or FQN.
with_base_url is the deterministic transport seam: production new() always defaults to Coinbase, while tests point the same request construction and response parser at a local listener. The client-wide three-second timeout bounds both /health and /invoke. Here /health is dependency readiness, not process-only liveness: it probes Coinbase's BTC-USD spot-price route and returns 503 for a non-success response or a transport error through the Toolkit's health error path.
The trait carries defaults you rarely override: timeout() defaults to 10 seconds and path() to the root URL. Implement description() with useful non-empty text: the SDK rejects an empty or whitespace-only description at registration. The optional authorize hook runs after signed HTTP authentication and lets you apply Tool-side policy such as caller allowlisting or rate limiting. Returning an error yields a local JSON 403; local HTTP errors are not signed verifier evidence.
Step 4 — Bootstrap the server
Start the HTTP server with the bootstrap! macro:
bootstrap!(SpotPrice) serves the tool on 127.0.0.1:8080. The macro is flexible:
If you call bootstrap!(SpotPrice) without an address, set the bind address at runtime via the BIND_ADDR environment variable.
The top of the generated src/main.rs already imports everything you need:
Step 5 — Test the tool
The scaffold already includes tokio = { version = "1", features = ["full"] }, so no unverified mock crate or extra dev dependency is needed. Add this complete module at the end of src/main.rs. It starts a one-request local HTTP server, asserts the exact path, and covers readiness, success, a bad-pair error response, and an unreachable endpoint without calling Coinbase:
Run the tests before starting the server:
Step 6 — Run and validate
Build and start the tool:
With the server running, validate it with the CLI. Validation checks that GET /health returns 200, that GET /meta is valid JSON, and that the output schema has the required top-level oneOf:
Step 7 — Keep localhost local
Do not register http://localhost:8080. Local HTTP is only for development validation; the Nexus leader transport accepts HTTPS Tool URLs. Configure signed HTTP, deploy the Tool behind its final HTTPS endpoint, and register that reachable URL in Step 9.
Step 8 — Configure signed HTTP v3
Signed HTTP v3 authenticates canonical Tool commitments; it does not replace HTTPS. The Leader signs only the schema-ordered canonical input hash. The Tool signs the response-domain message containing that Leader signature, the deterministic execution/walk/runtime-vertex/iteration nonce, and the domain-separated SHA-256 of canonical response BCS.
The Toolkit has only Disabled and Required modes. If NEXUS_TOOLKIT_CONFIG_PATH is unset, or signed_http is absent/disabled, the runtime accepts unsigned requests and produces no Tool signature. Required needs an allowed-Leader source and a nonempty Tool configuration. Add response_signing_key only for a Tool that uses the RegisteredKey/signed-result path; request authentication can operate without response-signing material.
First export the active Leader keys that this Tool may trust:
Use repeated --leader <LEADER_CAP_ID> instead of --all to restrict callers. For continuous refresh, run this as a separate process:
The generated Toolkit config reference defines this JSON shape: there is no top-level version field, and each Tool entry uses optional response_signing_key. This RegisteredKey path requires that key so the Toolkit can sign canonical result BCS. The all-zero key is test material only. Do not write a real-key copy to $PWD/toolkit-config.json or any other working-tree path; use the protected temporary flow below instead:
invoke_max_body_bytes defaults to 12 MiB in Toolkit 2.1.1; explicit configured values are preserved. The input set and output set each have a separate 8 MiB resolved-data budget. For larger-than-inline results, upload with the native adapter and use explicit output encoding; the Toolkit does not upload automatically. Instead of allowed_leaders_path, allowed_leaders may contain the active v3 allowlist schema inline: { "version": 1, "leaders": [...] }. A file path is resolved from the Toolkit process working directory, not from the config file; on refresh failure, the resolver retains the previously loaded allowlist. The tools map is keyed by exact FQN. replay_cache_ttl_ms controls completed response entries and defaults to five minutes.
There is no Tool kid field and no external replay-store field. The Tool identity used by workflow selects the active Tool key on-chain. Replay entries are process-local memory keyed by deterministic nonce and canonical input hash; in-flight reuse returns 409 request_in_flight, an exact completed retry returns cached canonical bytes, and a completed entry expires after its TTL.
For a real key, read from an operator-supplied protected secret-store path and build only a disposable config outside the repository. The persistent secret store remains under the operator's own rotation and access policy; this trap removes only the temporary config and key copy used by the demo. Require mode 0600 on the source and temporary key, mode 0600 on the config, and mode 0700 on the temporary directory:
The cleanup handler attempts removal on normal exit, interruption, or termination and reports any remaining file or directory. It cannot guarantee cleanup after an uncatchable kill, host crash, or filesystem failure; inspect the temporary directory and remove it manually when the handler could not run. A persistent service must receive its mode-0600 config through its protected secret manager or mount, outside the repository, with a service-specific key rotation and stop procedure; do not reuse this disposable demo directory as the persistent store.
For the key-registration, Tool verifier-support, DAG mode, readback, and negative-evidence steps, continue with Verify an off-chain Tool result.
Step 9 — Deploy for production
Terminate TLS directly in the Toolkit with both NEXUS_TOOL_TLS_CERT_PATH and NEXUS_TOOL_TLS_KEY_PATH, or use a gateway that provides authenticated HTTPS on both the public and gateway-to-Tool hops.
Nexus leaders accept only HTTPS Tool URLs, use TLS 1.2 or newer, follow no redirects, and bypass configured proxies.
Forward every v3 request header (
X-Nexus-Sig-V,X-Nexus-Leader-Id,X-Nexus-Leader-Key-Id,X-Nexus-Input-Hash,X-Nexus-Leader-Signature, andX-Nexus-Nonce) and both response headers (X-Nexus-Sig-VandX-Nexus-Tool-Signature). Preserve the request's semantic input. Raw method/path/query/body bytes are not signed, so HTTPS protects them in transit while the Toolkit recomputes the canonical input hash.Keep Tool and Leader signing keys secret. V3 replay resistance uses the deterministic invocation nonce and process-local replay cache, not host-clock validity claims.
Configure private IPv4 destinations only through the leader's explicit verified-Tool CIDR policy; signed HTTP never makes plaintext HTTP safe.
Validate the deployed endpoint, then register its final HTTPS URL:
Registration returns a Tool object plus separate CloneableOwnerCap<OverTool> and CloneableOwnerCap<OverToolCashier> capabilities. It locks an owned Coin<US> as registration collateral (the CLI selects one unless --collateral-coin is supplied), stores the Tool record, and saves the returned capability IDs unless --no-save is used; the SUI gas source that submits the transaction is separate. After the Tool is unregistered and its configured collateral lock has elapsed, nexus tool claim-collateral --tool-fqn "$TOOL_FQN" --owner-cap <OVER_TOOL_CAP_ID> reclaims the locked $US through the OverTool capability. That is collateral recovery, not SUI gas or Tool earnings. Use --from-meta <FILE|-> only when the reviewed metadata describes the same final HTTPS endpoint; it skips live endpoint validation.
The CLI exposes nexus tool cashier collect-invocations for finalized Invocation receipts and nexus tool cashier collect-deposits for generic CashierDeposit objects. Prove each command through selected-build help, generated bindings, matching package IDs, tests, and transaction effects; do not substitute claim-collateral for either collection path.
Step 10 — Version your tool
The @version suffix in the FQN is how Nexus tracks breaking changes:
Changing the input or output schema is a breaking change. Adding a required input port, removing an output port, renaming a variant, or changing a type all change the contract DAGs depend on. Bump the version — publish the new behavior as
…@2while…@1stays registered and callable.Non-contract changes (a bug fix in
invoke, faster code, a new upstream endpoint returning the same shape) can be redeployed under the same FQN.
Because old versions stay in the registry, existing DAGs that pin …@1 keep working when you ship …@2.
Step 11 — Use the tool in a workflow
Once registered, reference the tool from a DAG by its FQN with the off_chain variant:
The price vertex's ok variant exposes the amount, base, and currency output ports, which you wire into downstream Tools via edges. The registered_key field is valid only after the Tool advertises RegisteredKey support; remove the field or use "none" for the unsigned local-only path. To run and settle a full workflow, see Execute and settle an agent.
Verification checklist
You have built a complete off-chain tool when you can:
run the tool locally (
cargo run) and get200fromnexus tool validate offchain --url …;register its metadata (
nexus tool register offchain …) without an authorization error;fetch it back by FQN (
nexus tool inspect --tool-fqn …);parse and launch an exact Toolkit JSON file through
NEXUS_TOOLKIT_CONFIG_PATH;configure RegisteredKey support and reference it as an
off_chainvertex with"verifier":"registered_key";prove unsigned and tampered evidence are rejected, then inspect the accepted on-chain result.
Common failure modes
FQN mismatch / tool not found
The FQN in fqn! differs from the one registered or referenced in the DAG. They must match exactly, version included.
Schema mismatch / input rejected
The DAG supplies ports that do not match input_schema, or the response does not match output_schema. Re-check with nexus tool inspect.
Signature verification failure
Leader/key ID is not allowlisted, an active key changed, canonical evidence differs, or a proxy stripped v3 headers.
Unsupported output type
The output is not an enum (no top-level oneOf), or a port serializes to a shape Nexus cannot carry. Keep ports flat and JSON-scalar where possible.
Registration rejected
The Tool metadata/schema is invalid, the selected Coin<US> collateral is missing or insufficient, or the SUI gas source cannot pay.
Stale tool registration
You changed the schema without bumping the version. Register a new @version.
For insufficient payment, fund the relevant TaskPaymentReserve or ExecutionPayment for the Tool cost; signer SUI address balance remains separate transaction custody.
Next guides
Build an on-chain tool — the Move counterpart that mutates on-chain state.
Verify an off-chain tool result — make the verification path explicit.
Execute and settle an agent — run this tool inside a full workflow.
Last updated

