feat(import): preserve supported HTTP contracts

This commit is contained in:
bsodfather committed 2026-09-13 03:30:31 +03:00
1 parent 083974c27f
commit f8ee7c9bfe
87 files changed
+7496 -534

No files matched your search

+358 -31
View File
@@ -1,19 +1,22 @@
use std::collections::{BTreeMap, BTreeSet};
use crank_core::{
ExecutionConfig, HttpMethod, OperationSafetyClass, OperationSafetyPolicy, Protocol, RestTarget,
ToolDescription, ToolExample, WizardState,
ExecutionConfig, HttpMethod, OperationSafetyClass, OperationSafetyPolicy, Protocol,
RestRequestContract, RestRequestContractVersion, RestRequestDescriptor, RestResponseDescriptor,
RestTarget, ToolDescription, ToolExample, WizardState,
};
use serde_json::json;
use crate::rest::{
mapping::{BodyFieldMapping, input_mapping, output_mapping},
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_openapi},
schema::{
any_object, field_count, object_with_fields, schema_from_multipart, schema_from_openapi,
},
};
pub fn candidate_from_operation(
@@ -55,32 +58,37 @@ pub fn candidate_from_operation(
let base_url = server_urls.first().cloned().unwrap_or_default();
let mut input_fields = BTreeMap::new();
let mut used_input_field_names = BTreeSet::new();
for parameter in &operation.parameters {
used_input_field_names.insert(parameter.name.clone());
input_fields.insert(
parameter.name.clone(),
schema_from_openapi(
parameter.schema.as_ref(),
parameter.required || parameter.location == RestParameterLocation::Path,
parameter.description.clone(),
),
);
}
let body_fields = body_input_fields(
operation.request_body_schema.as_ref(),
&mut used_input_field_names,
&mut input_fields,
);
let input_schema = object_with_fields(
Some("Входные параметры MCP-инструмента".to_owned()),
input_fields,
);
let output_schema = 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 input_mapping = input_mapping(&operation.parameters, &body_fields);
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::<Vec<_>>();
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(&parameter_mappings, &body_fields);
let output_mapping = output_mapping(&output_schema);
let mut findings = operation_recommendations(operation);
findings.extend(candidate_recommendations(
@@ -100,6 +108,29 @@ pub fn candidate_from_operation(
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(),
@@ -136,7 +167,274 @@ pub fn candidate_from_operation(
}
}
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::<Vec<_>>();
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<String>,
input_fields: &mut BTreeMap<String, crank_schema::Schema>,
) -> Vec<BodyFieldMapping> {
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::<Vec<_>>();
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<String, crank_schema::Schema>,
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::<Vec<_>>();
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<String>,
fields: BTreeMap<String, crank_schema::Schema>,
) -> 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<RestRequestContract> {
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<String>,
input_fields: &mut BTreeMap<String, crank_schema::Schema>,
@@ -158,7 +456,6 @@ fn body_input_fields(
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);
@@ -172,6 +469,33 @@ fn body_input_fields(
mappings
}
fn unique_parameter_input_name(
parameter: &crate::rest::model::RestImportParameter,
used_names: &mut BTreeSet<String>,
) -> 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>) -> String {
if used_names.insert(name.to_owned()) {
return name.to_owned();
@@ -207,6 +531,8 @@ fn method_as_str(method: HttpMethod) -> &'static str {
HttpMethod::Put => "PUT",
HttpMethod::Patch => "PATCH",
HttpMethod::Delete => "DELETE",
HttpMethod::Head => "HEAD",
HttpMethod::Options => "OPTIONS",
}
}
@@ -216,6 +542,7 @@ fn safety_for_method(method: HttpMethod) -> OperationSafetyPolicy {
HttpMethod::Get => OperationSafetyClass::Read,
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
HttpMethod::Delete => OperationSafetyClass::Destructive,
HttpMethod::Head | HttpMethod::Options => OperationSafetyClass::Read,
};
OperationSafetyPolicy {
class,