Skip to main content

gadk_openapi/
operation.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 document's operations: tool names, parameters, request bodies and skipped operations.
16
17use std::collections::{HashMap, HashSet};
18
19use reqwest::Method;
20use serde_json::{Map, Value, json};
21
22use crate::error::Error;
23use crate::resolve;
24use crate::spec::OpenApiSpec;
25
26/// The operation keys of a path item, in the order OpenAPI lists them.
27const METHODS: [&str; 7] = ["get", "put", "post", "delete", "patch", "head", "options"];
28
29/// The longest tool name, in bytes.
30pub(crate) const MAX_NAME_BYTES: usize = 64;
31
32/// The longest tool description, in characters.
33const MAX_DESCRIPTION_CHARS: usize = 1024;
34
35/// An operation that does not become a tool, and why.
36#[derive(Debug, Clone, PartialEq, Eq)]
37#[non_exhaustive]
38pub struct SkippedOperation {
39    /// The HTTP method in upper case (`GET`), or `*` for every operation of a path item.
40    pub method: String,
41    /// The path template (`/pets/{petId}`).
42    pub path: String,
43    /// Why the operation was skipped (`cookie parameter session`).
44    pub reason: String,
45}
46
47impl SkippedOperation {
48    /// A skipped operation.
49    pub fn new(
50        method: impl Into<String>,
51        path: impl Into<String>,
52        reason: impl Into<String>,
53    ) -> Self {
54        Self {
55            method: method.into(),
56            path: path.into(),
57            reason: reason.into(),
58        }
59    }
60}
61
62/// Where a parameter goes in the request.
63#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub(crate) enum Location {
65    Path,
66    Query,
67    Header,
68}
69
70impl Location {
71    /// The OpenAPI `in` value.
72    fn as_str(self) -> &'static str {
73        match self {
74            Location::Path => "path",
75            Location::Query => "query",
76            Location::Header => "header",
77        }
78    }
79}
80
81/// One path, query or header parameter.
82#[derive(Clone, Debug, PartialEq)]
83pub(crate) struct Param {
84    /// The parameter's name in the request.
85    pub(crate) name: String,
86    pub(crate) location: Location,
87    /// The declaration property that carries it.
88    pub(crate) property: String,
89    pub(crate) required: bool,
90    /// The cleaned schema, with the parameter's description.
91    pub(crate) schema: Value,
92}
93
94/// An `application/json` request body.
95#[derive(Clone, Debug, PartialEq)]
96pub(crate) struct Body {
97    pub(crate) schema: Value,
98    pub(crate) required: bool,
99}
100
101/// One operation that becomes a tool.
102#[derive(Clone, Debug)]
103pub(crate) struct Operation {
104    pub(crate) method: Method,
105    /// The path template.
106    pub(crate) path: String,
107    /// The unprefixed tool name.
108    pub(crate) name: String,
109    pub(crate) description: String,
110    /// Parameters in declaration order (path-item parameters, then the operation's).
111    pub(crate) params: Vec<Param>,
112    pub(crate) body: Option<Body>,
113    /// Whether the method changes state (`post`, `put`, `patch`, `delete`).
114    pub(crate) mutating: bool,
115}
116
117impl Operation {
118    /// The declaration's `parameters_json_schema`. Its `properties` is a `serde_json::Map`, so
119    /// they come out in sorted key order; `required` follows declaration order.
120    pub(crate) fn parameters_schema(&self) -> Value {
121        let mut properties = Map::new();
122        let mut required = Vec::new();
123        for param in &self.params {
124            properties.insert(param.property.clone(), param.schema.clone());
125            if param.required {
126                required.push(Value::String(param.property.clone()));
127            }
128        }
129        if let Some(body) = &self.body {
130            properties.insert("body".to_string(), body.schema.clone());
131            if body.required {
132                required.push(Value::String("body".to_string()));
133            }
134        }
135        json!({"type": "object", "properties": properties, "required": required})
136    }
137}
138
139/// The document's operations.
140#[derive(Debug)]
141pub(crate) struct Collected {
142    /// The operations that become tools, in document order.
143    pub(crate) operations: Vec<Operation>,
144    pub(crate) skipped: Vec<SkippedOperation>,
145}
146
147/// Walks `paths` into operations and skipped operations. Two operations with the same tool
148/// name, or one tool with two properties of the same name, are [`Error::DuplicateName`].
149pub(crate) fn collect(spec: &OpenApiSpec) -> Result<Collected, Error> {
150    let doc = spec.document();
151    let mut operations = Vec::new();
152    let mut skipped = Vec::new();
153    let mut names = HashSet::new();
154    for (path, keys) in spec.path_order() {
155        let Some(item) = doc.get("paths").and_then(|paths| paths.get(path)) else {
156            continue;
157        };
158        if item.get("$ref").is_some() {
159            skipped.push(SkippedOperation::new(
160                "*",
161                path.as_str(),
162                "path item $ref is not supported",
163            ));
164            continue;
165        }
166        for key in keys {
167            if !METHODS.contains(&key.as_str()) {
168                continue;
169            }
170            match operation(spec, path, key, item, &item[key.as_str()])? {
171                Ok(op) => {
172                    if !names.insert(op.name.clone()) {
173                        return Err(Error::DuplicateName { name: op.name });
174                    }
175                    operations.push(op);
176                }
177                Err(skip) => skipped.push(skip),
178            }
179        }
180    }
181    Ok(Collected {
182        operations,
183        skipped,
184    })
185}
186
187/// One operation, or why it is skipped.
188fn operation(
189    spec: &OpenApiSpec,
190    path: &str,
191    method: &str,
192    item: &Value,
193    op: &Value,
194) -> Result<Result<Operation, SkippedOperation>, Error> {
195    let doc = spec.document();
196    let upper = method.to_ascii_uppercase();
197    let at = format!("{upper} {path}");
198    let skip = |reason: String| Ok(Err(SkippedOperation::new(upper.as_str(), path, reason)));
199
200    // Path-item parameters, then the operation's; the operation's wins for the same name and
201    // location, in the path-item parameter's place.
202    let mut merged: Vec<&Value> = Vec::new();
203    for raw in array(item.get("parameters")) {
204        merged.push(resolve::object(doc, raw, &at)?);
205    }
206    for raw in array(op.get("parameters")) {
207        let param = resolve::object(doc, raw, &at)?;
208        let key = (text(param, "name"), text(param, "in"));
209        match merged
210            .iter()
211            .position(|m| (text(m, "name"), text(m, "in")) == key)
212        {
213            Some(i) => merged[i] = param,
214            None => merged.push(param),
215        }
216    }
217    let mut located = Vec::with_capacity(merged.len());
218    for param in merged {
219        let location = match text(param, "in") {
220            "path" => Location::Path,
221            "query" => Location::Query,
222            "header" => Location::Header,
223            "cookie" => return skip(format!("cookie parameter {}", text(param, "name"))),
224            other => {
225                return skip(format!(
226                    "parameter {} has unsupported location {other:?}",
227                    text(param, "name")
228                ));
229            }
230        };
231        located.push((param, location));
232    }
233
234    let mut json_body = None;
235    if let Some(raw) = op.get("requestBody") {
236        let body = resolve::object(doc, raw, &at)?;
237        // `content` is a `serde_json::Map`, so its media types come in sorted key order, not
238        // document order: the body is the first JSON one in that order, and the skip reason
239        // lists them in that order.
240        let content = body.get("content").and_then(Value::as_object);
241        match content.and_then(|c| c.iter().find(|(media, _)| is_json(media))) {
242            Some((_, media)) => {
243                json_body = Some((media, body.get("required") == Some(&Value::Bool(true))));
244            }
245            None => {
246                let types = content
247                    .map(|c| c.keys().cloned().collect::<Vec<_>>().join(", "))
248                    .filter(|types| !types.is_empty())
249                    .unwrap_or_else(|| "(none)".to_string());
250                return skip(format!("request body content {types} is not JSON"));
251            }
252        }
253    }
254
255    let name = tool_name(op.get("operationId").and_then(Value::as_str), method, path);
256    let openapi_3_0 = spec.is_3_0();
257    let mut params = Vec::with_capacity(located.len());
258    for (param, location) in located {
259        let mut schema = match param.get("schema") {
260            Some(schema) => resolve::schema(doc, schema, &at, openapi_3_0)?,
261            None => json!({}),
262        };
263        if let (Some(description), Value::Object(schema)) = (
264            param.get("description").and_then(Value::as_str),
265            &mut schema,
266        ) && !schema.contains_key("description")
267        {
268            schema.insert("description".to_string(), json!(description));
269        }
270        params.push(Param {
271            name: text(param, "name").to_string(),
272            location,
273            property: property_name(text(param, "name")),
274            required: location == Location::Path
275                || param.get("required") == Some(&Value::Bool(true)),
276            schema,
277        });
278    }
279    disambiguate(&name, &mut params, json_body.is_some())?;
280
281    let body = match json_body {
282        Some((media, required)) => Some(Body {
283            schema: match media.get("schema") {
284                Some(schema) => resolve::schema(doc, schema, &at, openapi_3_0)?,
285                None => json!({}),
286            },
287            required,
288        }),
289        None => None,
290    };
291
292    let method = Method::from_bytes(upper.as_bytes()).unwrap_or(Method::GET);
293    let mutating = matches!(
294        method,
295        Method::POST | Method::PUT | Method::PATCH | Method::DELETE
296    );
297    Ok(Ok(Operation {
298        description: description(op, &upper, path),
299        method,
300        path: path.to_string(),
301        name,
302        params,
303        body,
304        mutating,
305    }))
306}
307
308/// Renames colliding properties `<property>_<in>` (every parameter that shares a property name
309/// with another, or is named `body`); a collision that remains is [`Error::DuplicateName`]
310/// named `<tool name>.<property>`.
311fn disambiguate(tool: &str, params: &mut [Param], has_body: bool) -> Result<(), Error> {
312    let mut counts: HashMap<String, usize> = HashMap::new();
313    for param in params.iter() {
314        *counts.entry(param.property.clone()).or_default() += 1;
315    }
316    for param in params.iter_mut() {
317        if counts[&param.property] > 1 || param.property == "body" {
318            param.property = format!("{}_{}", param.property, param.location.as_str());
319        }
320    }
321    let mut seen = HashSet::new();
322    if has_body {
323        seen.insert("body".to_string());
324    }
325    for param in params.iter() {
326        if !seen.insert(param.property.clone()) {
327            return Err(Error::DuplicateName {
328                name: format!("{tool}.{}", param.property),
329            });
330        }
331    }
332    Ok(())
333}
334
335/// The tool description: `summary` and `description` separated by a blank line, whichever
336/// exists, or `<METHOD> <path>`; at most 1,024 characters.
337fn description(op: &Value, upper: &str, path: &str) -> String {
338    let field = |key: &str| {
339        op.get(key)
340            .and_then(Value::as_str)
341            .filter(|s| !s.is_empty())
342    };
343    let full = match (field("summary"), field("description")) {
344        (Some(summary), Some(description)) => format!("{summary}\n\n{description}"),
345        (Some(one), None) | (None, Some(one)) => one.to_string(),
346        (None, None) => format!("{upper} {path}"),
347    };
348    full.chars().take(MAX_DESCRIPTION_CHARS).collect()
349}
350
351/// The tool name: the snake_case of `operation_id`, or of `<method>_<path>` when there is none
352/// or it becomes empty; at most 64 bytes.
353pub(crate) fn tool_name(operation_id: Option<&str>, method: &str, path: &str) -> String {
354    let mut name = operation_id.map(snake_case).unwrap_or_default();
355    if name.is_empty() {
356        name = snake_case(&format!("{method}_{path}"));
357    }
358    if name.len() > MAX_NAME_BYTES {
359        name.truncate(MAX_NAME_BYTES);
360        name.truncate(name.trim_end_matches('_').len());
361    }
362    name
363}
364
365/// `_` before an upper-case letter that follows a lower-case letter or digit, or that follows
366/// an upper-case letter and precedes a lower-case one; every character outside `[A-Za-z0-9_]`
367/// becomes `_`; runs of `_` collapse, edges are trimmed, the result is lower case, and a
368/// leading digit gets `op_`.
369pub(crate) fn snake_case(input: &str) -> String {
370    let chars: Vec<char> = input.chars().collect();
371    let mut spaced = String::with_capacity(input.len() + 4);
372    for (i, &c) in chars.iter().enumerate() {
373        if c.is_ascii_uppercase() && i > 0 {
374            let prev = chars[i - 1];
375            let next_lower = chars.get(i + 1).is_some_and(char::is_ascii_lowercase);
376            if prev.is_ascii_lowercase()
377                || prev.is_ascii_digit()
378                || (prev.is_ascii_uppercase() && next_lower)
379            {
380                spaced.push('_');
381            }
382        }
383        if c.is_ascii_alphanumeric() || c == '_' {
384            spaced.push(c.to_ascii_lowercase());
385        } else {
386            spaced.push('_');
387        }
388    }
389    let collapsed = spaced
390        .split('_')
391        .filter(|part| !part.is_empty())
392        .collect::<Vec<_>>()
393        .join("_");
394    if collapsed.starts_with(|c: char| c.is_ascii_digit()) {
395        format!("op_{collapsed}")
396    } else {
397        collapsed
398    }
399}
400
401/// The declaration property for a parameter: every character outside `[A-Za-z0-9_]` becomes
402/// `_`.
403fn property_name(name: &str) -> String {
404    name.chars()
405        .map(|c| {
406            if c.is_ascii_alphanumeric() || c == '_' {
407                c
408            } else {
409                '_'
410            }
411        })
412        .collect()
413}
414
415/// Whether a media type is JSON (`application/json` or `application/<x>+json`, parameters
416/// ignored).
417pub(crate) fn is_json(media_type: &str) -> bool {
418    let essence = media_type
419        .split(';')
420        .next()
421        .unwrap_or_default()
422        .trim()
423        .to_ascii_lowercase();
424    essence == "application/json"
425        || (essence.starts_with("application/") && essence.ends_with("+json"))
426}
427
428/// A string field of a JSON object, or `""`.
429fn text<'a>(value: &'a Value, key: &str) -> &'a str {
430    value.get(key).and_then(Value::as_str).unwrap_or_default()
431}
432
433/// The items of an optional JSON array.
434fn array(value: Option<&Value>) -> &[Value] {
435    value
436        .and_then(Value::as_array)
437        .map(Vec::as_slice)
438        .unwrap_or_default()
439}
440
441#[cfg(test)]
442#[path = "operation_tests.rs"]
443mod tests;