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

+81 -5
View File
@@ -108,8 +108,9 @@ fn search_mode_tool_definitions(policy: &ToolSelectionPolicy) -> Vec<Value> {
pub fn tool_definitions(tool: &PublishedAgentTool) -> Vec<Value> {
let safety = effective_safety_policy(tool);
let requires_confirmation = safety.class.requires_confirmation();
let input_schema = operation_input_json_schema(tool);
let input_schema = if requires_confirmation {
add_confirmation_token(schema_to_json_schema(&tool.operation.input_schema))
add_confirmation_token(input_schema)
} else {
schema_to_json_schema(&tool.operation.input_schema)
};
@@ -130,6 +131,26 @@ pub fn tool_definitions(tool: &PublishedAgentTool) -> Vec<Value> {
)]
}
fn operation_input_json_schema(tool: &PublishedAgentTool) -> Value {
let mut projected = schema_to_json_schema(&tool.operation.input_schema);
if matches!(&tool.operation.target, Target::Rest(target) if target.request_contract.is_some()) {
close_request_objects(&mut projected);
}
projected
}
fn close_request_objects(schema: &mut Value) {
if let Some(variants) = schema.get_mut("anyOf").and_then(Value::as_array_mut) {
for variant in variants {
close_request_objects(variant);
}
return;
}
if schema.get("type").and_then(Value::as_str) == Some("object") {
schema["additionalProperties"] = Value::Bool(false);
}
}
pub fn analyze_published_tool_catalog(
tools: &[PublishedAgentTool],
) -> Result<ToolCatalogAnalysis, ToolCatalogAnalysisError> {
@@ -187,13 +208,25 @@ fn infer_safety_class(tool: &PublishedAgentTool) -> OperationSafetyClass {
HttpMethod::Get => OperationSafetyClass::Read,
HttpMethod::Delete => OperationSafetyClass::Destructive,
HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch => OperationSafetyClass::Write,
HttpMethod::Head | HttpMethod::Options => OperationSafetyClass::Read,
},
}
}
fn add_confirmation_token(mut schema: Value) -> Value {
let Some(object) = schema.as_object_mut() else {
if let Some(variants) = schema.get_mut("anyOf").and_then(Value::as_array_mut) {
for variant in variants {
add_confirmation_token_to_object(variant);
}
return schema;
}
add_confirmation_token_to_object(&mut schema);
schema
}
fn add_confirmation_token_to_object(schema: &mut Value) {
let Some(object) = schema.as_object_mut() else {
return;
};
let properties = object.entry("properties").or_insert_with(|| json!({}));
if let Some(properties) = properties.as_object_mut() {
@@ -205,11 +238,10 @@ fn add_confirmation_token(mut schema: Value) -> Value {
}),
);
}
schema
}
pub fn schema_to_json_schema(schema: &crank_schema::Schema) -> Value {
match schema.kind {
let mut projected = match schema.kind {
crank_schema::SchemaKind::Object => {
let mut properties = serde_json::Map::new();
let mut required = Vec::new();
@@ -242,11 +274,55 @@ pub fn schema_to_json_schema(schema: &crank_schema::Schema) -> Value {
crank_schema::SchemaKind::Boolean => json!({ "type": "boolean" }),
crank_schema::SchemaKind::Enum => json!({
"type": "string",
"enum": schema.enum_values
"enum": schema.enum_values.clone()
}),
crank_schema::SchemaKind::Null => json!({ "type": "null" }),
crank_schema::SchemaKind::Oneof => json!({
"anyOf": schema.variants.iter().map(schema_to_json_schema).collect::<Vec<_>>()
}),
};
if schema.kind == crank_schema::SchemaKind::Object
&& matches!(
schema.format.as_deref(),
Some("binary" | crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT)
)
{
projected["additionalProperties"] = Value::Bool(false);
}
if let Some(format) = &schema.format
&& format != crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT
{
projected["format"] = Value::String(format.clone());
}
if schema.nullable {
if schema.kind == crank_schema::SchemaKind::Enum
&& let Some(values) = projected.get_mut("enum").and_then(Value::as_array_mut)
&& !values.iter().any(Value::is_null)
{
values.push(Value::Null);
}
if let Some(kind) = projected.get_mut("type") {
match kind {
Value::String(name) => {
*kind = Value::Array(vec![
Value::String(name.clone()),
Value::String("null".to_owned()),
]);
}
Value::Array(kinds) if !kinds.iter().any(|kind| kind.as_str() == Some("null")) => {
kinds.push(Value::String("null".to_owned()));
}
_ => {}
}
} else if let Some(variants) = projected.get_mut("anyOf").and_then(Value::as_array_mut) {
variants.push(json!({"type": "null"}));
}
}
if let Some(default) = &schema.default_value {
projected["default"] = default.clone();
}
if let Some(description) = &schema.description {
projected["description"] = Value::String(description.clone());
}
projected
}
@@ -2,12 +2,13 @@ use std::collections::BTreeMap;
use std::time::Instant;
use crank_community_mcp::manifest::{
analyze_published_tool_catalog, catalog_tool_definitions, tool_definitions,
analyze_published_tool_catalog, catalog_tool_definitions, schema_to_json_schema,
tool_definitions,
};
use crank_core::{
ExecutionConfig, HttpMethod, Operation, OperationId, OperationSecurityLevel, OperationStatus,
Protocol, RestTarget, Target, ToolAccessMode, ToolDescription, ToolSelectionPolicy,
WorkspaceId,
Protocol, RestRequestContract, RestRequestContractVersion, RestRequestDescriptor, RestTarget,
Target, ToolAccessMode, ToolDescription, ToolSelectionPolicy, WorkspaceId,
};
use crank_mapping::MappingSet;
use crank_registry::{PublishedAgentCatalog, PublishedAgentTool, RegistryOperation};
@@ -61,6 +62,107 @@ fn marks_destructive_tools_as_two_step_confirmation_calls() {
assert_eq!(definition["inputSchema"]["required"], json!(["base"]));
}
#[test]
fn projects_nullable_and_binary_as_valid_closed_json_schema() {
let nullable = Schema {
kind: SchemaKind::String,
nullable: true,
..empty_schema(SchemaKind::String)
};
let projected = schema_to_json_schema(&nullable);
assert_eq!(projected["type"], json!(["string", "null"]));
assert!(projected.get("nullable").is_none());
let nullable_enum = Schema {
kind: SchemaKind::Enum,
nullable: true,
enum_values: vec!["draft".to_owned()],
..empty_schema(SchemaKind::Enum)
};
let projected = schema_to_json_schema(&nullable_enum);
assert_eq!(projected["type"], json!(["string", "null"]));
assert_eq!(projected["enum"], json!(["draft", null]));
let binary = Schema {
kind: SchemaKind::Object,
format: Some("binary".to_owned()),
fields: BTreeMap::from([(
"data_base64".to_owned(),
Schema {
required: true,
..empty_schema(SchemaKind::String)
},
)]),
..empty_schema(SchemaKind::Object)
};
let projected = schema_to_json_schema(&binary);
assert_eq!(projected["additionalProperties"], false);
assert_eq!(projected["format"], "binary");
}
#[test]
fn optional_request_pair_uses_closed_presence_and_absence_branches() {
let mut tool = published_tool();
let selected = Schema {
kind: SchemaKind::Object,
format: Some(crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT.to_owned()),
fields: BTreeMap::from([
(
"body".to_owned(),
Schema {
required: true,
..empty_schema(SchemaKind::Object)
},
),
(
"content_type".to_owned(),
Schema {
kind: SchemaKind::Enum,
required: true,
enum_values: vec!["application/json".to_owned()],
..empty_schema(SchemaKind::Enum)
},
),
]),
..empty_schema(SchemaKind::Object)
};
let absent = Schema {
kind: SchemaKind::Object,
format: Some(crank_schema::CLOSED_OBJECT_SCHEMA_FORMAT.to_owned()),
..empty_schema(SchemaKind::Object)
};
tool.operation.input_schema = Schema {
kind: SchemaKind::Oneof,
variants: vec![selected, absent],
..empty_schema(SchemaKind::Oneof)
};
let Target::Rest(target) = &mut tool.operation.target;
target.request_contract = Some(RestRequestContract {
version: RestRequestContractVersion::V1,
body_field: "body".to_owned(),
selector_field: Some("content_type".to_owned()),
body_required: false,
variants: vec![RestRequestDescriptor {
media_type: "application/json".to_owned(),
schema_variant: 0,
}],
});
let schema = &tool_definitions(&tool)[0]["inputSchema"];
assert_eq!(schema["anyOf"][0]["additionalProperties"], false);
assert_eq!(
schema["anyOf"][0]["required"],
json!(["body", "content_type"])
);
assert_eq!(schema["anyOf"][1]["additionalProperties"], false);
assert!(
schema["anyOf"][1]["properties"]
.as_object()
.unwrap()
.is_empty()
);
}
#[test]
fn catalog_budget_uses_the_same_definitions_as_tools_list() {
let tool = published_tool();
@@ -154,10 +256,14 @@ fn operation() -> RegistryOperation {
method: HttpMethod::Get,
path_template: "/v2/rates".to_owned(),
static_headers: BTreeMap::new(),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: BTreeMap::new(),
}),
input_schema: input_schema(),
output_schema: Schema {
kind: SchemaKind::Object,
format: None,
description: None,
required: false,
nullable: false,
@@ -201,6 +307,7 @@ fn input_schema() -> Schema {
"base".to_owned(),
Schema {
kind: SchemaKind::String,
format: None,
description: None,
required: true,
nullable: false,
@@ -215,6 +322,7 @@ fn input_schema() -> Schema {
"mode".to_owned(),
Schema {
kind: SchemaKind::Enum,
format: None,
description: None,
required: false,
nullable: false,
@@ -228,6 +336,7 @@ fn input_schema() -> Schema {
Schema {
kind: SchemaKind::Object,
format: None,
description: None,
required: false,
nullable: false,
@@ -239,6 +348,21 @@ fn input_schema() -> Schema {
}
}
fn empty_schema(kind: SchemaKind) -> Schema {
Schema {
kind,
format: None,
description: None,
required: false,
nullable: false,
default_value: None,
fields: BTreeMap::new(),
items: None,
enum_values: Vec::new(),
variants: Vec::new(),
}
}
fn timestamp(value: &str) -> OffsetDateTime {
OffsetDateTime::parse(value, &Rfc3339).unwrap()
}