Skip to main content

gadk_openapi/
toolset.rs

1// Copyright 2026 Chris Olson
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! The OpenAPI toolset ([`OpenApiToolset`]).
16
17use std::any::Any;
18use std::fmt;
19use std::sync::Arc;
20
21use gadk_agent::tool::{Tool, ToolPredicate, Toolset};
22use gadk_agent::{ReadonlyContext, ToolError};
23use serde_json::Value;
24use url::Url;
25
26use crate::config::OpenApiConfig;
27use crate::error::Error;
28use crate::operation::{self, MAX_NAME_BYTES, SkippedOperation};
29use crate::spec::OpenApiSpec;
30use crate::tool::{RestApiTool, Shared};
31
32/// The operations of one OpenAPI document as a [`Toolset`] named `openapi_toolset`: one tool
33/// per operation, in document order.
34///
35/// Each tool's declaration lists the operation's path, query and header parameters and, for an
36/// `application/json` request body, `body`. A call returns `{"status": <u16>, "body": <body>}`
37/// for any HTTP status, plus `"truncated": true` when the body was cut. Redirects are not
38/// followed: a 3xx response is returned as a result like any other status.
39pub struct OpenApiToolset {
40    tools: Vec<RestApiTool>,
41    skipped: Vec<SkippedOperation>,
42    prefix: String,
43    tool_filter: Option<ToolPredicate>,
44}
45
46impl OpenApiToolset {
47    /// Builds every tool of `spec` once.
48    ///
49    /// Fails with [`Error::DuplicateName`] when two operations (or two properties of one tool)
50    /// share a name, [`Error::NameTooLong`] when a prefixed name is over 64 bytes,
51    /// [`Error::Ref`] for a `$ref` that cannot be resolved, [`Error::NoBaseUrl`] when there
52    /// is no absolute base URL (or it has a query or fragment), and [`Error::HttpClient`] when
53    /// the HTTP client cannot be built.
54    pub fn new(spec: &OpenApiSpec, config: OpenApiConfig) -> Result<Self, Error> {
55        let collected = operation::collect(spec)?;
56        if !config.prefix.is_empty() {
57            for op in &collected.operations {
58                let name = format!("{}_{}", config.prefix, op.name);
59                if name.len() > MAX_NAME_BYTES {
60                    return Err(Error::NameTooLong { name });
61                }
62            }
63        }
64        let shared = Arc::new(Shared {
65            // Redirects are not followed: a configured header or header parameter (and a
66            // confirmed body) must not reach another URL. A 3xx is returned as a result.
67            client: reqwest::Client::builder()
68                .redirect(reqwest::redirect::Policy::none())
69                .build()
70                .map_err(|err| Error::HttpClient {
71                    source: Box::new(err),
72                })?,
73            base_url: base_url(spec, config.base_url.as_deref())?,
74            auth: config.auth,
75            query_api_key: config.query_api_key,
76            headers: config.headers,
77            timeout: config.timeout,
78            max_response_bytes: config.max_response_bytes,
79            require_confirmation: config.require_confirmation,
80            confirmation_provider: config.confirmation_provider,
81        });
82        let tools = collected
83            .operations
84            .into_iter()
85            .map(|op| RestApiTool::new(op, shared.clone()))
86            .collect();
87        Ok(Self {
88            tools,
89            skipped: collected.skipped,
90            prefix: config.prefix,
91            tool_filter: config.tool_filter,
92        })
93    }
94
95    /// The operations that did not become tools, and why.
96    pub fn skipped_operations(&self) -> &[SkippedOperation] {
97        &self.skipped
98    }
99}
100
101impl fmt::Debug for OpenApiToolset {
102    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103        f.debug_struct("OpenApiToolset")
104            .field(
105                "tools",
106                &self
107                    .tools
108                    .iter()
109                    .map(RestApiTool::original_name)
110                    .collect::<Vec<_>>(),
111            )
112            .field("skipped", &self.skipped)
113            .field("prefix", &self.prefix)
114            .finish_non_exhaustive()
115    }
116}
117
118#[async_trait::async_trait]
119impl Toolset for OpenApiToolset {
120    /// `openapi_toolset`.
121    fn name(&self) -> &str {
122        "openapi_toolset"
123    }
124
125    /// The tools in document order, filtered by `tool_filter` (which sees the unprefixed
126    /// names), then renamed `<prefix>_<name>` when `prefix` is set.
127    async fn tools(&self, ctx: &ReadonlyContext) -> Result<Vec<Arc<dyn Tool>>, ToolError> {
128        let mut tools: Vec<Arc<dyn Tool>> = Vec::with_capacity(self.tools.len());
129        for tool in &self.tools {
130            if let Some(filter) = &self.tool_filter
131                && !filter(ctx, tool)
132            {
133                continue;
134            }
135            let mut tool = tool.clone();
136            if !self.prefix.is_empty() {
137                tool.expose_as(format!("{}_{}", self.prefix, tool.original_name()));
138            }
139            tools.push(Arc::new(tool));
140        }
141        Ok(tools)
142    }
143
144    fn as_any(&self) -> &dyn Any {
145        self
146    }
147}
148
149/// The base URL without a trailing `/`: `configured`, else `servers[0].url` with its variables
150/// set to their defaults and resolved against the URL the document was fetched from. A base
151/// that is not absolute, or that has a query or fragment, is [`Error::NoBaseUrl`].
152pub(crate) fn base_url(spec: &OpenApiSpec, configured: Option<&str>) -> Result<String, Error> {
153    let url = match configured {
154        Some(configured) => Url::parse(configured).map_err(|_| Error::NoBaseUrl)?,
155        None => {
156            let server = spec.document().get("servers").and_then(|s| s.get(0));
157            let mut raw = server
158                .and_then(|s| s.get("url"))
159                .and_then(Value::as_str)
160                .filter(|url| !url.is_empty())
161                .unwrap_or("/")
162                .to_string();
163            if let Some(variables) = server
164                .and_then(|s| s.get("variables"))
165                .and_then(Value::as_object)
166            {
167                for (name, variable) in variables {
168                    if let Some(default) = variable.get("default").and_then(Value::as_str) {
169                        raw = raw.replace(&format!("{{{name}}}"), default);
170                    }
171                }
172            }
173            match Url::parse(&raw) {
174                Ok(url) => url,
175                Err(url::ParseError::RelativeUrlWithoutBase) => match spec.source() {
176                    Some(source) => source.join(&raw).map_err(|_| Error::NoBaseUrl)?,
177                    None => return Err(Error::NoBaseUrl),
178                },
179                Err(_) => return Err(Error::NoBaseUrl),
180            }
181        }
182    };
183    // The operation's path is appended to the base, so a query or fragment would swallow it.
184    if url.cannot_be_a_base() || url.query().is_some() || url.fragment().is_some() {
185        return Err(Error::NoBaseUrl);
186    }
187    Ok(url.as_str().trim_end_matches('/').to_string())
188}
189
190#[cfg(test)]
191#[path = "toolset_tests.rs"]
192mod tests;