[skip ci] wip: preserve Hermes crank development checkpoint
Owner-authorized recovery of accumulated source changes.
Includes accepted work and in-progress changes; NOT a release or acceptance.
Parent baseline 1b6db09bd1. Runtime data, build caches and local credentials excluded.
This commit is contained in:
1 parent
1b6db09bd1
commit
301dce301a
357 files changed
+118831
-5113
No files matched your search
@@ -0,0 +1,558 @@
|
||||
//! Story 3.17 acceptance fixtures: a real MCP endpoint over a real PostgreSQL registry.
|
||||
//!
|
||||
//! Everything is the production path: `build_test_app` + the real
|
||||
//! `CommunityMachineCredentialVerifier`, published Prompt versions created through the registry
|
||||
//! (`create_prompt_draft` → `publish_prompt_draft`), one published Resource template with a typed
|
||||
//! enum parameter (`create_resource_template_draft` → `publish_resource_template_version`) whose
|
||||
//! declared Read Operation is published too, exact bindings written through
|
||||
//! `save_agent_catalog_config_editable_with_prompts`, and an Agent published with `publish_agent`.
|
||||
//! No route stub, no fake service, no row written behind the registry's back.
|
||||
//!
|
||||
//! Bounded fixture set:
|
||||
//! - `greeting` (bound to `completion-agent`) — argument `name` (plain string, no enumeration) and
|
||||
//! `tone` (enum `warm|dry`, default `warm`);
|
||||
//! - `completion-orders` (bound template) — URI template `crank://completion-orders/{region}` with an
|
||||
//! enumerated `region` parameter (`eu|us|apac`);
|
||||
//! - `draft-prompt` — Draft only, never published;
|
||||
//! - `unbound-prompt` — published but not bound to any Agent;
|
||||
//! - `other-agent-prompt` and `crank://completion-other/{region}` — bound to the other Agent of the
|
||||
//! same workspace (scope isolation).
|
||||
//!
|
||||
//! Test-owned identifiers are distinctive on purpose: the AC1 cases assert that none of these names or
|
||||
//! URIs is echoed by an unavailable completion.
|
||||
|
||||
#![allow(dead_code)]
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use crank_core::ids::{PromptId, ResourceId};
|
||||
use crank_core::prompt::{PromptDefinition, PromptSensitivity};
|
||||
use crank_core::resource::TemplateSource;
|
||||
use crank_core::{
|
||||
Agent, AgentId, AgentStatus, AgentVersion, HttpMethod, PlatformApiKeyScope, RestTarget, Target,
|
||||
ToolSelectionPolicy, WorkspaceId,
|
||||
};
|
||||
use crank_mapping::{MappingRule, MappingSet};
|
||||
use crank_registry::model::{
|
||||
AgentPromptBinding, CreatePromptDraftRequest, CreateResourceTemplateDraftRequest,
|
||||
PublishPromptRequest, PublishResourceTemplateVersionRequest, SaveAgentCatalogConfigRequest,
|
||||
};
|
||||
use crank_registry::{
|
||||
AgentResourceBinding, CreateAgentRequest, PostgresRegistry, PublishAgentRequest, PublishRequest,
|
||||
};
|
||||
use serde_json::{Value, json};
|
||||
use sha2::{Digest, Sha256};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use super::super::common::{
|
||||
agent_mcp_url, build_test_app, create_platform_api_key, initialize_session, object_schema,
|
||||
post_jsonrpc_with_headers, spawn_mcp_server, test_operation, test_registry, test_workspace_id,
|
||||
};
|
||||
|
||||
pub(super) const MODERN_REVISION: &str = "2026-07-28";
|
||||
pub(super) const LEGACY_REVISION: &str = "2025-11-25";
|
||||
pub(super) const META_PROTOCOL_VERSION: &str = "io.modelcontextprotocol/protocolVersion";
|
||||
pub(super) const META_CLIENT_CAPABILITIES: &str = "io.modelcontextprotocol/clientCapabilities";
|
||||
pub(super) const META_CLIENT_INFO: &str = "io.modelcontextprotocol/clientInfo";
|
||||
|
||||
pub(super) const AGENT_SLUG: &str = "completion-agent";
|
||||
pub(super) const OTHER_AGENT_SLUG: &str = "completion-other";
|
||||
|
||||
/// The exact URI template of the bound template fixture.
|
||||
pub(super) const BOUND_TEMPLATE_URI: &str = "crank://completion-orders/{region}";
|
||||
/// The exact URI template bound only to the other Agent.
|
||||
pub(super) const FOREIGN_TEMPLATE_URI: &str = "crank://completion-other/{region}";
|
||||
|
||||
/// The one safe wire detail of a malformed completion request.
|
||||
pub(super) const INVALID_PARAMS: &str = "invalid completion/complete parameters";
|
||||
/// The one safe wire detail of an unavailable completion reference.
|
||||
pub(super) const NOT_AVAILABLE: &str = "the completion reference is not available";
|
||||
|
||||
fn greeting_definition() -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name": "greeting",
|
||||
"description": "Greets the customer",
|
||||
"arguments": [
|
||||
{"name": "name", "schema": {"type": "string"}, "required": true},
|
||||
{
|
||||
"name": "tone",
|
||||
"schema": {"type": "string", "enum": ["warm", "dry"]},
|
||||
"required": false,
|
||||
"default": "warm"
|
||||
}
|
||||
],
|
||||
"messages": [{"role": "user", "content": "Hello {{name}}"}]
|
||||
}))
|
||||
.expect("the greeting definition is valid")
|
||||
}
|
||||
|
||||
fn simple_definition(name: &str, description: &str, content: &str) -> PromptDefinition {
|
||||
PromptDefinition::parse(&json!({
|
||||
"name": name,
|
||||
"description": description,
|
||||
"arguments": [],
|
||||
"messages": [{"role": "user", "content": content}]
|
||||
}))
|
||||
.expect("the simple definition is valid")
|
||||
}
|
||||
|
||||
pub(super) struct CompletionEndpoint {
|
||||
pub(super) client: reqwest::Client,
|
||||
pub(super) mcp_url: String,
|
||||
pub(super) base_url: String,
|
||||
pub(super) api_key: String,
|
||||
pub(super) registry: PostgresRegistry,
|
||||
}
|
||||
|
||||
impl CompletionEndpoint {
|
||||
/// One modern `completion/complete` request with the required per-request identity. The method
|
||||
/// declares no `Mcp-Name` (its `ref` is a union), so only `Mcp-Method` travels with it.
|
||||
pub(super) async fn modern(&self, params: Value) -> Value {
|
||||
self.modern_for(AGENT_SLUG, &self.api_key, params).await
|
||||
}
|
||||
|
||||
pub(super) async fn modern_for(&self, agent_slug: &str, api_key: &str, params: Value) -> Value {
|
||||
let mut params = params;
|
||||
params["_meta"] = json!({
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: {"name": "crank-completion-atdd", "version": "0.1.0"}
|
||||
});
|
||||
let response = post_jsonrpc_with_headers(
|
||||
&self.client,
|
||||
&agent_mcp_url(&self.base_url, agent_slug),
|
||||
api_key,
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", "completion/complete"),
|
||||
],
|
||||
json!({"jsonrpc": "2.0", "id": 21, "method": "completion/complete", "params": params}),
|
||||
)
|
||||
.await;
|
||||
json_body(response).await
|
||||
}
|
||||
|
||||
/// The same request inside the initialized legacy session of the chosen Agent.
|
||||
pub(super) async fn legacy(&self, params: Value) -> Value {
|
||||
self.legacy_for(AGENT_SLUG, &self.api_key, params).await
|
||||
}
|
||||
|
||||
pub(super) async fn legacy_for(&self, agent_slug: &str, api_key: &str, params: Value) -> Value {
|
||||
let session = self.legacy_session_for(agent_slug, api_key).await;
|
||||
let response = self
|
||||
.client
|
||||
.post(agent_mcp_url(&self.base_url, agent_slug))
|
||||
.header(
|
||||
reqwest::header::ACCEPT,
|
||||
"application/json, text/event-stream",
|
||||
)
|
||||
.header(reqwest::header::AUTHORIZATION, format!("Bearer {api_key}"))
|
||||
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
||||
.header("MCP-Session-Id", session)
|
||||
.json(&json!({"jsonrpc": "2.0", "id": 22, "method": "completion/complete", "params": params}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
json_body(response).await
|
||||
}
|
||||
|
||||
/// One modern request of an arbitrary method (advertisement probes); the request declares its
|
||||
/// `Mcp-Method` header exactly as the pinned transport requires.
|
||||
pub(super) async fn modern_method(&self, method: &str, params: Value) -> Value {
|
||||
let mut params = params;
|
||||
params["_meta"] = json!({
|
||||
META_PROTOCOL_VERSION: MODERN_REVISION,
|
||||
META_CLIENT_CAPABILITIES: {},
|
||||
META_CLIENT_INFO: {"name": "crank-completion-atdd", "version": "0.1.0"}
|
||||
});
|
||||
let response = post_jsonrpc_with_headers(
|
||||
&self.client,
|
||||
&self.mcp_url,
|
||||
&self.api_key,
|
||||
&[
|
||||
("MCP-Protocol-Version", MODERN_REVISION),
|
||||
("Mcp-Method", method),
|
||||
],
|
||||
json!({"jsonrpc": "2.0", "id": 31, "method": method, "params": params}),
|
||||
)
|
||||
.await;
|
||||
json_body(response).await
|
||||
}
|
||||
|
||||
/// The legacy `initialize` response of this Agent route (the legacy advertisement probe).
|
||||
pub(super) async fn legacy_initialize(&self) -> Value {
|
||||
let response = self
|
||||
.client
|
||||
.post(&self.mcp_url)
|
||||
.header(
|
||||
reqwest::header::ACCEPT,
|
||||
"application/json, text/event-stream",
|
||||
)
|
||||
.header(
|
||||
reqwest::header::AUTHORIZATION,
|
||||
format!("Bearer {}", self.api_key),
|
||||
)
|
||||
.json(&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 32,
|
||||
"method": "initialize",
|
||||
"params": {"protocolVersion": LEGACY_REVISION, "capabilities": {}}
|
||||
}))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
json_body(response).await
|
||||
}
|
||||
|
||||
pub(super) async fn legacy_session_for(&self, agent_slug: &str, api_key: &str) -> String {
|
||||
initialize_session(
|
||||
&self.client,
|
||||
&agent_mcp_url(&self.base_url, agent_slug),
|
||||
api_key,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// The same completion case on the requested supported revision.
|
||||
pub(super) async fn on_revision(&self, revision: &str, params: Value) -> Value {
|
||||
match revision {
|
||||
MODERN_REVISION => self.modern(params).await,
|
||||
LEGACY_REVISION => self.legacy(params).await,
|
||||
other => panic!("{other} is not a supported protocol revision"),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn other_agent_key(&self) -> String {
|
||||
create_platform_api_key(
|
||||
&self.registry,
|
||||
OTHER_AGENT_SLUG,
|
||||
"mcp-completion-other",
|
||||
&[PlatformApiKeyScope::Read],
|
||||
)
|
||||
.await
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn json_body(response: reqwest::Response) -> Value {
|
||||
let status = response.status();
|
||||
let body = response.text().await.unwrap();
|
||||
serde_json::from_str(&body)
|
||||
.unwrap_or_else(|error| panic!("expected a JSON-RPC body, got {status} {body:?}: {error}"))
|
||||
}
|
||||
|
||||
async fn create_published_prompt(
|
||||
registry: &PostgresRegistry,
|
||||
prompt_id: &PromptId,
|
||||
definition: PromptDefinition,
|
||||
) {
|
||||
let created_at = 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("the Prompt Draft is created")
|
||||
.updated_at;
|
||||
registry
|
||||
.publish_prompt_draft(PublishPromptRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
prompt_id: prompt_id.clone(),
|
||||
expected_updated_at: created_at,
|
||||
published_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the Prompt publishes as an immutable version");
|
||||
}
|
||||
|
||||
/// One published Read Operation with an enumerated `region` path parameter, the exact target the
|
||||
/// bound template declares.
|
||||
async fn publish_region_operation(registry: &PostgresRegistry, name: &str) {
|
||||
let mut operation = test_operation("http://127.0.0.1:9", name);
|
||||
operation.id = crank_core::OperationId::new(format!("op_{name}"));
|
||||
operation.display_name = "Region lookup".to_owned();
|
||||
operation.target = Target::Rest(RestTarget {
|
||||
base_url: "http://127.0.0.1:9".to_owned(),
|
||||
method: HttpMethod::Get,
|
||||
path_template: "/regions/{region}".to_owned(),
|
||||
static_headers: Default::default(),
|
||||
request_contract: None,
|
||||
response_contract: Vec::new(),
|
||||
multipart_field_mime_types: Default::default(),
|
||||
});
|
||||
operation.input_schema = object_schema("region");
|
||||
operation
|
||||
.input_schema
|
||||
.fields
|
||||
.get_mut("region")
|
||||
.unwrap()
|
||||
.enum_values = vec!["eu".to_owned(), "us".to_owned(), "apac".to_owned()];
|
||||
operation.input_mapping = MappingSet {
|
||||
rules: vec![MappingRule {
|
||||
source: "$.mcp.region".to_owned(),
|
||||
target: "$.request.path.region".to_owned(),
|
||||
required: true,
|
||||
default_value: None,
|
||||
transform: None,
|
||||
condition: None,
|
||||
notes: None,
|
||||
}],
|
||||
};
|
||||
registry
|
||||
.create_operation(&test_workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.expect("the 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("the Read Operation exact version publishes");
|
||||
}
|
||||
|
||||
/// One published Resource template with an enumerated `region` parameter.
|
||||
async fn publish_template(
|
||||
registry: &PostgresRegistry,
|
||||
resource_id: &ResourceId,
|
||||
uri_template: &str,
|
||||
operation_name: &str,
|
||||
) {
|
||||
let definition = json!({
|
||||
"operation_id": format!("op_{operation_name}"),
|
||||
"operation_version": 1,
|
||||
"uri_template": uri_template,
|
||||
"parameters": [{
|
||||
"name": "region",
|
||||
"input_path": "input.region",
|
||||
"schema": {
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"enum_values": ["eu", "us", "apac"]
|
||||
}
|
||||
}],
|
||||
"cache": {"ttl_ms": 60_000, "vary": ["region"], "max_bytes": 65_536},
|
||||
"failure": {"outcome": "error"}
|
||||
});
|
||||
let source = TemplateSource::parse(&definition)
|
||||
.expect("the template fixture satisfies the Story 3.10 source contract");
|
||||
let definition_json =
|
||||
serde_json::to_string(&source).expect("the normalized definition serializes canonically");
|
||||
let digest = format!("{:x}", Sha256::digest(definition_json.as_bytes()));
|
||||
let draft = registry
|
||||
.create_resource_template_draft(CreateResourceTemplateDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
resource_id: resource_id.clone(),
|
||||
uri: format!("crank://templates/{operation_name}"),
|
||||
name: format!("{operation_name}_template"),
|
||||
description: "Bound completion fixture template".to_owned(),
|
||||
kind: "text".to_owned(),
|
||||
mime_type: "application/json".to_owned(),
|
||||
sensitivity: "internal".to_owned(),
|
||||
definition_json: definition_json.clone(),
|
||||
definition_digest: digest.clone(),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the 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("the template exact version publishes");
|
||||
}
|
||||
|
||||
async fn create_agent(registry: &PostgresRegistry, agent_slug: &str) -> AgentId {
|
||||
let agent_id = AgentId::new(format!("agent_{agent_slug}"));
|
||||
let now = OffsetDateTime::now_utc();
|
||||
registry
|
||||
.create_agent(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.17 completion 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("the draft Agent is created");
|
||||
agent_id
|
||||
}
|
||||
|
||||
async fn bind_snapshot(
|
||||
registry: &PostgresRegistry,
|
||||
agent_id: &AgentId,
|
||||
prompts: &[AgentPromptBinding],
|
||||
resources: &[AgentResourceBinding],
|
||||
) {
|
||||
registry
|
||||
.save_agent_catalog_config_editable_with_prompts(
|
||||
SaveAgentCatalogConfigRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id,
|
||||
agent_version: 1,
|
||||
bindings: &[],
|
||||
tool_selection_policy: &ToolSelectionPolicy::default(),
|
||||
resource_bindings: resources,
|
||||
expected_state: None,
|
||||
},
|
||||
prompts,
|
||||
)
|
||||
.await
|
||||
.expect("the exact bound snapshot is accepted");
|
||||
registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &test_workspace_id(),
|
||||
agent_id,
|
||||
version: 1,
|
||||
published_at: &OffsetDateTime::now_utc(),
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.expect("the bound Agent publishes");
|
||||
}
|
||||
|
||||
/// Publish the whole fixture set and start the real MCP server.
|
||||
pub(super) async fn completion_endpoint() -> CompletionEndpoint {
|
||||
let registry = test_registry().await;
|
||||
let greeting_id = PromptId::new("prm_completion_greeting");
|
||||
let draft_id = PromptId::new("prm_completion_draft");
|
||||
let unbound_id = PromptId::new("prm_completion_unbound");
|
||||
let other_id = PromptId::new("prm_completion_other");
|
||||
|
||||
create_published_prompt(®istry, &greeting_id, greeting_definition()).await;
|
||||
registry
|
||||
.create_prompt_draft(CreatePromptDraftRequest {
|
||||
workspace_id: test_workspace_id(),
|
||||
prompt_id: draft_id,
|
||||
sensitivity: PromptSensitivity::Internal,
|
||||
definition: simple_definition("draft-prompt", "Never published", "Draft content."),
|
||||
created_at: OffsetDateTime::now_utc(),
|
||||
})
|
||||
.await
|
||||
.expect("the Draft-only Prompt is created");
|
||||
create_published_prompt(
|
||||
®istry,
|
||||
&unbound_id,
|
||||
simple_definition(
|
||||
"unbound-prompt",
|
||||
"Published, never bound",
|
||||
"Unbound content.",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
create_published_prompt(
|
||||
®istry,
|
||||
&other_id,
|
||||
simple_definition(
|
||||
"other-agent-prompt",
|
||||
"Bound elsewhere",
|
||||
"Other agent secret.",
|
||||
),
|
||||
)
|
||||
.await;
|
||||
|
||||
publish_region_operation(®istry, "completion_region_lookup").await;
|
||||
publish_region_operation(®istry, "completion_other_region_lookup").await;
|
||||
let bound_template = ResourceId::new("res_completion_orders");
|
||||
publish_template(
|
||||
®istry,
|
||||
&bound_template,
|
||||
BOUND_TEMPLATE_URI,
|
||||
"completion_region_lookup",
|
||||
)
|
||||
.await;
|
||||
let foreign_template = ResourceId::new("res_completion_other_orders");
|
||||
publish_template(
|
||||
®istry,
|
||||
&foreign_template,
|
||||
FOREIGN_TEMPLATE_URI,
|
||||
"completion_other_region_lookup",
|
||||
)
|
||||
.await;
|
||||
|
||||
let agent_id = create_agent(®istry, AGENT_SLUG).await;
|
||||
bind_snapshot(
|
||||
®istry,
|
||||
&agent_id,
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: greeting_id.clone(),
|
||||
prompt_version: 1,
|
||||
}],
|
||||
&[AgentResourceBinding {
|
||||
resource_id: bound_template,
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await;
|
||||
|
||||
let other_agent_id = create_agent(®istry, OTHER_AGENT_SLUG).await;
|
||||
bind_snapshot(
|
||||
®istry,
|
||||
&other_agent_id,
|
||||
&[AgentPromptBinding {
|
||||
prompt_id: other_id,
|
||||
prompt_version: 1,
|
||||
}],
|
||||
&[AgentResourceBinding {
|
||||
resource_id: foreign_template,
|
||||
resource_version: 1,
|
||||
}],
|
||||
)
|
||||
.await;
|
||||
|
||||
let api_key = create_platform_api_key(
|
||||
®istry,
|
||||
AGENT_SLUG,
|
||||
"mcp-completion",
|
||||
&[PlatformApiKeyScope::Read, PlatformApiKeyScope::Write],
|
||||
)
|
||||
.await;
|
||||
let base_url = spawn_mcp_server(build_test_app(
|
||||
registry.clone(),
|
||||
Duration::from_millis(0),
|
||||
Some("https://crank.example.com".to_owned()),
|
||||
))
|
||||
.await;
|
||||
|
||||
CompletionEndpoint {
|
||||
client: reqwest::Client::new(),
|
||||
mcp_url: agent_mcp_url(&base_url, AGENT_SLUG),
|
||||
base_url,
|
||||
api_key,
|
||||
registry,
|
||||
}
|
||||
}
|
||||
|
||||
/// The workspace identity the fixture published into.
|
||||
pub(super) fn workspace_id() -> WorkspaceId {
|
||||
test_workspace_id()
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
//! AT-3.17-02: completion identifiers never reach metric labels.
|
||||
//!
|
||||
//! The MCP request metric is recorded with a closed `McpMethod` label and the completion service emits
|
||||
//! only fixed labels, counts and the served revision. This test proves it against a real recorder: the
|
||||
//! rendered series of a snapshot taken after completion traffic carries no Prompt name, URI template,
|
||||
//! argument name, suggestion value or Agent slug, and every `method` label value stays inside the
|
||||
//! fixed enum.
|
||||
|
||||
use std::{collections::BTreeSet, time::Duration};
|
||||
|
||||
use metrics_util::debugging::DebuggingRecorder;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::fixtures::*;
|
||||
|
||||
/// The closed `method` label set of `crank_mcp_requests_total` (crank-metrics `McpMethod`).
|
||||
const METHOD_LABELS: [&str; 9] = [
|
||||
"initialize",
|
||||
"initialized",
|
||||
"ping",
|
||||
"tools_list",
|
||||
"tools_call",
|
||||
"notification",
|
||||
"unsupported",
|
||||
"response",
|
||||
"invalid",
|
||||
];
|
||||
|
||||
fn request(reference: Value, argument: &str, value: &str) -> Value {
|
||||
json!({"ref": reference, "argument": {"name": argument, "value": value}})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completion_identifiers_never_reach_metric_labels() {
|
||||
crank_observability::bind_metric_service(crank_observability::MetricService::McpServer)
|
||||
.expect("explicit MCP service binding before the recorder");
|
||||
let recorder = DebuggingRecorder::new();
|
||||
let snapshotter = recorder.snapshotter();
|
||||
recorder
|
||||
.install()
|
||||
.expect("isolated completion test recorder");
|
||||
|
||||
let endpoint = completion_endpoint().await;
|
||||
for revision in [MODERN_REVISION, LEGACY_REVISION] {
|
||||
for params in [
|
||||
// A matched published value, a partially matched token and an unavailable reference: the
|
||||
// three shapes that a naive implementation would be tempted to label with.
|
||||
request(
|
||||
json!({"type": "ref/prompt", "name": "greeting"}),
|
||||
"tone",
|
||||
"warm",
|
||||
),
|
||||
request(
|
||||
json!({"type": "ref/resource", "uri": BOUND_TEMPLATE_URI}),
|
||||
"region",
|
||||
"apac",
|
||||
),
|
||||
request(
|
||||
json!({"type": "ref/prompt", "name": "no-such-prompt"}),
|
||||
"tone",
|
||||
"no-such-token",
|
||||
),
|
||||
] {
|
||||
let _ = endpoint.on_revision(revision, params).await;
|
||||
}
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
|
||||
let snapshot = snapshotter.snapshot().into_vec();
|
||||
assert!(
|
||||
!snapshot.is_empty(),
|
||||
"the completion traffic must be observable at all, otherwise this check proves nothing"
|
||||
);
|
||||
|
||||
let rendered = format!("{snapshot:?}");
|
||||
for forbidden in [
|
||||
"greeting",
|
||||
"prm_completion_greeting",
|
||||
"completion-agent",
|
||||
"completion-orders",
|
||||
"no-such-prompt",
|
||||
"no-such-token",
|
||||
"warm",
|
||||
"apac",
|
||||
"tone",
|
||||
"region",
|
||||
] {
|
||||
assert!(
|
||||
!rendered.contains(forbidden),
|
||||
"a completion identifier leaked into metric labels: {forbidden:?}"
|
||||
);
|
||||
}
|
||||
|
||||
let mut observed_methods = BTreeSet::new();
|
||||
for (key, _, _, _) in &snapshot {
|
||||
if key.key().name() != "crank_mcp_requests_total" {
|
||||
continue;
|
||||
}
|
||||
for label in key.key().labels() {
|
||||
if label.key() == "method" {
|
||||
observed_methods.insert(label.value().to_owned());
|
||||
}
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
!observed_methods.is_empty(),
|
||||
"the completion requests must produce `crank_mcp_requests_total` series"
|
||||
);
|
||||
for method in &observed_methods {
|
||||
assert!(
|
||||
METHOD_LABELS.contains(&method.as_str()),
|
||||
"the `method` label must stay inside the fixed taxonomy, got {method:?} \
|
||||
from {observed_methods:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user