Files
crank/crates/crank-community-mcp/tests/unit/manifest.rs
T
bsodfather 54ce770682
CI / Rust Checks (pull_request) Failing after 13m41s
CI / UI Checks (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Deploy (pull_request) Skipped
Community Release / release (push) Failing after 13m33s
feat(epic3): deliver the accepted Epic 3 scope through Story 3.17
Recovery delivery of the accumulated, TL-accepted Epic 3 work that had never been
committed to Git (stories 3.6-3.17, see the crank board). Story 3.18 is not accepted
yet and is deliberately excluded: its logging surface, its capability registration,
its oracle projections and its tests are not part of this tree.

Accepted scope
- 3.6 typed static Resource Drafts; 3.7 publication and exact binding of static
  Resource Versions; 3.8 MCP discovery/read and revocation of static Resources;
- 3.9 Resource import/export in API and UI plus TLS dependency maintenance;
  3.10 REST-backed Resource templates; 3.11 shared REST read runtime and the MCP
  revision/capability foundation;
- 3.12 parameterised Prompt Drafts with preview; 3.13 Prompt publication and exact
  version binding to Agents; 3.14 MCP prompts; 3.15 Prompt import/export;
- 3.16 composite Prompts with published Resources (dependency content scan plus
  dynamic read through the accepted 3.11 runtime, admin preview and MCP prompts/get);
- 3.17 bounded MCP completion suggestions from typed published schemas and the
  resources/list admission fix for bound template publications.

Accepted evidence being reused (unchanged code paths)
- 3.16 candidate: core 7, admin-api 22, registry 4, mcp-server 4, UI 6; one final
  `just verify` run 1651 passed / 0 failed / 2 ignored.
- 3.17 candidate: full run 1672 passed / 0 failed / 2 ignored, QA targeted reruns and
  a real MCP Inspector 2.12.0 client smoke.

Delivery engineering in this commit
- CI: one event per change (feature branches are gated by their pull request, push
  runs only on main), story events run the changed packages, the full workspace suite
  stays the feature/release gate; no cache/sharding without a measured runner check.
- Release: the packaged archives, checksums and SBOM are now uploaded to the Gitea
  release entry of the tag instead of dying with the runner workspace.

Not included on purpose: Story 3.18 work, build caches, runtime databases, local
credentials and scratch evidence.

Refs: crank kanban t_e39d7263; baseline 1b6db09bd1.
2026-10-25 09:08:22 +00:00

371 lines
12 KiB
Rust

use std::collections::BTreeMap;
use std::time::Instant;
use crank_community_mcp::manifest::{
analyze_published_tool_catalog, catalog_tool_definitions, schema_to_json_schema,
tool_definitions,
};
use crank_core::{
ExecutionConfig, HttpMethod, Operation, OperationId, OperationSecurityLevel, OperationStatus,
Protocol, RestRequestContract, RestRequestContractVersion, RestRequestDescriptor, RestTarget,
Target, ToolAccessMode, ToolDescription, ToolSelectionPolicy, WorkspaceId,
};
use crank_mapping::MappingSet;
use crank_registry::{PublishedAgentCatalog, PublishedAgentTool, RegistryOperation};
use crank_schema::{Schema, SchemaKind};
use serde_json::json;
use time::{OffsetDateTime, format_description::well_known::Rfc3339};
#[test]
fn builds_tools_list_manifest_from_published_agent_tool() {
let definitions = tool_definitions(&published_tool());
assert_eq!(definitions.len(), 1);
let definition = &definitions[0];
assert_eq!(definition["name"], "frankfurter_latest_rate");
assert_eq!(definition["title"], "Последний курс валюты");
assert_eq!(
definition["description"],
"Возвращает последний курс валюты через Frankfurter."
);
assert_eq!(definition["inputSchema"]["type"], "object");
assert_eq!(definition["inputSchema"]["required"], json!(["base"]));
assert_eq!(
definition["inputSchema"]["properties"]["base"],
json!({ "type": "string" })
);
assert_eq!(
definition["inputSchema"]["properties"]["mode"],
json!({ "type": "string", "enum": ["latest", "historical"] })
);
}
#[test]
fn marks_destructive_tools_as_two_step_confirmation_calls() {
let mut tool = published_tool();
let Target::Rest(target) = &mut tool.operation.target;
target.method = HttpMethod::Delete;
let definitions = tool_definitions(&tool);
let definition = &definitions[0];
assert!(
definition["description"]
.as_str()
.unwrap()
.contains("_crank_confirmation_token")
);
assert_eq!(
definition["inputSchema"]["properties"]["_crank_confirmation_token"]["type"],
"string"
);
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();
let definitions = tool_definitions(&tool);
let analysis = analyze_published_tool_catalog(&[tool]).unwrap();
assert_eq!(analysis.budget.tool_count, definitions.len());
assert_eq!(
analysis.budget.serialized_bytes,
serde_json::to_vec(&definitions[0]).unwrap().len()
);
assert!(!analysis.budget.exceeds_recommended_budget);
}
#[test]
fn agent_catalog_discovery_profile_handles_200_agents_2000_operations_under_budget() {
const AGENT_COUNT: usize = 200;
const TOOLS_PER_AGENT: usize = 10;
const P95_BUDGET_MS: u128 = 150;
let mut durations = Vec::with_capacity(AGENT_COUNT);
let mut total_definitions = 0usize;
let started = Instant::now();
for agent_index in 0..AGENT_COUNT {
let tools = (0..TOOLS_PER_AGENT)
.map(|tool_index| {
let mut tool = published_tool();
tool.agent_id = format!("agent_{agent_index:03}").into();
tool.agent_slug = format!("agent-{agent_index:03}");
tool.operation.id =
OperationId::new(format!("op_{agent_index:03}_{tool_index:03}"));
tool.tool_name = format!("tool_{agent_index:03}_{tool_index:03}");
tool.tool_title = format!("Tool {agent_index:03}-{tool_index:03}");
tool
})
.collect::<Vec<_>>();
let catalog = PublishedAgentCatalog {
agent_version: 1,
catalog_revision: format!("agent-{agent_index:03}-revision-1"),
tool_selection_policy: ToolSelectionPolicy {
mode: ToolAccessMode::Direct,
..Default::default()
},
tools,
resources: Vec::new(),
prompts: Vec::new(),
};
let catalog_started = Instant::now();
let definitions = catalog_tool_definitions(&catalog);
durations.push(catalog_started.elapsed());
total_definitions += definitions.len();
}
durations.sort_unstable();
let p95 = durations[((durations.len() * 95).div_ceil(100)).saturating_sub(1)];
assert_eq!(total_definitions, AGENT_COUNT * TOOLS_PER_AGENT);
assert!(
p95.as_millis() <= P95_BUDGET_MS,
"agent catalog discovery p95={}ms total={}ms",
p95.as_millis(),
started.elapsed().as_millis()
);
}
fn published_tool() -> PublishedAgentTool {
PublishedAgentTool {
workspace_id: WorkspaceId::new("ws_01"),
workspace_slug: "default".to_owned(),
agent_id: "agent_01".into(),
agent_slug: "fx-agent".to_owned(),
operation: operation(),
tool_name: "frankfurter_latest_rate".to_owned(),
tool_title: "Последний курс валюты".to_owned(),
tool_description: "Возвращает последний курс валюты через Frankfurter.".to_owned(),
}
}
fn operation() -> RegistryOperation {
Operation {
id: OperationId::new("op_01"),
name: "frankfurter_latest_rate".to_owned(),
display_name: "Последний курс валюты".to_owned(),
category: "finance".to_owned(),
protocol: Protocol::Rest,
security_level: OperationSecurityLevel::Standard,
status: OperationStatus::Published,
version: 1,
target: Target::Rest(RestTarget {
base_url: "https://api.frankfurter.dev".to_owned(),
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,
default_value: None,
fields: BTreeMap::new(),
items: None,
enum_values: Vec::new(),
variants: Vec::new(),
},
input_mapping: MappingSet { rules: Vec::new() },
output_mapping: MappingSet { rules: Vec::new() },
execution_config: 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(),
},
tool_description: ToolDescription {
title: "Последний курс валюты".to_owned(),
description: "Возвращает последний курс валюты через Frankfurter.".to_owned(),
tags: Vec::new(),
examples: Vec::new(),
},
samples: None,
generated_draft: None,
config_export: None,
wizard_state: None,
created_at: timestamp("2026-06-20T00:00:00Z"),
updated_at: timestamp("2026-06-20T00:00:00Z"),
published_at: Some(timestamp("2026-06-20T00:00:00Z")),
}
}
fn input_schema() -> Schema {
let mut fields = BTreeMap::new();
fields.insert(
"base".to_owned(),
Schema {
kind: SchemaKind::String,
format: None,
description: None,
required: true,
nullable: false,
default_value: None,
fields: BTreeMap::new(),
items: None,
enum_values: Vec::new(),
variants: Vec::new(),
},
);
fields.insert(
"mode".to_owned(),
Schema {
kind: SchemaKind::Enum,
format: None,
description: None,
required: false,
nullable: false,
default_value: None,
fields: BTreeMap::new(),
items: None,
enum_values: vec!["latest".to_owned(), "historical".to_owned()],
variants: Vec::new(),
},
);
Schema {
kind: SchemaKind::Object,
format: None,
description: None,
required: false,
nullable: false,
default_value: None,
fields,
items: None,
enum_values: Vec::new(),
variants: Vec::new(),
}
}
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()
}