use std::collections::{BTreeMap, BTreeSet}; use crank_core::{ ExecutionConfig, HttpMethod, OperationSafetyClass, OperationSafetyPolicy, Protocol, RestRequestContract, RestRequestContractVersion, RestRequestDescriptor, RestResponseDescriptor, RestTarget, ToolDescription, ToolExample, WizardState, }; use serde_json::json; use crate::rest::{ mapping::{BodyFieldMapping, ParameterFieldMapping, input_mapping, output_mapping}, model::{ ImportOperationCandidate, RestImportCandidate, RestImportOperation, RestParameterLocation, }, naming::{fallback_operation_seed, title_from_name, unique_name}, recommendations::{candidate_recommendations, operation_recommendations}, schema::{ any_object, field_count, object_with_fields, schema_from_multipart, schema_from_openapi, }, }; pub fn candidate_from_operation( operation: &RestImportOperation, security_schemes: &BTreeMap, document_servers: &[String], used_names: &mut BTreeSet, ) -> ImportOperationCandidate { let method_name = method_as_str(operation.method); let seed = operation .operation_id .as_deref() .filter(|value| !value.trim().is_empty()) .map(ToOwned::to_owned) .unwrap_or_else(|| fallback_operation_seed(method_name, &operation.path)); let name = unique_name(&seed, used_names); let display_name = operation .summary .as_deref() .filter(|value| !value.trim().is_empty()) .map(ToOwned::to_owned) .unwrap_or_else(|| title_from_name(&name)); let description = operation .description .as_deref() .or(operation.summary.as_deref()) .filter(|value| !value.trim().is_empty()) .map(ToOwned::to_owned) .unwrap_or_else(|| format!("Выполняет {method_name} {}", operation.path)); let category = operation .tags .first() .cloned() .unwrap_or_else(|| "imported".to_owned()); let server_urls = if operation.servers.is_empty() { document_servers.to_vec() } else { operation.servers.clone() }; let base_url = server_urls.first().cloned().unwrap_or_default(); let mut input_fields = BTreeMap::new(); let mut used_input_field_names = BTreeSet::new(); let parameter_mappings = operation .parameters .iter() .map(|parameter| { let input_name = unique_parameter_input_name(parameter, &mut used_input_field_names); let default_value = parameter .schema .as_ref() .and_then(|schema| schema.get("default")) .cloned(); input_fields.insert( input_name.clone(), schema_from_openapi( parameter.schema.as_ref(), parameter.required || parameter.location == RestParameterLocation::Path, parameter.description.clone(), ), ); ParameterFieldMapping { input_name, wire_name: parameter.name.clone(), location: parameter.location, required: parameter.required || parameter.location == RestParameterLocation::Path, default_value, } }) .collect::>(); let body_fields = body_input_fields(operation, &mut used_input_field_names, &mut input_fields); let input_schema = input_schema_for_body_variants(operation, input_fields, &body_fields); let output_schema = output_schema_from_operation(operation); let input_mapping = input_mapping(¶meter_mappings, &body_fields); let output_mapping = output_mapping(&output_schema); let mut findings = operation_recommendations(operation); findings.extend(candidate_recommendations( operation, &name, &description, &input_schema, &output_schema, )); let draft = RestImportCandidate { name: name.clone(), display_name: display_name.clone(), category: category.clone(), target: RestTarget { base_url, method: operation.method, path_template: operation.path.clone(), static_headers: BTreeMap::new(), request_contract: request_contract(operation, &body_fields), response_contract: operation .response_variants .iter() .enumerate() .map(|(schema_variant, variant)| RestResponseDescriptor { status_code: variant.status_code, media_type: variant.content_type.clone(), schema_variant, }) .collect(), multipart_field_mime_types: operation .request_body_variants .iter() .filter(|variant| variant.content_type == "multipart/form-data") .filter(|variant| !variant.multipart_field_mime_types.is_empty()) .map(|variant| { ( variant.content_type.clone(), variant.multipart_field_mime_types.clone(), ) }) .collect(), }, input_schema: input_schema.clone(), output_schema: output_schema.clone(), input_mapping, output_mapping, tool_description: ToolDescription { title: display_name.clone(), description: description.clone(), tags: operation.tags.clone(), examples: vec![ToolExample { input: json!({}) }], }, wizard_state: Some(WizardState { input_sample: None, output_sample: None, test_input: None, import_findings: Vec::new(), }), }; ImportOperationCandidate { key: operation.key.clone(), method: operation.method, path: operation.path.clone(), status: String::new(), source_location: operation.source_location.clone(), security_requirements: operation.security_requirements.clone(), security_schemes: security_schemes.clone(), operation_id: operation.operation_id.clone(), suggested_name: name, suggested_display_name: display_name, description, category, input_fields: field_count(&input_schema), output_fields: field_count(&output_schema), server_urls, findings, draft, } } fn output_schema_from_operation(operation: &RestImportOperation) -> crank_schema::Schema { if operation.response_variants.is_empty() { return operation .response_schema .as_ref() .map(|schema| schema_from_openapi(Some(schema), true, Some("Ответ API".to_owned()))) .unwrap_or_else(|| any_object(Some("Ответ API".to_owned()))); } let mut variants = operation .response_variants .iter() .map(|variant| match &variant.schema { Some(schema) => schema_from_openapi(Some(schema), true, Some("Ответ API".to_owned())), None => crank_schema::Schema { kind: crank_schema::SchemaKind::Null, format: None, description: Some("Успешный ответ без тела".to_owned()), required: true, nullable: false, default_value: None, fields: BTreeMap::new(), items: None, enum_values: Vec::new(), variants: Vec::new(), }, }) .collect::>(); if variants.len() == 1 { return variants .pop() .unwrap_or_else(|| any_object(Some("Ответ API".to_owned()))); } crank_schema::Schema { kind: crank_schema::SchemaKind::Oneof, format: None, description: Some("Варианты успешного ответа API".to_owned()), required: true, nullable: false, default_value: None, fields: BTreeMap::new(), items: None, enum_values: Vec::new(), variants, } } fn body_input_fields( operation: &RestImportOperation, used_names: &mut BTreeSet, input_fields: &mut BTreeMap, ) -> Vec { let variants = &operation.request_body_variants; if variants.is_empty() { return legacy_body_input_fields( operation.request_body_schema.as_ref(), used_names, input_fields, ); } let required = variants.iter().any(|variant| variant.required); let body_variants = variants .iter() .map(|variant| { let description = Some(format!("Тело запроса ({})", variant.content_type)); if variant.content_type == "multipart/form-data" { schema_from_multipart(variant.schema.as_ref(), required, description) } else { schema_from_openapi(variant.schema.as_ref(), required, description) } }) .collect::>(); let body_schema = if body_variants.len() == 1 { body_variants .into_iter() .next() .expect("single body variant exists") } else { crank_schema::Schema { kind: crank_schema::SchemaKind::Oneof, format: None, description: Some("Тело запроса для выбранного формата".to_owned()), required, nullable: body_variants.iter().any(|variant| variant.nullable), default_value: None, fields: BTreeMap::new(), items: None, enum_values: Vec::new(), variants: body_variants, } }; let body_name = unique_body_input_name("body", used_names); input_fields.insert(body_name.clone(), body_schema); if variants.len() > 1 { let selector = unique_body_input_name("content_type", used_names); input_fields.insert( selector.clone(), crank_schema::Schema { kind: crank_schema::SchemaKind::Enum, format: None, description: Some("Выбирает формат тела запроса".to_owned()), required, nullable: false, default_value: None, fields: BTreeMap::new(), items: None, enum_values: variants .iter() .map(|variant| variant.content_type.clone()) .collect(), variants: Vec::new(), }, ); // The adapter obtains the selector from the mapped body envelope. return vec![ BodyFieldMapping { input_name: body_name, // Keep selector and value in an internal envelope so that a // selected nullable body can remain JSON null on the wire. body_path: "__body".to_owned(), required, }, BodyFieldMapping { input_name: selector, body_path: "__content_type".to_owned(), required, }, ]; } vec![BodyFieldMapping { input_name: body_name, body_path: String::new(), required, }] } fn input_schema_for_body_variants( operation: &RestImportOperation, input_fields: BTreeMap, body_fields: &[BodyFieldMapping], ) -> crank_schema::Schema { if operation.request_body_variants.len() <= 1 { return object_with_fields( Some("Входные параметры MCP-инструмента".to_owned()), input_fields, ); } let Some(body_name) = body_fields .iter() .find(|field| field.body_path == "__body") .map(|field| field.input_name.as_str()) else { return object_with_fields( Some("Входные параметры MCP-инструмента".to_owned()), input_fields, ); }; let Some(selector_name) = body_fields .iter() .find(|field| field.body_path == "__content_type") .map(|field| field.input_name.as_str()) else { return object_with_fields( Some("Входные параметры MCP-инструмента".to_owned()), input_fields, ); }; let Some(body_schema) = input_fields.get(body_name) else { return object_with_fields( Some("Входные параметры MCP-инструмента".to_owned()), input_fields, ); }; let Some(selector_schema) = input_fields.get(selector_name) else { return object_with_fields( Some("Входные параметры MCP-инструмента".to_owned()), input_fields, ); }; let variants = operation .request_body_variants .iter() .zip(&body_schema.variants) .map(|(request_variant, body_schema)| { let mut fields = input_fields.clone(); let mut body_schema = body_schema.clone(); body_schema.required = true; fields.insert(body_name.to_owned(), body_schema); let mut selector = selector_schema.clone(); selector.required = true; selector.enum_values = vec![request_variant.content_type.clone()]; fields.insert(selector_name.to_owned(), selector); closed_object_with_fields(Some("Входные параметры MCP-инструмента".to_owned()), fields) }) .collect::>(); let mut variants = variants; if !operation .request_body_variants .iter() .any(|variant| variant.required) { let mut absent_fields = input_fields; absent_fields.remove(body_name); absent_fields.remove(selector_name); variants.push(closed_object_with_fields( Some("Входные параметры без HTTP body".to_owned()), absent_fields, )); } crank_schema::Schema { kind: crank_schema::SchemaKind::Oneof, format: None, description: Some("Входные параметры для выбранного формата тела запроса".to_owned()), required: true, nullable: false, default_value: None, fields: BTreeMap::new(), items: None, enum_values: Vec::new(), variants, } } fn closed_object_with_fields( description: Option, fields: BTreeMap, ) -> crank_schema::Schema { let mut schema = object_with_fields(description, fields); schema.format = Some(crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT.to_owned()); schema } fn request_contract( operation: &RestImportOperation, body_fields: &[BodyFieldMapping], ) -> Option { if operation.request_body_variants.is_empty() { return None; } let body_field = body_fields .iter() .find(|field| field.body_path.is_empty() || field.body_path == "__body")? .input_name .clone(); let selector_field = body_fields .iter() .find(|field| field.body_path == "__content_type") .map(|field| field.input_name.clone()); Some(RestRequestContract { version: RestRequestContractVersion::V1, body_field, selector_field, body_required: operation .request_body_variants .iter() .any(|variant| variant.required), variants: operation .request_body_variants .iter() .enumerate() .map(|(schema_variant, variant)| RestRequestDescriptor { media_type: variant.content_type.clone(), schema_variant, }) .collect(), }) } fn legacy_body_input_fields( request_body_schema: Option<&serde_json::Value>, used_names: &mut BTreeSet, input_fields: &mut BTreeMap, ) -> Vec { let Some(request_body_schema) = request_body_schema else { return Vec::new(); }; let body_schema = schema_from_openapi( Some(request_body_schema), true, Some("Тело запроса".to_owned()), ); if body_schema.kind != crank_schema::SchemaKind::Object || body_schema.fields.is_empty() { let input_name = unique_body_input_name("body", used_names); input_fields.insert(input_name.clone(), body_schema); return vec![BodyFieldMapping { input_name, body_path: String::new(), required: true, }]; } let mut mappings = Vec::new(); for (field_name, field_schema) in body_schema.fields { let input_name = unique_body_input_name(&field_name, used_names); mappings.push(BodyFieldMapping { input_name: input_name.clone(), body_path: field_name, required: field_schema.required, }); input_fields.insert(input_name, field_schema); } mappings } fn unique_parameter_input_name( parameter: &crate::rest::model::RestImportParameter, used_names: &mut BTreeSet, ) -> String { let reserved = matches!(parameter.name.as_str(), "body" | "content_type"); if !reserved && used_names.insert(parameter.name.clone()) { return parameter.name.clone(); } unique_body_input_name( &format!( "{}_{}", parameter_location_name(parameter.location), parameter.name ), used_names, ) } fn parameter_location_name(location: RestParameterLocation) -> &'static str { match location { RestParameterLocation::Path => "path", RestParameterLocation::Query => "query", RestParameterLocation::Header => "header", RestParameterLocation::Cookie => "cookie", } } fn unique_body_input_name(name: &str, used_names: &mut BTreeSet) -> String { if used_names.insert(name.to_owned()) { return name.to_owned(); } let prefixed = format!("body_{name}"); if used_names.insert(prefixed.clone()) { return prefixed; } for index in 2.. { let candidate = format!("body_{name}_{index}"); if used_names.insert(candidate.clone()) { return candidate; } } unreachable!() } pub fn operation_draft_from_candidate( candidate: &ImportOperationCandidate, server_url: Option<&str>, ) -> RestImportCandidate { let mut draft = candidate.draft.clone(); if let Some(server_url) = server_url.filter(|value| !value.trim().is_empty()) { draft.target.base_url = server_url.trim().trim_end_matches('/').to_owned(); } draft } fn method_as_str(method: HttpMethod) -> &'static str { match method { HttpMethod::Get => "GET", HttpMethod::Post => "POST", HttpMethod::Put => "PUT", HttpMethod::Patch => "PATCH", HttpMethod::Delete => "DELETE", HttpMethod::Head => "HEAD", HttpMethod::Options => "OPTIONS", } } #[allow(dead_code)] fn safety_for_method(method: HttpMethod) -> OperationSafetyPolicy { let class = match method { HttpMethod::Get => OperationSafetyClass::Read, HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write, HttpMethod::Delete => OperationSafetyClass::Destructive, HttpMethod::Head | HttpMethod::Options => OperationSafetyClass::Read, }; OperationSafetyPolicy { class, confirmation: None, } } #[allow(dead_code)] fn default_execution_config() -> ExecutionConfig { ExecutionConfig { timeout_ms: 10_000, retry_policy: None, response_cache: None, idempotency: None, safety: None, approval_policy: None, auth_profile_ref: None, headers: BTreeMap::new(), } } #[allow(dead_code)] fn _protocol() -> Protocol { Protocol::Rest }