Files
crank/apps/mcp-server/tests/integration/mcp_prompts/composition.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

591 lines
22 KiB
Rust

//! Story 3.16 / FR-18 на границе MCP `prompts/get`: составной Prompt из опубликованных Resource.
//!
//! Всё идёт production-путём: реальный registry (create/publish Prompt, exact bindings, publish
//! Agent), реальный artifact root для опубликованного Resource и настоящий MCP endpoint.
//!
//! Проверяется:
//! - точный pinned-текст вставляется дословно внутрь объявленного сообщения, роли и число
//! сообщений не меняются (AC4/AC5);
//! - новая опубликованная версия Resource не меняет то, что получает агент (AC8);
//! - недоступная (отозванная) зависимость — структурированный отказ без `messages` (AC6).
use std::{
fs,
path::PathBuf,
sync::atomic::{AtomicU64, Ordering},
time::Duration,
};
use crank_artifacts::ArtifactStore;
use crank_core::{
Agent, AgentId, AgentStatus, AgentVersion, HttpMethod, OperationSafetyClass,
OperationSafetyPolicy, PlatformApiKeyScope, RestTarget, Target, ToolSelectionPolicy,
ids::{PromptId, ResourceId},
prompt::{PromptDefinition, PromptSensitivity},
resource::template::TemplateSource,
};
use crank_mapping::{MappingRule, MappingSet};
use crank_registry::{
PostgresRegistry, PublishRequest,
model::{
AgentPromptBinding, CreatePromptDraftRequest, PublishPromptRequest,
resource::{
CreateResourceDraftRequest, CreateResourceTemplateDraftRequest,
PublishResourceTemplateVersionRequest, PublishResourceVersionRequest,
},
},
};
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use time::OffsetDateTime;
use super::super::common::{
agent_mcp_url, build_test_app_with_artifacts, create_platform_api_key, object_schema,
spawn_mcp_server, test_operation, test_registry, test_workspace_id,
};
use super::fixtures::{
META_CLIENT_CAPABILITIES, META_CLIENT_INFO, META_PROTOCOL_VERSION, MODERN_REVISION,
PromptEndpoint,
};
const AGENT_SLUG: &str = "composed-prompts";
const PINNED_V1: &str = "PINNED CHANGELOG v1";
const PINNED_V2: &str = "PINNED CHANGELOG v2";
static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
struct TestRoot(PathBuf);
impl TestRoot {
fn new() -> Self {
let path = std::env::temp_dir().join(format!(
"crank-mcp-prompt-composition-{}-{}",
std::process::id(),
NEXT_ROOT.fetch_add(1, Ordering::Relaxed)
));
fs::create_dir_all(&path).expect("artifact root must be creatable");
// Тот же контракт приватности, что у production root: 0700.
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(&path, fs::Permissions::from_mode(0o700))
.expect("artifact root must be 0700");
}
Self(path)
}
}
impl Drop for TestRoot {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.0);
}
}
/// Публикует static Resource через production-путь 3.6/3.7 в реальном artifact root.
async fn publish_resource(
registry: &PostgresRegistry,
store: &ArtifactStore,
resource_id: &str,
bytes: &[u8],
) -> u32 {
let id = ResourceId::new(resource_id);
let artifact = store
.put_registered(bytes)
.expect("fixture bytes are registered durably");
if registry
.get_resource_draft(test_workspace_id().as_str(), &id)
.await
.is_ok()
{
let current = registry
.get_resource_draft(test_workspace_id().as_str(), &id)
.await
.expect("current draft reads");
registry
.update_resource_draft(
crank_registry::model::resource::UpdateResourceDraftRequest {
workspace_id: test_workspace_id(),
resource_id: id.clone(),
description: "next version".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
expected_updated_at: current.resource.updated_at,
artifact,
},
)
.await
.expect("next draft version is created");
} else {
registry
.create_resource_draft(CreateResourceDraftRequest {
workspace_id: test_workspace_id(),
resource_id: id.clone(),
uri: format!("crank://resources/{resource_id}"),
name: resource_id.to_owned(),
description: String::new(),
kind: "text".to_owned(),
mime_type: "text/plain".to_owned(),
sensitivity: "internal".to_owned(),
artifact,
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("resource draft is created");
}
let current = registry
.get_resource_draft(test_workspace_id().as_str(), &id)
.await
.expect("draft reads");
registry
.publish_resource_version(PublishResourceVersionRequest {
workspace_id: test_workspace_id(),
resource_id: id,
expected_updated_at: current.resource.updated_at,
expected_version: current.version.version,
expected_digest: current.version.digest.clone(),
expected_size_bytes: current.version.size_bytes,
artifact: store
.put_registered(bytes)
.expect("fixture bytes are registered durably"),
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("resource version publishes")
.version
}
fn composed_definition(resource_id: &str, version: u32) -> PromptDefinition {
PromptDefinition::parse(&json!({
"name": "release-notes",
"description": "Composed release notes",
"arguments": [{"name": "channel", "schema": {"type": "string"}, "required": true}],
"messages": [
{"role": "system", "content": "Summarise only the attached document."},
{"role": "user", "content": "Channel: {{channel}}", "resource_refs": [0]}
],
"dependencies": [{"resource_id": resource_id, "version": version}]
}))
.expect("composed definition is valid")
}
/// Стенд: опубликованный Resource v1, составной Prompt, exact binding и опубликованный Agent.
///
/// Возвращает endpoint, store и корень артефактов: `ArtifactStore` клонируется в приложение, поэтому
/// последующая публикация новой версии Resource идёт в тот же immutable root.
async fn composed_endpoint() -> (PromptEndpoint, ArtifactStore, TestRoot) {
let root = TestRoot::new();
let store = ArtifactStore::open(root.0.clone()).expect("artifact store opens");
let registry = test_registry().await;
let resource_id = "res_story316_mcp_composed";
let version = publish_resource(&registry, &store, resource_id, PINNED_V1.as_bytes()).await;
let endpoint = bound_prompt_endpoint(
registry,
store.clone(),
PromptId::new("prm_story316_mcp_composed"),
composed_definition(resource_id, version),
)
.await;
(endpoint, store, root)
}
/// Опубликованный Prompt + exact binding в опубликованном Agent и живой MCP endpoint.
async fn bound_prompt_endpoint(
registry: PostgresRegistry,
store: ArtifactStore,
prompt_id: PromptId,
definition: PromptDefinition,
) -> PromptEndpoint {
let created = registry
.create_prompt_draft(CreatePromptDraftRequest {
workspace_id: test_workspace_id(),
prompt_id: prompt_id.clone(),
sensitivity: PromptSensitivity::Internal,
definition,
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("composed prompt draft is created");
registry
.publish_prompt_draft(PublishPromptRequest {
workspace_id: test_workspace_id(),
prompt_id: prompt_id.clone(),
expected_updated_at: created.updated_at,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("composed prompt publishes");
let agent_id = AgentId::new(format!("agent_{AGENT_SLUG}"));
let now = OffsetDateTime::now_utc();
registry
.create_agent(crank_registry::CreateAgentRequest {
agent: &Agent {
id: agent_id.clone(),
workspace_id: test_workspace_id(),
slug: AGENT_SLUG.to_owned(),
display_name: AGENT_SLUG.to_owned(),
description: "Story 3.16 composed Prompt fixture".to_owned(),
status: AgentStatus::Draft,
current_draft_version: 1,
latest_published_version: None,
created_at: now,
updated_at: now,
published_at: None,
},
version: &AgentVersion {
agent_id: agent_id.clone(),
version: 1,
status: AgentStatus::Draft,
instructions: json!({}),
tool_selection_policy: ToolSelectionPolicy::default(),
created_at: now,
},
bindings: &[],
})
.await
.expect("draft Agent is created");
registry
.save_agent_catalog_config_editable_with_prompts(
crank_registry::model::SaveAgentCatalogConfigRequest {
workspace_id: &test_workspace_id(),
agent_id: &agent_id,
agent_version: 1,
bindings: &[],
tool_selection_policy: &ToolSelectionPolicy::default(),
resource_bindings: &[],
expected_state: None,
},
&[AgentPromptBinding {
prompt_id: prompt_id.clone(),
prompt_version: 1,
}],
)
.await
.expect("exact published Prompt binding is accepted");
registry
.publish_agent(crank_registry::PublishAgentRequest {
workspace_id: &test_workspace_id(),
agent_id: &agent_id,
version: 1,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("alice"),
expected_state: None,
})
.await
.expect("bound Agent publishes");
let api_key = create_platform_api_key(
&registry,
AGENT_SLUG,
"mcp-prompts-composed",
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
)
.await;
let base_url = spawn_mcp_server(build_test_app_with_artifacts(
registry.clone(),
Duration::from_millis(0),
Some("https://crank.example.com".to_owned()),
store,
))
.await;
PromptEndpoint {
client: reqwest::Client::new(),
mcp_url: agent_mcp_url(&base_url, AGENT_SLUG),
base_url,
api_key,
registry,
greeting_id: prompt_id,
archived_id: PromptId::new("prm_story316_unused_archived"),
archived_updated_at: now,
}
}
/// Один modern `prompts/get` запрос через тот же adapter, что у остальных Prompt-тестов.
async fn get(endpoint: &PromptEndpoint, channel: &str) -> Value {
let headers = [
("MCP-Protocol-Version", MODERN_REVISION),
("Mcp-Method", "prompts/get"),
("Mcp-Name", "release-notes"),
];
let params = json!({
"name": "release-notes",
"arguments": {"channel": channel},
"_meta": {
META_PROTOCOL_VERSION: MODERN_REVISION,
META_CLIENT_CAPABILITIES: {},
META_CLIENT_INFO: {"name": "crank-prompts-story316", "version": "0.1.0"}
}
});
let response = super::super::common::post_jsonrpc_with_headers(
&endpoint.client,
&agent_mcp_url(&endpoint.base_url, AGENT_SLUG),
&endpoint.api_key,
&headers,
json!({"jsonrpc": "2.0", "id": 7, "method": "prompts/get", "params": params}),
)
.await;
super::fixtures::json_body(response).await
}
fn message_texts(body: &Value) -> Vec<(String, String)> {
body["result"]["messages"]
.as_array()
.unwrap_or_else(|| panic!("prompts/get must carry messages: {body}"))
.iter()
.map(|message| {
(
message["role"].as_str().unwrap_or_default().to_owned(),
message["content"]["text"]
.as_str()
.unwrap_or_default()
.to_owned(),
)
})
.collect()
}
#[tokio::test]
async fn get_inserts_pinned_text_inside_the_declared_message() {
let (endpoint, _store, _root) = composed_endpoint().await;
let body = get(&endpoint, "ops").await;
let messages = message_texts(&body);
assert_eq!(
messages.len(),
2,
"the declared message count is unchanged: {body}"
);
assert_eq!(messages[0].0, "system");
assert_eq!(
messages[0].1, "Summarise only the attached document.",
"the system message never receives document text: {body}"
);
assert_eq!(messages[1].0, "user");
assert_eq!(
messages[1].1,
format!("Channel: ops\n\n{PINNED_V1}"),
"the pinned text is inserted verbatim after the rendered template: {body}"
);
assert!(
body["result"]["messages"][1].get("tool_calls").is_none(),
"content never becomes a tool call: {body}"
);
}
#[tokio::test]
async fn get_keeps_the_pinned_version_after_a_new_resource_version() {
let (endpoint, store, _root) = composed_endpoint().await;
// Новая опубликованная версия того же Resource не переписывает пин.
publish_resource(
&endpoint.registry,
&store,
"res_story316_mcp_composed",
PINNED_V2.as_bytes(),
)
.await;
let body = get(&endpoint, "ops").await;
let messages = message_texts(&body);
assert!(
messages[1].1.contains(PINNED_V1),
"the agent keeps receiving the pinned version: {body}"
);
assert!(
!messages[1].1.contains(PINNED_V2),
"a newer Resource version requires a new Prompt publication: {body}"
);
}
#[tokio::test]
async fn get_unavailable_dependency_is_structured_without_messages() {
let (endpoint, _store, _root) = composed_endpoint().await;
endpoint
.registry
.revoke_resource(crank_registry::model::resource::RevokeResourceRequest {
workspace_id: test_workspace_id(),
resource_id: ResourceId::new("res_story316_mcp_composed"),
actor_user_id: "user_default_owner".to_owned(),
request_id: "story316-mcp".to_owned(),
trace_id: "story316-mcp".to_owned(),
revoked_at: OffsetDateTime::now_utc(),
})
.await
.expect("revocation is the accepted 3.8 path");
let body = get(&endpoint, "ops").await;
assert!(
body.get("result").is_none(),
"no partial prompt is returned: {body}"
);
let message = body["error"]["message"].as_str().unwrap_or_default();
assert!(
message.contains("dependencies[0]"),
"the failure names the declaration position: {body}"
);
assert!(
!serde_json::to_string(&body)
.unwrap_or_default()
.contains(PINNED_V1),
"no dependency content appears in the failure: {body}"
);
}
// ---------------------------------------------------------------------------
// AC6 (§4): dynamic (template) dependency читается runtime 3.11 через prompts/get
// ---------------------------------------------------------------------------
const DYNAMIC_RESOURCE_ID: &str = "res_story316_mcp_dynamic";
const DYNAMIC_DEFAULT_ID: &str = "order-42";
/// Upstream шаблона: `GET /orders/{order_id}` → `{"id": "<order_id>"}`.
async fn spawn_orders_upstream() -> String {
use axum::{Router, extract::Path, routing::get};
let app = Router::new().route(
"/orders/{order_id}",
get(|Path(order_id): Path<String>| async move { axum::Json(json!({ "id": order_id })) }),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
.await
.expect("upstream must bind a loopback port");
let address = listener.local_addr().expect("upstream address");
tokio::spawn(async move {
axum::serve(listener, app).await.expect("upstream serves");
});
format!("http://{address}")
}
/// Стенд динамической зависимости: опубликованная read Operation, опубликованный template
/// Resource с параметром по умолчанию, составной Prompt и опубликованный Agent.
async fn dynamic_endpoint() -> (PromptEndpoint, TestRoot) {
let root = TestRoot::new();
let store = ArtifactStore::open(root.0.clone()).expect("artifact store opens");
let registry = test_registry().await;
let upstream = spawn_orders_upstream().await;
let mut operation = test_operation(&upstream, "story316_prompt_dynamic");
operation.id = crank_core::OperationId::new("op_story316_prompt_dynamic");
operation.target = Target::Rest(RestTarget {
base_url: upstream,
method: HttpMethod::Get,
path_template: "/orders/{order_id}".to_owned(),
static_headers: Default::default(),
request_contract: None,
response_contract: Vec::new(),
multipart_field_mime_types: Default::default(),
});
operation.input_schema = object_schema("order_id");
operation.execution_config.timeout_ms = 1_000;
operation.execution_config.safety = Some(OperationSafetyPolicy {
class: OperationSafetyClass::Read,
confirmation: None,
});
operation.input_mapping = MappingSet {
rules: vec![MappingRule {
source: "$.mcp.order_id".to_owned(),
target: "$.request.path.order_id".to_owned(),
required: true,
default_value: None,
transform: None,
condition: None,
notes: None,
}],
};
registry
.create_operation(&test_workspace_id(), &operation, Some("alice"))
.await
.expect("GET Read operation is created through the registry API");
registry
.publish_operation(PublishRequest {
workspace_id: &test_workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &OffsetDateTime::now_utc(),
published_by: Some("alice"),
})
.await
.expect("GET Read operation exact version publishes");
let resource_id = ResourceId::new(DYNAMIC_RESOURCE_ID);
let definition_value = json!({
"operation_id": operation.id.to_string(),
"operation_version": 1,
"uri_template": "crank://orders/{order_id}",
"parameters": [{
"name": "order_id",
"input_path": "input.order_id",
"schema": { "type": "string", "required": true, "default_value": DYNAMIC_DEFAULT_ID }
}],
"cache": { "ttl_ms": 60000, "vary": ["order_id"], "max_bytes": 65536 },
"failure": { "outcome": "error" }
});
let definition = serde_json::to_string(
&TemplateSource::parse(&definition_value).expect("template source is valid"),
)
.expect("normalized definition serializes canonically");
let digest = format!("{:x}", Sha256::digest(definition.as_bytes()));
let draft = registry
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
workspace_id: test_workspace_id(),
resource_id: resource_id.clone(),
uri: "crank://templates/story316-order".to_owned(),
name: "story316_order".to_owned(),
description: "Story 3.16 dynamic dependency".to_owned(),
kind: "json".to_owned(),
mime_type: "application/json".to_owned(),
sensitivity: "internal".to_owned(),
definition_json: definition,
definition_digest: digest.clone(),
created_at: OffsetDateTime::now_utc(),
})
.await
.expect("template Draft is created through the registry API");
registry
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
workspace_id: test_workspace_id(),
resource_id: resource_id.clone(),
expected_updated_at: draft.snapshot.resource.updated_at,
expected_version: draft.snapshot.version.version,
expected_digest: digest,
published_at: OffsetDateTime::now_utc(),
})
.await
.expect("template exact version publishes");
let endpoint = bound_prompt_endpoint(
registry,
store,
PromptId::new("prm_story316_mcp_dynamic"),
composed_definition(DYNAMIC_RESOURCE_ID, 1),
)
.await;
(endpoint, root)
}
/// AT-3.16-06 (§4): `prompts/get` читает «живой» документ через Resource runtime; вывод вставлен
/// дословно внутри объявленного сообщения, роли и число сообщений не меняются.
#[tokio::test]
async fn get_reads_a_dynamic_dependency_through_the_resource_runtime() {
let (endpoint, _root) = dynamic_endpoint().await;
let body = get(&endpoint, "ops").await;
let messages = message_texts(&body);
assert_eq!(
messages.len(),
2,
"a dependency cannot add or remove a declared message: {body}"
);
assert_eq!(messages[0].0, "system");
assert_eq!(
messages[0].1, "Summarise only the attached document.",
"the system message never receives document text: {body}"
);
assert_eq!(messages[1].0, "user");
assert_eq!(
messages[1].1,
format!("Channel: ops\n\n{{\"id\":\"{DYNAMIC_DEFAULT_ID}\"}}"),
"the pinned template output is inserted verbatim after one blank line: {body}"
);
assert!(
body["result"]["messages"][1].get("tool_calls").is_none(),
"content never becomes a tool call: {body}"
);
}