Skip to main content

nexus_toolkit/
nexus_tool.rs

1//! See <https://github.com/Talus-Network/gitbook-docs/blob/production/nexus-sdk/toolkit-rust.md>
2
3use {
4    anyhow::Result as AnyResult,
5    nexus_sdk::ToolFqn,
6    reqwest::Url,
7    schemars::JsonSchema,
8    serde::{de::DeserializeOwned, Serialize},
9    serde_json::{json, Value},
10    std::{future::Future, time::Duration},
11    warp::http::StatusCode,
12};
13
14/// Authenticated request context available to tools when signed HTTP is enabled.
15///
16/// This context is produced by the toolkit runtime after it has:
17/// - verified the Leader signature over the supplied canonical input hash, and
18/// - reserved the request nonce in the Tool's offchain replay cache.
19///
20/// Tools can use this context inside [`NexusTool::authorize`] to implement their own
21/// admission policy (allowlists, task gating, rate-limits, etc) without any on-chain reads.
22///
23/// Terminology:
24/// - Invoker: the node calling the tool (in Nexus, the Leader).
25/// - Responder: the node serving the request (in Nexus, the Tool).
26pub type AuthContext = nexus_sdk::signed_http::v3::wire::AuthenticatedRequest;
27
28/// This trait defines the interface for a Nexus Tool. It forces implementation
29/// of the following methods:
30///
31/// - `fqn`: Returns the tool fully qualified name.
32/// - `invoke`: Invokes the tool with the given input.
33/// - `health`: Returns the health status of the tool.
34///
35/// And the following associated types:
36///
37/// - `Input`: The input type of the tool.
38/// - `Output`: The output type of the tool.
39///
40/// Based on the provided methods and associated types, the trait automatically
41/// generates the following endpoints:
42///
43/// - `GET /health`: Returns the health status of the tool.
44/// - `GET /meta`: Returns the metadata of the tool.
45/// - `POST /invoke`: Invokes the tool with the given input.
46///
47/// The metadata of the tool includes the domain, name, version, input schema,
48/// and output schema.
49pub trait NexusTool: Send + Sync + 'static {
50    /// The input type of the tool. It must implement `JsonSchema` and
51    /// `DeserializeOwned`. It is used to generate the input schema of the tool.
52    /// It is also used to deserialize the input payload.
53    type Input: JsonSchema + DeserializeOwned + Send;
54    /// The output type of the tool. It must implement `JsonSchema` and
55    /// `Serialize`. It is used to generate the output schema of the tool. It is
56    /// also used to serialize the output payload.
57    ///
58    /// **Important:** The output type must be a Rust `enum` so that a top-level
59    /// `oneOf` is generated. This is to adhere to Nexus' output variants. This
60    /// fact is validated by the CLI.
61    type Output: JsonSchema + Serialize + Send;
62    /// Returns the FQN of the Tool.
63    fn fqn() -> ToolFqn;
64    /// Returns the Tool timeout duration. Defaults to 10 seconds.
65    ///
66    /// The runtime applies this deadline to input decoding, construction,
67    /// authorization, invocation, and output serialization. Expiry returns an
68    /// unsigned HTTP 504 response.
69    ///
70    /// Cancellation cannot preempt synchronous work or undo external side effects.
71    fn timeout() -> Duration {
72        Duration::from_secs(10)
73    }
74    /// Invokes the tool with the given input. It is an asynchronous function
75    /// that returns the output of the tool.
76    ///
77    /// It is used to generate the `/invoke` endpoint.
78    fn invoke(&self, input: Self::Input) -> impl Future<Output = Self::Output> + Send;
79
80    /// Encodes output ports before the runtime validates and signs them.
81    /// Override this when an invocation uploads data through the SDK and returns
82    /// explicit Walrus values. Storage policy and wallet authority belong to the
83    /// tool operator; the toolkit does not upload data automatically.
84    fn encode_output(output: Self::Output) -> AnyResult<nexus_sdk::types::OffchainToolOutput> {
85        nexus_sdk::types::OffchainToolOutput::from_json(serde_json::to_value(
86            crate::WithSerdeErrorPath(output),
87        )?)
88    }
89
90    /// Authorize an invocation after it has been authenticated via signed HTTP.
91    ///
92    /// This is an optional ergonomic hook for tool developers to implement their
93    /// own admission policy (allowlists, rate-limits, task gating, etc).
94    ///
95    /// Default: allow.
96    ///
97    /// # Example
98    /// ```ignore
99    /// async fn authorize(&self, ctx: AuthContext) -> AnyResult<()> {
100    ///     // Example policy: only allow a specific LeaderId.
101    ///     if ctx.invoker_id != "0x1111" {
102    ///         anyhow::bail!("leader not allowed");
103    ///     }
104    ///     Ok(())
105    /// }
106    /// ```
107    fn authorize(&self, _ctx: AuthContext) -> impl Future<Output = AnyResult<()>> + Send {
108        async { Ok(()) }
109    }
110    /// Returns the health status of the tool. For now, this only returns an
111    /// HTTP status code.
112    ///
113    /// TODO: <https://github.com/Talus-Network/nexus-sdk/issues/7>
114    ///
115    /// It is used to generate the `/health` endpoint.
116    fn health(&self) -> impl Future<Output = AnyResult<StatusCode>> + Send;
117    /// Returns the relative path on a webserver that the tool resides on. This
118    /// defaults to an empty path (root URL). But can be overridden by the
119    /// implementor.
120    fn path() -> &'static str {
121        ""
122    }
123    /// Returns a concise description of the Tool's observable behavior.
124    ///
125    /// This value is part of the durable registry metadata that users and
126    /// Agent developers rely on when selecting a Tool. Implementations must
127    /// provide meaningful text. SDK registration rejects blank descriptions.
128    fn description() -> &'static str;
129    /// Construct a new instance of the tool. This is mainly here so that
130    /// dependencies can be injected for testing purposes.
131    fn new() -> impl Future<Output = Self> + Send;
132    /// Returns the metadata of the tool. It includes the domain, name, version,
133    /// input schema, and output schema.
134    ///
135    /// It is used to generate the `/meta` endpoint.
136    fn meta(url: Url) -> Value {
137        let fqn = Self::fqn();
138        let url = url.to_string();
139        let timeout = Self::timeout().as_millis() as u64;
140        let description = Self::description();
141        let input_schema = schemars::schema_for!(Self::Input);
142        let output_schema = schemars::schema_for!(Self::Output);
143
144        json!(
145            {
146                "fqn": fqn,
147                "url": url,
148                "timeout": timeout,
149                "description": description,
150                "input_schema": input_schema,
151                "output_schema": output_schema,
152            }
153        )
154    }
155}