1use 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
26const METHODS: [&str; 7] = ["get", "put", "post", "delete", "patch", "head", "options"];
28
29pub(crate) const MAX_NAME_BYTES: usize = 64;
31
32const MAX_DESCRIPTION_CHARS: usize = 1024;
34
35#[derive(Debug, Clone, PartialEq, Eq)]
37#[non_exhaustive]
38pub struct SkippedOperation {
39 pub method: String,
41 pub path: String,
43 pub reason: String,
45}
46
47impl SkippedOperation {
48 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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub(crate) enum Location {
65 Path,
66 Query,
67 Header,
68}
69
70impl Location {
71 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#[derive(Clone, Debug, PartialEq)]
83pub(crate) struct Param {
84 pub(crate) name: String,
86 pub(crate) location: Location,
87 pub(crate) property: String,
89 pub(crate) required: bool,
90 pub(crate) schema: Value,
92}
93
94#[derive(Clone, Debug, PartialEq)]
96pub(crate) struct Body {
97 pub(crate) schema: Value,
98 pub(crate) required: bool,
99}
100
101#[derive(Clone, Debug)]
103pub(crate) struct Operation {
104 pub(crate) method: Method,
105 pub(crate) path: String,
107 pub(crate) name: String,
109 pub(crate) description: String,
110 pub(crate) params: Vec<Param>,
112 pub(crate) body: Option<Body>,
113 pub(crate) mutating: bool,
115}
116
117impl Operation {
118 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#[derive(Debug)]
141pub(crate) struct Collected {
142 pub(crate) operations: Vec<Operation>,
144 pub(crate) skipped: Vec<SkippedOperation>,
145}
146
147pub(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
187fn 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 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 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
308fn 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[¶m.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
335fn 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
351pub(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
365pub(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
401fn 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
415pub(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
428fn text<'a>(value: &'a Value, key: &str) -> &'a str {
430 value.get(key).and_then(Value::as_str).unwrap_or_default()
431}
432
433fn 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;