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    fn timeout() -> Duration {
66        Duration::from_secs(10)
67    }
68    /// Invokes the tool with the given input. It is an asynchronous function
69    /// that returns the output of the tool.
70    ///
71    /// It is used to generate the `/invoke` endpoint.
72    fn invoke(&self, input: Self::Input) -> impl Future<Output = Self::Output> + Send;
73
74    /// Authorize an invocation after it has been authenticated via signed HTTP.
75    ///
76    /// This is an optional ergonomic hook for tool developers to implement their
77    /// own admission policy (allowlists, rate-limits, task gating, etc).
78    ///
79    /// Default: allow.
80    ///
81    /// # Example
82    /// ```ignore
83    /// async fn authorize(&self, ctx: AuthContext) -> AnyResult<()> {
84    ///     // Example policy: only allow a specific LeaderId.
85    ///     if ctx.invoker_id != "0x1111" {
86    ///         anyhow::bail!("leader not allowed");
87    ///     }
88    ///     Ok(())
89    /// }
90    /// ```
91    fn authorize(&self, _ctx: AuthContext) -> impl Future<Output = AnyResult<()>> + Send {
92        async { Ok(()) }
93    }
94    /// Returns the health status of the tool. For now, this only returns an
95    /// HTTP status code.
96    ///
97    /// TODO: <https://github.com/Talus-Network/nexus-sdk/issues/7>
98    ///
99    /// It is used to generate the `/health` endpoint.
100    fn health(&self) -> impl Future<Output = AnyResult<StatusCode>> + Send;
101    /// Returns the relative path on a webserver that the tool resides on. This
102    /// defaults to an empty path (root URL). But can be overridden by the
103    /// implementor.
104    fn path() -> &'static str {
105        ""
106    }
107    /// Returns a concise description of the Tool's observable behavior.
108    ///
109    /// This value is part of the durable registry metadata that users and
110    /// Agent developers rely on when selecting a Tool. Implementations must
111    /// provide meaningful text. SDK registration rejects blank descriptions.
112    fn description() -> &'static str;
113    /// Construct a new instance of the tool. This is mainly here so that
114    /// dependencies can be injected for testing purposes.
115    fn new() -> impl Future<Output = Self> + Send;
116    /// Returns the metadata of the tool. It includes the domain, name, version,
117    /// input schema, and output schema.
118    ///
119    /// It is used to generate the `/meta` endpoint.
120    fn meta(url: Url) -> Value {
121        let fqn = Self::fqn();
122        let url = url.to_string();
123        let timeout = Self::timeout().as_millis() as u64;
124        let description = Self::description();
125        let input_schema = schemars::schema_for!(Self::Input);
126        let output_schema = schemars::schema_for!(Self::Output);
127
128        json!(
129            {
130                "fqn": fqn,
131                "url": url,
132                "timeout": timeout,
133                "description": description,
134                "input_schema": input_schema,
135                "output_schema": output_schema,
136            }
137        )
138    }
139}