🦀Toolkit Rust
Audience: Nexus toolkit integrators (Rust).
Area: Toolkit Rust public API.
Generated from: Nexus SDK Toolkit public API at annotated tag v2.2.0, peeled commit c996eda4f125989cbec4f1cdc5d5e5235a558167 (generated inventory preserved below).
This page documents the public Rust surface that the Nexus Toolkit exports for tool authors and runtime integrators. The items are grouped by source file and listed in declaration order.
toolkit-rust/src/lib.rs
AnyResult
pub type AnyResult = anyhow::Result;Convenience result alias re-exported by the toolkit crate.
env_logger
pub use env_logger;Re-export of the logging initialization crate used by the toolkit runtime.
debug
pub use log::debug;Logging macro re-export for toolkit and tool runtime code.
warp
pub use warp;HTTP framework re-export used by the toolkit runtime and bootstrap macro.
StatusCode
HTTP status code type used throughout the toolkit runtime and tool trait helpers.
toolkit-rust/src/nexus_tool.rs
AuthContext
Authenticated request context available to Tools when signed HTTP is required. It contains the Leader capability ID, Leader key ID, canonical input hash, Leader signature, deterministic nonce, and verified context timestamp after request authentication.
NexusTool
Trait implemented by a Nexus tool service.
Input
The input payload type for the tool.
Off-chain input schemas must describe object properties. A schema with "type": "object" and omitted properties, or with an empty "properties": {} map, declares zero input ports; non-object property schemas are rejected. Invocation requests carry resolved values in the JSON ports envelope. That envelope and raw body bytes are not signed; in Required mode, the Toolkit reconstructs and verifies the canonical schema-ordered input commitment before invoking the Tool.
Output
The output payload type for the tool.
fqn
Returns the fully qualified tool name used by the runtime and metadata endpoint.
timeout
Returns the tool timeout, which defaults to 10 seconds.
invoke
Runs the tool for a single invocation request.
encode_output
The default implementation retains inline JSON output encoding. Override this hook to return explicit protocol ports with OffchainToolOutput::from_ports; it does not upload data automatically.
authorize
Optional policy hook that runs after signed HTTP authentication and before invocation.
health
Returns the health status used by GET /health.
path
Returns the relative HTTP path for the tool, defaulting to the web root.
description
Returns the human-readable description surfaced in metadata. Implementations must provide meaningful text: SDK registration rejects an empty or whitespace-only description.
new
Constructs a tool instance, usually so dependencies can be injected for tests.
meta
Builds the metadata JSON used by GET /meta.
toolkit-rust/src/config.rs
ENV_TOOLKIT_CONFIG_PATH
Environment variable that points the runtime at its JSON config file.
TLS runtime selection
When both nonempty TLS credential paths are configured, bootstrap! terminates TLS in the Toolkit runtime. It explicitly selects the Rustls ring provider before building the server configuration so another provider enabled by a Tool dependency cannot make provider selection ambiguous. The runtime serves plain HTTP only when both TLS variables are absent; a missing, empty, or unmatched certificate/key path is a startup configuration error. An external HTTPS gateway can connect to this supported plain-HTTP mode, but that does not meet the documented operator profile, which requires HTTPS on both the public and gateway-to-Toolkit hops. Set both NEXUS_TOOL_TLS_CERT_PATH and NEXUS_TOOL_TLS_KEY_PATH to terminate the upstream TLS connection in Toolkit. GET /meta always advertises an external HTTPS URL and ignores X-Forwarded-Proto; it does not prove that the active listener is TLS-protected. Client-certificate binding requires TLS termination in Toolkit or certificate passthrough so the runtime can compare the TLS peer key with the allowlisted Leader key; forwarded certificate headers do not establish that peer key.
SignedHttpMode
Signed HTTP policy for the toolkit runtime.
Disabled
Do not require signature headers.
Required
Reject requests that are missing or fail signature verification.
ToolkitRuntimeConfig
Validated runtime config for the toolkit HTTP server.
from_env
Loads config from ENV_TOOLKIT_CONFIG_PATH when set, otherwise uses runtime defaults.
from_path
Parses config from a JSON file on disk.
from_json_bytes
Parses config from JSON bytes.
from_json_str
Parses config from a JSON string.
invoke_max_body_bytes
Returns the maximum allowed /invoke request body size.
signed_http_is_required
Returns whether the runtime requires signed HTTP requests.
has_tool
Returns whether signed HTTP configuration contains an entry for the Tool id. The entry may omit response-signing material.
Toolkit JSON contract
ToolkitRuntimeConfig has no top-level config version and uses optional per-Tool response_signing_key. Keep this exact JSON shape consistent across config, tests, and verification examples.
ToolkitRuntimeConfig reads one strict JSON object. Unknown fields fail parsing.
invoke_max_body_bytes
Optional request-body limit in bytes; defaults to 12 MiB. /invoke requires Content-Length within the limit.
signed_http.mode
disabled or required; omission inside the section defaults to required. Omitting the whole section disables signed HTTP.
signed_http.allowed_leaders_path
Path to a v3 AllowedLeadersFileV1 JSON file. A relative path resolves from the Toolkit process working directory, not from the config file. A file-backed resolver refreshes this path during key lookup and retains the prior allowlist if a refresh fails.
signed_http.allowed_leaders
Inline alternative with { "version": 1, "leaders": [...] }. Use one allowlist source; when both are present, inline data is selected.
signed_http.tools
Nonempty map from exact Tool FQN to its runtime signing configuration.
response_signing_key
Optional 32-byte Ed25519 private key encoded as hex, base64, base64url, or Sui’s 33-byte base64 form with a leading zero flag. When present, the Toolkit signs successful canonical Tool result BCS; RegisteredKey result evidence requires it. The zero key above is test material only.
require_client_certificate
Optional per-Tool TLS peer-key check; defaults to false. When enabled, the peer certificate key must match the allowlisted Leader key.
context_timestamp_window_ms
Optional symmetric Unix-millisecond freshness window for the signed Tool context; defaults to 30,000 ms. The inclusive window is checked before replay-cache access.
replay_cache_ttl_ms
Optional positive completed-entry lifetime; defaults to 300,000 ms.
Set the config path before bootstrap! starts:
There is no Tool KID or external replay-store field. Tool identity selects the active on-chain Tool key. Replay state is process-local memory keyed by deterministic nonce and canonical input hash: in-flight reuse is rejected, an exact completed retry returns cached canonical bytes, and completed entries expire after the configured TTL.
In Required, the Toolkit verifies the Leader signature over the schema-ordered canonical input hash and reconstructs that hash from the resolved body before invocation. A separate Leader context signature binds the receiving Tool FQN, invocation nonce, and Unix-millisecond timestamp; the Toolkit checks it against the allowlist and applies the inclusive freshness window before replay-cache access. When response_signing_key is configured, the Toolkit signs successful canonical result BCS; without that key, request authentication still applies but the response carries no Tool signature. A signed response can still encode a semantic Tool err variant; consumers must decode the canonical result and distinguish ok from err. The Tool signature retains the existing v3 response domain, Leader signature, deterministic nonce, and domain-separated response hash. The context signature does not cover HTTP method, path, query, raw JSON, status, or arbitrary headers; authenticated HTTPS protects those fields and plaintext transport.
The request headers are X-Nexus-Sig-V, X-Nexus-Leader-Id, X-Nexus-Leader-Key-Id, X-Nexus-Input-Hash, X-Nexus-Leader-Signature, X-Nexus-Nonce, nexus-context-sig, and nexus-context-timestamp. The signature-version header value remains 3; the context signature is the v3.1 protocol addition. A signed canonical response carries only X-Nexus-Sig-V and X-Nexus-Tool-Signature.
Gateways must forward every listed request and response header without renaming or dropping it, including nexus-context-sig and nexus-context-timestamp. The documented operator profile requires HTTPS on both the public and gateway-to-Toolkit hops; set both Toolkit TLS paths for direct TLS. When require_client_certificate is enabled, TLS must terminate in Toolkit or pass through to it; forwarded certificate headers do not identify a TLS peer.
toolkit-rust/src/serde_tracked.rs
WithSerdeErrorPath
Transparent wrapper that preserves serde error paths while serializing and deserializing the inner value.
toolkit-rust/src/runtime.rs
bootstrap!
Macro that loads toolkit configuration, serves GET /health, GET /meta, and POST /invoke, and supports --meta for printing tool metadata without starting the server.
Explicit output encoding and failure boundaries
A Tool can upload a result with nexus_walrus::WalrusStorage and return StoredBlob::nexus_data() in an explicit output port. Complete the upload inside the invocation before returning; choose a timeout that covers it and persist registration/recovery state when cancellation or restart must be recoverable. The operator supplies storage payment and retention policy. The Leader downloads and validates the reference; it does not upload or own the Blob.
Here Output::Ok.result is a NexusData produced by the upload. Annotate its schema for the decoded downstream value, such as #[schemars(with = "String")] for a string. The runtime validates explicit ports against metadata and signs the canonical reference. Match port order to metadata order. See Walrus storage for dependencies and durable upload phases.
Inputs and outputs each have an independent 8 MiB resolved-byte budget per invocation. Inline bytes, downloaded values, every Many item, and 32 bytes per object ID count toward the relevant budget. The default 12 MiB HTTP request limit accommodates base64 and metadata; explicit invoke_max_body_bytes settings are retained and do not raise the resolved-data budget. Published Move inline limits and signed response limits still apply, so large outputs require explicit upload.
Small canonical JSON retains the existing transport. Large or formatting-sensitive values use base64 bytes transport to preserve the authenticated digest; the receiving runtime verifies that commitment before JSON decoding. Upgrade receiving runtimes before sending values that require this form.
With panic = "unwind", the runtime contains panics during input decoding, Tool construction, authorization, invocation, and output encoding. Internal failures return a sanitized HTTP 500 without a Tool result signature or panic payload; they are not successful protocol outputs. panic = "abort" still terminates the process. Exceeding NexusTool::timeout() returns unsigned HTTP 504; the default Tool timeout is 10 seconds. A Blob already uploaded before failure remains paid and owned; follow the post-upload failure procedure before retrying or cleaning up. Validate failure behavior and the next request in local tests.
Last updated

