gadk_openapi/config.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 toolset configuration ([`OpenApiConfig`], [`RequireConfirmation`]).
16
17use std::fmt;
18use std::sync::Arc;
19use std::time::Duration;
20
21use gadk_agent::tool::{ConfirmationProvider, ToolPredicate};
22use gadk_auth::CredentialProvider;
23
24/// The default request timeout.
25pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
26
27/// The default largest response body kept in a tool result, in bytes (256 KiB).
28pub const DEFAULT_MAX_RESPONSE_BYTES: usize = 262_144;
29
30/// Which tool calls need the user's confirmation before the request is sent.
31#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
32#[non_exhaustive]
33pub enum RequireConfirmation {
34 /// Calls of `post`, `put`, `patch` and `delete` operations (the default).
35 #[default]
36 Mutating,
37 /// Every call.
38 Always,
39 /// No call.
40 Never,
41}
42
43/// How [`OpenApiToolset`](crate::OpenApiToolset) calls the API. Start from
44/// [`OpenApiConfig::new`] (the same as [`Default`]) and chain the builder methods.
45#[derive(Clone)]
46#[non_exhaustive]
47pub struct OpenApiConfig {
48 pub(crate) base_url: Option<String>,
49 pub(crate) auth: Option<Arc<dyn CredentialProvider>>,
50 pub(crate) query_api_key: Option<(String, String)>,
51 pub(crate) prefix: String,
52 pub(crate) tool_filter: Option<ToolPredicate>,
53 pub(crate) require_confirmation: RequireConfirmation,
54 pub(crate) confirmation_provider: Option<ConfirmationProvider>,
55 pub(crate) headers: Vec<(String, String)>,
56 pub(crate) timeout: Duration,
57 pub(crate) max_response_bytes: usize,
58}
59
60impl Default for OpenApiConfig {
61 fn default() -> Self {
62 Self {
63 base_url: None,
64 auth: None,
65 query_api_key: None,
66 prefix: String::new(),
67 tool_filter: None,
68 require_confirmation: RequireConfirmation::default(),
69 confirmation_provider: None,
70 headers: Vec::new(),
71 timeout: DEFAULT_TIMEOUT,
72 max_response_bytes: DEFAULT_MAX_RESPONSE_BYTES,
73 }
74 }
75}
76
77impl OpenApiConfig {
78 /// The default configuration: the document's server URL, no credentials, no prefix or
79 /// filter, [`RequireConfirmation::Mutating`], a 30 s timeout and a 256 KiB response cap.
80 pub fn new() -> Self {
81 Self::default()
82 }
83
84 /// The base URL of every request, instead of the document's `servers[0].url`. It must be
85 /// absolute, without a query or fragment, or [`OpenApiToolset::new`] fails with
86 /// [`Error::NoBaseUrl`].
87 ///
88 /// [`OpenApiToolset::new`]: crate::OpenApiToolset::new
89 /// [`Error::NoBaseUrl`]: crate::Error::NoBaseUrl
90 pub fn base_url(mut self, url: impl Into<String>) -> Self {
91 self.base_url = Some(url.into());
92 self
93 }
94
95 /// Sends every request through [`gadk_auth::client`] with `provider`, which writes the
96 /// credential's headers. A 401 or 403 is retried once with a refreshed credential only when
97 /// the provider is a refreshing provider (such as `gadk_auth::gcp::new_provider`, or your own
98 /// `RefreshingProvider`); `static_token`, `api_key`, `token_source`, `adc` and
99 /// `service_account` are not retried (`adc` and `service_account` renew their tokens before
100 /// they expire).
101 pub fn auth(mut self, provider: Arc<dyn CredentialProvider>) -> Self {
102 self.auth = Some(provider);
103 self
104 }
105
106 /// Appends `name=value` to every request's query string.
107 pub fn query_api_key(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
108 self.query_api_key = Some((name.into(), value.into()));
109 self
110 }
111
112 /// Exposes each tool as `<prefix>_<name>`. Empty (the default) keeps the names.
113 pub fn prefix(mut self, prefix: impl Into<String>) -> Self {
114 self.prefix = prefix.into();
115 self
116 }
117
118 /// Keeps only the tools `filter` accepts. The filter sees each tool under its unprefixed
119 /// name.
120 pub fn tool_filter(mut self, filter: ToolPredicate) -> Self {
121 self.tool_filter = Some(filter);
122 self
123 }
124
125 /// Which calls need confirmation (default [`RequireConfirmation::Mutating`]).
126 pub fn require_confirmation(mut self, mode: RequireConfirmation) -> Self {
127 self.require_confirmation = mode;
128 self
129 }
130
131 /// Decides per call whether confirmation is needed, instead of
132 /// [`require_confirmation`](OpenApiConfig::require_confirmation). It is called with the
133 /// exposed tool name and the call's arguments.
134 pub fn confirmation_provider(mut self, provider: ConfirmationProvider) -> Self {
135 self.confirmation_provider = Some(provider);
136 self
137 }
138
139 /// Adds a header to every request.
140 pub fn header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
141 self.headers.push((name.into(), value.into()));
142 self
143 }
144
145 /// The limit on one whole call, from sending the request to reading the body (default
146 /// 30 s).
147 pub fn timeout(mut self, timeout: Duration) -> Self {
148 self.timeout = timeout;
149 self
150 }
151
152 /// The largest response body kept in a result (default 262,144 bytes); a longer body is
153 /// cut and the result gains `"truncated": true`.
154 pub fn max_response_bytes(mut self, max: usize) -> Self {
155 self.max_response_bytes = max;
156 self
157 }
158}
159
160impl fmt::Debug for OpenApiConfig {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 f.debug_struct("OpenApiConfig")
163 .field("base_url", &self.base_url)
164 .field("auth", &self.auth.as_ref().map(|_| "<provider>"))
165 .field(
166 "query_api_key",
167 &self.query_api_key.as_ref().map(|(name, _)| name),
168 )
169 .field("prefix", &self.prefix)
170 .field(
171 "tool_filter",
172 &self.tool_filter.as_ref().map(|_| "<filter>"),
173 )
174 .field("require_confirmation", &self.require_confirmation)
175 .field(
176 "confirmation_provider",
177 &self.confirmation_provider.as_ref().map(|_| "<provider>"),
178 )
179 .field(
180 "headers",
181 &self
182 .headers
183 .iter()
184 .map(|(name, _)| name)
185 .collect::<Vec<_>>(),
186 )
187 .field("timeout", &self.timeout)
188 .field("max_response_bytes", &self.max_response_bytes)
189 .finish()
190 }
191}