Compare commits

...
Author SHA1 Message Date
bsodfather 4832878468 refactor(mcp): migrate compatible logging paths to rmcp SDK
CI / UI Checks (pull_request) Successful in 9s
CI / Rust Checks (pull_request) Successful in 27m19s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
2026-11-11 22:51:42 +00:00
bsodfather 5bf4e3e9bf Merge pull request 'fix(deps): rustix 1.1.6 for release security gate' (#125) from fix/rustix-rustsec-2026-0486 into main
CI / UI Checks (push) Successful in 13s
CI / Rust Checks (push) Successful in 34m16s
CI / Rust Feature Validation (push) Skipped
CI / Frontend E2E (push) Skipped
CI / Community Image Smoke (push) Skipped
CI / Required Checks (push) Successful in 1s
CI / Deploy (push) Skipped
Community Release / release (push) Successful in 52m54s
2026-11-11 12:10:13 +00:00
bsodfather 1ac5b10c67 fix(deps): update rustix for RUSTSEC-2026-0486
CI / UI Checks (pull_request) Successful in 7s
CI / Rust Checks (pull_request) Successful in 27m46s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
2026-11-11 11:41:23 +00:00
bsodfather 07a9ef0a4a Merge pull request 'refactor(mcp): completion request/result via rmcp SDK' (#124) from delivery/rmcp107-completion into main
CI / UI Checks (push) Successful in 12s
CI / Rust Checks (push) Successful in 31m41s
CI / Rust Feature Validation (push) Skipped
CI / Frontend E2E (push) Skipped
CI / Community Image Smoke (push) Skipped
CI / Required Checks (push) Successful in 1s
CI / Deploy (push) Skipped
Community Release / release (push) Failing after 12s
2026-11-11 10:52:36 +00:00
bsodfather 4f83d8d24c refactor(mcp): route completion requests and results through rmcp SDK
CI / UI Checks (pull_request) Successful in 12s
CI / Rust Checks (pull_request) Successful in 36m53s
CI / Rust Feature Validation (pull_request) Skipped
CI / Frontend E2E (pull_request) Skipped
CI / Community Image Smoke (pull_request) Skipped
CI / Required Checks (pull_request) Successful in 1s
CI / Deploy (pull_request) Skipped
2026-11-11 10:11:35 +00:00
bsodfather 2a57800f63 Merge pull request 'fix(mcp): rmcp 3.9.0 — RUSTSEC-2026-0462' (#123) from fix/rmcp-security-0462 into main
CI / UI Checks (push) Successful in 9s
CI / Rust Checks (push) Successful in 25m46s
CI / Rust Feature Validation (push) Skipped
CI / Frontend E2E (push) Skipped
CI / Community Image Smoke (push) Skipped
CI / Required Checks (push) Successful in 3s
CI / Deploy (push) Skipped
Community Release / release (push) Successful in 48m48s
2026-11-10 21:51:10 +00:00
14 changed files with 1395 additions and 46 deletions

No files matched your search

Generated
+3 -3
View File
@@ -3109,9 +3109,9 @@ dependencies = [
[[package]]
name = "rustix"
version = "1.1.4"
version = "1.1.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa"
dependencies = [
"bitflags",
"errno",
@@ -4862,7 +4862,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
dependencies = [
"libc",
"rustix 1.1.4",
"rustix 1.1.6",
]
[[package]]
@@ -21,8 +21,7 @@ use crate::{
PromptGetCommand, PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity,
ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome,
declared_mcp_method, discover_result, handle_completion_command,
validate_modern_request_name,
declared_mcp_method, discover_result, validate_modern_request_name,
},
session::SessionState,
tool_error::execution_locale,
@@ -624,7 +623,7 @@ pub(super) async fn handle_modern_request(
);
}
};
let outcome = handle_completion_command(
let outcome = super::rmcp_dispatch::handle_completion_command(
state,
resource_service_context(path, credential, transport_correlation, message),
version,
@@ -61,9 +61,33 @@ pub(crate) struct CounterSet {
sdk_prompts_dispatch: AtomicUsize,
sdk_prompts_list_result: AtomicUsize,
sdk_prompts_get_result: AtomicUsize,
sdk_completion_dispatch: AtomicUsize,
sdk_completion_result: AtomicUsize,
sdk_logging_dispatch: AtomicUsize,
sdk_logging_level: AtomicUsize,
sdk_logging_notification: AtomicUsize,
}
impl CounterSet {
pub(crate) fn sdk_logging_dispatch(&self) -> usize {
self.sdk_logging_dispatch.load(Ordering::SeqCst)
}
pub(crate) fn sdk_logging_level(&self) -> usize {
self.sdk_logging_level.load(Ordering::SeqCst)
}
pub(crate) fn sdk_logging_notification(&self) -> usize {
self.sdk_logging_notification.load(Ordering::SeqCst)
}
pub(crate) fn sdk_completion_dispatch(&self) -> usize {
self.sdk_completion_dispatch.load(Ordering::SeqCst)
}
pub(crate) fn sdk_completion_result(&self) -> usize {
self.sdk_completion_result.load(Ordering::SeqCst)
}
pub(crate) fn sdk_prompts_dispatch(&self) -> usize {
self.sdk_prompts_dispatch.load(Ordering::SeqCst)
}
@@ -246,6 +270,38 @@ pub(crate) fn sdk_prompts_get_result_serialized() {
#[path = "../rmcp_prompts_runtime_tests.rs"]
mod rmcp_prompts_runtime_tests;
/// Mark only after constructing real SDK CompleteRequestParams.
pub(crate) fn sdk_completion_dispatch_enter() {
increment(|counters| &counters.sdk_completion_dispatch);
}
/// Mark only after successfully serializing real SDK CompleteResult/CompletionInfo.
pub(crate) fn sdk_completion_result_serialized() {
increment(|counters| &counters.sdk_completion_result);
}
#[cfg(test)]
#[path = "../rmcp_completion_runtime_tests.rs"]
mod rmcp_completion_runtime_tests;
/// Mark only after constructing the real SDK typed legacy logging request.
pub(crate) fn sdk_logging_dispatch_enter() {
increment(|counters| &counters.sdk_logging_dispatch);
}
/// Mark only after successfully decoding a real SDK LoggingLevel at either input.
pub(crate) fn sdk_logging_level_parsed() {
increment(|counters| &counters.sdk_logging_level);
}
/// Mark only after serializing real SDK LoggingMessageNotificationParam params, not an envelope.
pub(crate) fn sdk_logging_notification_serialized() {
increment(|counters| &counters.sdk_logging_notification);
}
#[path = "../rmcp_logging_runtime_tests.rs"]
mod rmcp_logging_runtime_tests;
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
let _ = OBSERVER.try_with(|counters| {
counter(counters).fetch_add(1, Ordering::SeqCst);
@@ -39,8 +39,7 @@ use crate::{
EVENT_LEVEL_APPLIED, INVALID_LEVEL, Kind, LoggingOutcome, MethodHandler, PromptGetCommand,
PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity, ResourceReadCommand,
ResourcesCommand, ResourcesListCommand, ResourcesOutcome, ServiceContext, SetLevelCommand,
ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_completion_command,
handle_logging_command,
ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_logging_command,
},
tool_error::execution_locale,
transport::{ResponseMode, session_id_from_headers, transport_response},
@@ -648,7 +647,7 @@ pub(super) async fn handle_legacy_request(
);
}
};
let outcome = handle_completion_command(
let outcome = super::rmcp_dispatch::handle_completion_command(
&state,
ServiceContext {
workspace_slug: &session.workspace_slug,
+12 -8
View File
@@ -331,14 +331,18 @@ pub(super) fn completion_result(
total: Option<usize>,
has_more: bool,
) -> Value {
let mut completion = json!({ "values": values });
if let Some(total) = total {
completion["total"] = json!(total);
}
if has_more {
completion["hasMore"] = json!(true);
}
json!({ "completion": completion })
let mut completion = rmcp::model::CompletionInfo::default();
completion.values = values;
// The domain scans at most 1024 candidates, so its exact count fits the SDK's u32.
completion.total = total.map(|total| u32::try_from(total).expect("bounded completion count"));
completion.has_more = has_more.then_some(true);
let mut result = rmcp::model::CompleteResult::new(completion);
// Keep the shared result era-neutral; the existing caller projects modern resultType.
result.result_type = None;
let result = serde_json::to_value(result).expect("SDK completion contains strings and counts");
#[cfg(test)]
super::dispatch_observer::sdk_completion_result_serialized();
result
}
/// The structured `prompts/get` argument rejection (AT-3.14-02): a `-32602` error whose `data`
@@ -128,6 +128,47 @@ pub(super) async fn list_resource_templates(
.await
}
pub(super) async fn handle_completion_command(
state: &Arc<AppState>,
context: ServiceContext<'_>,
revision: &str,
command: crate::protocol::CompletionCommand,
) -> crate::protocol::CompletionOutcome {
use crate::protocol::{
CompletionArgument, CompletionCommand, CompletionOutcome, CompletionReference,
};
use rmcp::model::{ArgumentInfo, CompleteRequestParams, Reference};
let reference = match command.reference {
CompletionReference::Prompt { name } => Reference::for_prompt(name),
CompletionReference::Resource { uri } => Reference::for_resource(uri),
};
let params = CompleteRequestParams::new(
reference,
ArgumentInfo::new(command.argument.name, command.argument.value),
);
// SDK context only supports strings; retain arbitrary JSON unchanged for domain validation.
let context_arguments = command.context;
#[cfg(test)]
super::dispatch_observer::sdk_completion_dispatch_enter();
let reference = match params.r#ref {
Reference::Prompt(reference) => CompletionReference::Prompt {
name: reference.name,
},
Reference::Resource(reference) => CompletionReference::Resource { uri: reference.uri },
_ => return CompletionOutcome::InvalidParams("invalid completion/complete parameters"),
};
let command = CompletionCommand {
reference,
argument: CompletionArgument {
name: params.argument.name,
value: params.argument.value,
},
context: context_arguments,
};
crate::protocol::handle_completion_command(state, context, revision, command).await
}
fn sdk_resource_page(
list: crate::protocol::ResourcesListCommand,
) -> crate::protocol::ResourcesListCommand {
@@ -41,6 +41,9 @@ use std::{
sync::{Mutex, MutexGuard},
};
// Both pinned revisions still require logging despite the SDK's SEP-2577 deprecation.
#[allow(deprecated)]
use rmcp::model::{LoggingLevel, LoggingMessageNotificationParam, SetLevelRequestParams};
use serde::Deserialize;
use serde_json::{Value, json};
use tokio::task_local;
@@ -61,7 +64,8 @@ pub(crate) enum LogLevel {
}
impl LogLevel {
/// The exact wire literal of this level.
/// The exact wire literal of this level (contract assertions only; runtime uses SDK serde).
#[cfg(test)]
pub(crate) const fn as_str(self) -> &'static str {
match self {
Self::Debug => "debug",
@@ -80,17 +84,47 @@ impl LogLevel {
/// Nothing is coerced: no case folding, no aliases (`warn`), no numeric severities. A value that
/// is not one of the pinned strings is malformed, which is what the pinned `LoggingLevel` type
/// says and what `InvalidParamsError` is for.
#[allow(deprecated)]
pub(crate) fn parse(value: &str) -> Option<Self> {
match value {
"debug" => Some(Self::Debug),
"info" => Some(Self::Info),
"notice" => Some(Self::Notice),
"warning" => Some(Self::Warning),
"error" => Some(Self::Error),
"critical" => Some(Self::Critical),
"alert" => Some(Self::Alert),
"emergency" => Some(Self::Emergency),
_ => None,
if value.len() > MAX_LEVEL_BYTES {
return None;
}
let level: LoggingLevel = serde_json::from_value(Value::String(value.to_owned())).ok()?;
#[cfg(test)]
crate::app::dispatch_observer::sdk_logging_level_parsed();
Some(level.into())
}
}
// Keep domain severity ordering independent of SDK enum discriminants (which have no Ord).
#[allow(deprecated)]
impl From<LoggingLevel> for LogLevel {
fn from(level: LoggingLevel) -> Self {
match level {
LoggingLevel::Debug => Self::Debug,
LoggingLevel::Info => Self::Info,
LoggingLevel::Notice => Self::Notice,
LoggingLevel::Warning => Self::Warning,
LoggingLevel::Error => Self::Error,
LoggingLevel::Critical => Self::Critical,
LoggingLevel::Alert => Self::Alert,
LoggingLevel::Emergency => Self::Emergency,
}
}
}
#[allow(deprecated)]
impl From<LogLevel> for LoggingLevel {
fn from(level: LogLevel) -> Self {
match level {
LogLevel::Debug => Self::Debug,
LogLevel::Info => Self::Info,
LogLevel::Notice => Self::Notice,
LogLevel::Warning => Self::Warning,
LogLevel::Error => Self::Error,
LogLevel::Critical => Self::Critical,
LogLevel::Alert => Self::Alert,
LogLevel::Emergency => Self::Emergency,
}
}
}
@@ -135,11 +169,20 @@ pub(crate) struct SetLevelCommand {
impl SetLevelCommand {
/// The bounded input contract of AC2: the level is length-bounded and compared exactly, so a
/// malformed or oversized value is refused with bounded work and one safe detail.
pub(crate) fn validate(&self) -> Result<LogLevel, &'static str> {
#[allow(deprecated)]
pub(crate) fn validate(&self) -> Result<SetLevelRequestParams, &'static str> {
if self.level.is_empty() || self.level.len() > MAX_LEVEL_BYTES {
return Err(INVALID_LEVEL);
}
LogLevel::parse(&self.level).ok_or(INVALID_LEVEL)
// Only level was part of the old command: unknown members (including _meta) stay ignored.
let request =
serde_json::from_value(json!({"level": self.level})).map_err(|_| INVALID_LEVEL)?;
#[cfg(test)]
{
crate::app::dispatch_observer::sdk_logging_level_parsed();
crate::app::dispatch_observer::sdk_logging_dispatch_enter();
}
Ok(request)
}
}
@@ -282,19 +325,22 @@ pub(crate) fn take_notifications() -> Vec<Value> {
}
std::mem::take(&mut log.pending)
.into_iter()
.map(|event| {
json!({
.filter_map(|event| {
#[allow(deprecated)]
let params = LoggingMessageNotificationParam::new(
event.level.into(),
json!({"event": event.event, "outcome": event.outcome}),
)
.with_logger(LOGGER_NAME);
// Logging remains best-effort: a serialization failure drops only this event.
let params = serde_json::to_value(params).ok()?;
#[cfg(test)]
crate::app::dispatch_observer::sdk_logging_notification_serialized();
Some(json!({
"jsonrpc": "2.0",
"method": "notifications/message",
"params": {
"level": event.level.as_str(),
"logger": LOGGER_NAME,
"data": {
"event": event.event,
"outcome": event.outcome,
}
}
})
"params": params,
}))
})
.collect()
})
@@ -354,7 +400,9 @@ pub(crate) fn handle_logging_command(
command: SetLevelCommand,
) -> LoggingOutcome {
match command.validate() {
Ok(level) => {
Ok(request) => {
#[allow(deprecated)]
let level = request.level.into();
store.set(session_id, level);
LoggingOutcome::Applied(level)
}
@@ -10,7 +10,8 @@ use super::*;
/// is malformed (which the adapter answers with the same safe detail).
fn validate(level: &str) -> Option<Result<LogLevel, &'static str>> {
let command: SetLevelCommand = serde_json::from_value(json!({ "level": level })).ok()?;
Some(command.validate())
#[allow(deprecated)]
Some(command.validate().map(|request| request.level.into()))
}
#[test]
@@ -291,8 +292,11 @@ fn the_modern_level_is_read_from_the_pinned_meta_key_only() {
fn the_command_records_the_level_of_its_own_session_only() {
let store = LogLevelStore::new();
store.set("other-session", LogLevel::Debug);
let command: SetLevelCommand =
serde_json::from_value(json!({ "level": "critical" })).expect("a pinned level parses");
// Unknown members were ignored by the legacy command; SDK metadata must not narrow that wire.
let command: SetLevelCommand = serde_json::from_value(json!({
"level": "critical", "_meta": 7, "unknown": {"private": "ignored"}
}))
.expect("a pinned level parses regardless of unknown members");
let outcome = handle_logging_command(&store, "this-session", command);
assert!(matches!(
outcome,
@@ -36,7 +36,10 @@ pub(crate) use command::{
ContinuationSupport, ServiceContext, ToolCallCommand, ToolCallOutcome, ToolsCommand,
ToolsListCommand, ToolsOutcome, handle_tools_command,
};
pub(crate) use completion::{CompletionCommand, CompletionOutcome, handle_completion_command};
pub(crate) use completion::{
CompletionArgument, CompletionCommand, CompletionOutcome, CompletionReference,
handle_completion_command,
};
pub(crate) use logging::{
CarriedScope, EVENT_FAILED, EVENT_LEVEL_APPLIED, EVENT_REJECTED, EVENT_SERVED, INVALID_LEVEL,
LogLevel, LogLevelStore, LoggingOutcome, SetLevelCommand, carry_scope, handle_logging_command,
@@ -0,0 +1,345 @@
//! #107 Completion: real build_app HTTP wire controls and a separate SDK-path oracle.
use super::{CounterSet, observe, support::*};
use axum::{body::Body, response::Response};
use futures_util::{StreamExt, stream};
use serde_json::{Value, json};
use std::{sync::Arc, time::Duration};
#[path = "rmcp_completion_test_support.rs"]
mod fixtures;
use fixtures::{BOUNDED_URI, Endpoint, LARGE_URI, URI};
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
let (parts, body) = response.into_parts();
let body = stream::unfold(
(body.into_data_stream(), counters),
|(mut body, c)| async move {
observe(c.clone(), body.next())
.await
.map(|chunk| (chunk, (body, c)))
},
);
Response::from_parts(parts, Body::from_stream(body))
}
fn counts(c: &CounterSet) -> [usize; 2] {
[c.sdk_completion_dispatch(), c.sdk_completion_result()]
}
fn params(reference: Value, name: &str, value: &str) -> Value {
json!({"ref":reference,"argument":{"name":name,"value":value}})
}
fn prompt(name: &str) -> Value {
json!({"type":"ref/prompt","name":name})
}
fn resource(uri: &str) -> Value {
json!({"type":"ref/resource","uri":uri})
}
fn request(revision: &str, mut params: Value) -> Value {
if revision == MODERN_REVISION {
params["_meta"] = modern_meta();
}
json!({"jsonrpc":"2.0","id":9007199254740993_u64,"method":"completion/complete","params":params})
}
async fn wire(response: reqwest::Response, sse: bool) -> Value {
assert_eq!(response.status(), 200);
assert_eq!(response.headers()["x-request-id"], "sdk-completion-wire");
assert_eq!(
response.headers()["x-trace-id"],
"11111111111111111111111111111111"
);
let content_type = response.headers()["content-type"]
.to_str()
.unwrap()
.to_owned();
let text = tokio::time::timeout(Duration::from_secs(5), response.text())
.await
.unwrap()
.unwrap();
let body: Value = if sse {
assert!(
content_type.starts_with("text/event-stream"),
"{content_type}: {text}"
);
let frames: Vec<Value> = text
.lines()
.filter_map(|line| {
line.strip_prefix("data:")
.map(|s| serde_json::from_str(s.trim()).unwrap())
})
.collect();
let terminal: Vec<_> = frames
.iter()
.filter(|f| f.get("id") == Some(&json!(9007199254740993_u64)))
.collect();
assert_eq!(terminal.len(), 1, "{frames:?}");
assert_eq!(frames.last(), Some(terminal[0]), "terminal must be last");
terminal[0].clone()
} else {
assert!(
content_type.starts_with("application/json"),
"{content_type}: {text}"
);
serde_json::from_str(&text).unwrap()
};
assert_eq!(body["jsonrpc"], "2.0");
assert_eq!(body["id"], json!(9007199254740993_u64));
body
}
async fn success(
h: &Endpoint,
revision: &str,
session: Option<&str>,
p: Value,
sse: bool,
) -> (Value, [usize; 2]) {
let before = counts(&h.counters);
let body = wire(
h.post(revision, session, &request(revision, p), sse).await,
sse,
)
.await;
assert!(body.get("error").is_none(), "{body}");
let result = &body["result"];
if revision == MODERN_REVISION {
assert_eq!(result["resultType"], "complete", "{body}");
} else {
assert!(result.get("resultType").is_none(), "{body}");
}
for key in ["ttlMs", "cacheScope", "_meta"] {
assert!(result.get(key).is_none(), "{body}");
}
let after = counts(&h.counters);
(
result["completion"].clone(),
std::array::from_fn(|i| after[i] - before[i]),
)
}
async fn control(revision: &str) -> Vec<[usize; 2]> {
let h = Endpoint::started().await;
let session = h.session(revision).await;
let session = session.as_deref();
let modes: &[bool] = if revision == MODERN_REVISION {
&[false, true]
} else {
&[false]
};
let mut deltas = Vec::new();
for &sse in modes {
for (p, expected) in [
(
params(prompt("greeting"), "tone", ""),
json!({"values":["warm","dry"],"total":2}),
),
(
params(prompt("archived-prompt"), "tone", "W"),
json!({"values":["warm"],"total":1}),
),
(
params(prompt("greeting"), "name", "A"),
json!({"values":[],"total":0}),
),
(
params(resource(URI), "region", ""),
json!({"values":["eu","us","apac"],"total":3}),
),
(
params(resource(URI), "region", "A"),
json!({"values":["apac"],"total":1}),
),
(
params(resource(URI), "region", "zzz"),
json!({"values":[],"total":0}),
),
] {
let (completion, delta) = success(&h, revision, session, p, sse).await;
assert_eq!(completion, expected);
deltas.push(delta);
}
for (uri, total) in [(BOUNDED_URI, Some(150)), (LARGE_URI, None)] {
let (completion, delta) = success(
&h,
revision,
session,
params(resource(uri), "region", "item"),
sse,
)
.await;
assert_eq!(
completion["values"],
json!((0..100).map(|i| format!("item{i:04}")).collect::<Vec<_>>())
);
assert_eq!(completion["hasMore"], true);
if let Some(total) = total {
assert_eq!(completion["total"], total);
} else {
assert!(
completion.get("total").is_none(),
"partial scan: {completion}"
);
}
deltas.push(delta);
}
let mut with_context = params(prompt("greeting"), "tone", "w");
with_context["context"] = json!({"arguments":{"name":"Ada","tone":"dry"}});
let (completion, delta) = success(&h, revision, session, with_context, sse).await;
assert_eq!(completion, json!({"values":["warm"],"total":1}));
deltas.push(delta);
let mut unavailable = None;
for p in [
params(prompt("draft-prompt"), "tone", ""),
params(prompt("unbound-prompt"), "tone", ""),
params(prompt("other-agent-prompt"), "tone", ""),
params(prompt("never-existed"), "tone", ""),
params(prompt("changed-draft"), "tone", ""),
params(prompt("greeting"), "unknown-argument", ""),
params(resource("crank://foreign/{region}"), "region", ""),
params(resource(URI), "unknown-parameter", ""),
] {
let body = wire(
h.post(revision, session, &request(revision, p), sse).await,
sse,
)
.await;
assert_eq!(body["error"]["code"], -32602, "{body}");
assert_eq!(
body["error"]["message"],
"the completion reference is not available"
);
assert!(body.get("result").is_none());
if let Some(ref previous) = unavailable {
assert_eq!(&body, previous);
}
unavailable = Some(body);
}
let mut invalid = vec![
json!({"argument":{"name":"tone","value":""}}),
params(json!({"type":"ref/tool","name":"greeting"}), "tone", ""),
params(prompt("greeting"), "tone", &"s".repeat(1025)),
params(prompt("greeting"), &"n".repeat(129), ""),
];
// Preserve domain validation on arbitrary JSON, never drop or stringify context values for SDK.
for value in [
json!(7),
json!(true),
json!(null),
json!(["eu"]),
json!({"region":"eu"}),
json!("s".repeat(1025)),
] {
let mut p = params(prompt("greeting"), "tone", "");
p["context"] = json!({"arguments":{"secret-context":value}});
invalid.push(p);
}
let mut p = params(prompt("greeting"), "tone", "");
p["context"] = json!({"arguments":(0..33).map(|i| (format!("arg{i}"), json!("eu"))).collect::<serde_json::Map<_,_>>()});
invalid.push(p);
for p in invalid {
let body = wire(
h.post(revision, session, &request(revision, p), sse).await,
sse,
)
.await;
assert_eq!(body["error"]["code"], -32602, "{body}");
assert_eq!(
body["error"]["message"],
"invalid completion/complete parameters"
);
assert!(body.get("result").is_none());
for leaked in ["secret-context", &"s".repeat(1025), &"n".repeat(129)] {
assert!(!body.to_string().contains(leaked), "{body}");
}
}
}
h.registry
.revoke_platform_api_key(
&workspace_id(),
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
&time::OffsetDateTime::now_utc(),
)
.await
.unwrap();
let before = h.counters.snapshot();
let sdk_before = counts(&h.counters);
let response = h
.post(
revision,
session,
&request(revision, params(prompt("greeting"), "tone", "")),
false,
)
.await;
assert_eq!(response.status(), 401);
let _ = response.bytes().await.unwrap();
assert_eq!(
counts(&h.counters),
sdk_before,
"revoked key must not dispatch to SDK"
);
let after = h.counters.snapshot();
assert_eq!(after.era_modern, before.era_modern);
assert_eq!(after.era_legacy, before.era_legacy);
assert_eq!(after.tools_service, before.tools_service);
eprintln!(
"existing GREEN Completion HTTP {revision}: Prompt+Resource refs, exact bound v1/archive, prefix/empty/bounded/truncated, JSON/context/errors/correlation/auth; SDK actual={deltas:?}, expected=[1,1] per success"
);
deltas
}
#[tokio::test]
async fn rmcp_completion_wire_legacy() {
control(LEGACY_REVISION).await;
}
#[tokio::test]
async fn rmcp_completion_wire_modern() {
control(MODERN_REVISION).await;
}
#[tokio::test]
async fn rmcp_completion_sdk_legacy() {
let deltas = control(LEGACY_REVISION).await;
assert!(
deltas.iter().all(|d| *d == [1, 1]),
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
);
}
#[tokio::test]
async fn rmcp_completion_sdk_modern() {
let deltas = control(MODERN_REVISION).await;
assert!(
deltas.iter().all(|d| *d == [1, 1]),
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
);
}
#[tokio::test]
async fn rmcp_completion_observer_scope_control() {
use super::{sdk_completion_dispatch_enter, sdk_completion_result_serialized};
let a = Arc::new(CounterSet::default());
let b = Arc::new(CounterSet::default());
sdk_completion_dispatch_enter();
sdk_completion_result_serialized();
assert_eq!(counts(&a), [0; 2]);
let snapshot = a.snapshot();
tokio::join!(
observe(a.clone(), async {
sdk_completion_dispatch_enter();
tokio::task::yield_now().await;
sdk_completion_result_serialized();
}),
observe(b.clone(), async {
sdk_completion_result_serialized();
})
);
assert_eq!(counts(&a), [1, 1]);
assert_eq!(counts(&b), [0, 1]);
assert_eq!(a.snapshot(), snapshot);
let body = Body::from_stream(stream::once(async {
sdk_completion_result_serialized();
Ok::<_, std::convert::Infallible>("data: terminal\n\n")
}));
let response = observe_body(Response::new(body), b.clone());
assert_eq!(counts(&b), [0, 1], "body must be deferred");
assert_eq!(
&axum::body::to_bytes(response.into_body(), 100)
.await
.unwrap()[..],
b"data: terminal\n\n"
);
assert_eq!(counts(&b), [0, 2]);
assert_eq!(counts(&a), [1, 1]);
}
@@ -0,0 +1,445 @@
//! Completion HTTP fixture using the existing observed HTTP app and disposable PostgreSQL.
use super::*;
use crank_core::prompt::{PromptDefinition, PromptSensitivity};
use crank_core::{
Agent, AgentStatus, AgentVersion, HttpMethod, RestTarget, Target, ToolSelectionPolicy,
ids::PromptId,
};
use crank_registry::PostgresRegistry;
use crank_registry::model::{
AgentPromptBinding, ArchivePromptRequest, CreatePromptDraftRequest, PublishPromptRequest,
SaveAgentCatalogConfigRequest, UpdatePromptDraftRequest,
};
use crank_registry::{CreateAgentRequest, PublishAgentRequest};
use crank_runtime::{
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
};
pub(super) fn definition(name: &str, content: &str) -> PromptDefinition {
PromptDefinition::parse(&json!({
"name":name, "description":format!("Published {name}"),
"arguments":[
{"name":"name","schema":{"type":"string"},"required":true},
{"name":"count","schema":{"type":"integer"},"required":false,"default":2},
{"name":"enabled","schema":{"type":"boolean"},"required":false,"default":true},
{"name":"tone","schema":{"type":"string","enum":["warm","dry"]},"required":false,"default":"warm"}
],
"messages":[{"role":"system","content":"Be brief."},{"role":"user","content":content}]
})).unwrap()
}
pub(super) struct Endpoint {
pub registry: crank_registry::PostgresRegistry,
pub counters: Arc<CounterSet>,
pub key: String,
pub url: String,
server: tokio::task::JoinHandle<()>,
}
impl Drop for Endpoint {
fn drop(&mut self) {
self.server.abort();
}
}
impl Endpoint {
pub async fn started() -> Self {
crank_test_support::postgres_schema_url_for_task("completion_owner", "t_3fa1ad63").await;
let registry = test_registry().await;
publish_region_operation(&registry, "completion_lookup").await;
for (id, uri, size) in [
("res_completion_small", URI, 3),
("res_completion_large", LARGE_URI, 1025),
("res_completion_bounded", BOUNDED_URI, 150),
] {
publish_template(&registry, &ResourceId::new(id), uri, size).await;
}
let mut archived_at = test_time();
for (id, name, publish) in [
("prm_a", "greeting", true),
("prm_b", "archived-prompt", true),
("prm_c", "unbound-prompt", true),
("prm_d", "draft-prompt", false),
("prm_e", "other-agent-prompt", true),
] {
let row = registry
.create_prompt_draft(CreatePromptDraftRequest {
workspace_id: workspace_id(),
prompt_id: PromptId::new(id),
sensitivity: PromptSensitivity::Internal,
definition: definition(
name,
"Hello {{name}} count={{count}} enabled={{enabled}} tone={{tone}}",
),
created_at: time::OffsetDateTime::now_utc(),
})
.await
.unwrap();
if publish {
let row = registry
.publish_prompt_draft(PublishPromptRequest {
workspace_id: workspace_id(),
prompt_id: PromptId::new(id),
expected_updated_at: row.updated_at,
published_at: time::OffsetDateTime::now_utc(),
})
.await
.unwrap();
if id == "prm_b" {
archived_at = row.updated_at;
}
}
}
for (id, slug) in [
(agent_id(), AGENT_SLUG),
(
crank_core::AgentId::new("agent_other_prompts"),
"other-prompts",
),
] {
registry
.create_agent(CreateAgentRequest {
agent: &Agent {
id: id.clone(),
workspace_id: workspace_id(),
slug: slug.into(),
display_name: "SDK Prompts".into(),
description: String::new(),
status: AgentStatus::Draft,
current_draft_version: 1,
latest_published_version: None,
created_at: test_time(),
updated_at: test_time(),
published_at: None,
},
version: &AgentVersion {
agent_id: id,
version: 1,
status: AgentStatus::Draft,
instructions: json!({}),
tool_selection_policy: ToolSelectionPolicy::default(),
created_at: test_time(),
},
bindings: &[],
})
.await
.unwrap();
}
let other_agent = crank_core::AgentId::new("agent_other_prompts");
registry
.save_agent_catalog_config_editable_with_prompts(
SaveAgentCatalogConfigRequest {
workspace_id: &workspace_id(),
agent_id: &other_agent,
agent_version: 1,
bindings: &[],
tool_selection_policy: &ToolSelectionPolicy::default(),
resource_bindings: &[],
expected_state: None,
},
&[AgentPromptBinding {
prompt_id: PromptId::new("prm_e"),
prompt_version: 1,
}],
)
.await
.unwrap();
registry
.publish_agent(PublishAgentRequest {
workspace_id: &workspace_id(),
agent_id: &other_agent,
version: 1,
published_at: &test_time(),
published_by: Some("alice"),
expected_state: None,
})
.await
.unwrap();
registry
.save_agent_catalog_config_editable_with_prompts(
SaveAgentCatalogConfigRequest {
workspace_id: &workspace_id(),
agent_id: &agent_id(),
agent_version: 1,
bindings: &[],
tool_selection_policy: &ToolSelectionPolicy::default(),
resource_bindings: &[
AgentResourceBinding {
resource_id: ResourceId::new("res_completion_small"),
resource_version: 1,
},
AgentResourceBinding {
resource_id: ResourceId::new("res_completion_large"),
resource_version: 1,
},
AgentResourceBinding {
resource_id: ResourceId::new("res_completion_bounded"),
resource_version: 1,
},
],
expected_state: None,
},
&[
AgentPromptBinding {
prompt_id: PromptId::new("prm_a"),
prompt_version: 1,
},
AgentPromptBinding {
prompt_id: PromptId::new("prm_b"),
prompt_version: 1,
},
],
)
.await
.unwrap();
registry
.publish_agent(PublishAgentRequest {
workspace_id: &workspace_id(),
agent_id: &agent_id(),
version: 1,
published_at: &test_time(),
published_by: Some("alice"),
expected_state: None,
})
.await
.unwrap();
registry
.archive_prompt_draft(ArchivePromptRequest {
workspace_id: workspace_id(),
prompt_id: PromptId::new("prm_b"),
expected_updated_at: archived_at,
archived_at: time::OffsetDateTime::now_utc(),
})
.await
.unwrap();
// A mutable v2 draft must not change the bound v1 rendering or discovery metadata.
let draft = registry
.get_prompt_draft(&workspace_id(), &PromptId::new("prm_a"))
.await
.unwrap();
registry
.update_prompt_draft(UpdatePromptDraftRequest {
workspace_id: workspace_id(),
prompt_id: PromptId::new("prm_a"),
sensitivity: PromptSensitivity::Internal,
definition: definition("changed-draft", "Changed {{name}}"),
expected_updated_at: draft.updated_at,
updated_at: time::OffsetDateTime::now_utc(),
})
.await
.unwrap();
let key = create_api_key(&registry).await;
let counters = Arc::new(CounterSet::default());
let app = crate::build_app(
registry.clone(),
Duration::ZERO,
None,
SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(),
crank_runtime::community_with_outbound_policy(
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
)
.build(),
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
Arc::new(InMemoryCoordinationStateStore::default()),
Arc::new(crate::session::InMemorySessionStore::default()),
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
);
let app = observe_requests(app, counters.clone(), None).layer(axum::middleware::from_fn({
let counters = counters.clone();
move |request: axum::extract::Request, next: axum::middleware::Next| {
let counters = counters.clone();
async move { observe_body(next.run(request).await, counters) }
}
}));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!(
"http://{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}",
listener.local_addr().unwrap()
);
let server = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
Self {
registry,
counters,
key,
url,
server,
}
}
pub async fn post(
&self,
revision: &str,
session: Option<&str>,
body: &Value,
sse: bool,
) -> reqwest::Response {
let mut request = reqwest::Client::new()
.post(&self.url)
.bearer_auth(&self.key)
.header(
"Accept",
if sse {
"text/event-stream, application/json"
} else {
"application/json"
},
)
.header("x-request-id", "sdk-completion-wire")
.header(
"traceparent",
"00-11111111111111111111111111111111-2222222222222222-01",
)
.header("MCP-Protocol-Version", revision);
if let Some(session) = session {
request = request.header("MCP-Session-Id", session);
}
if revision == MODERN_REVISION {
request = request.header("Mcp-Method", body["method"].as_str().unwrap());
}
request.json(body).send().await.unwrap()
}
pub async fn session(&self, revision: &str) -> Option<String> {
if revision == MODERN_REVISION {
return None;
}
let response = self
.post(revision, None, &legacy_initialize(1), false)
.await;
assert_eq!(response.status(), 200);
let session = response.headers()["MCP-Session-Id"]
.to_str()
.unwrap()
.to_owned();
assert_eq!(
json_body(response).await["result"]["protocolVersion"],
revision
);
assert_eq!(
self.post(revision, Some(&session), &initialized_notification(), false)
.await
.status(),
202
);
Some(session)
}
}
use crank_core::{ids::ResourceId, resource::TemplateSource};
use crank_mapping::{MappingRule, MappingSet};
use crank_registry::model::{
CreateResourceTemplateDraftRequest, PublishResourceTemplateVersionRequest,
};
use crank_registry::{AgentResourceBinding, PublishRequest};
use sha2::{Digest, Sha256};
pub(super) const URI: &str = "crank://completion-orders/{region}";
pub(super) const LARGE_URI: &str = "crank://completion-large/{region}";
pub(super) const BOUNDED_URI: &str = "crank://completion-bounded/{region}";
async fn publish_region_operation(registry: &PostgresRegistry, name: &str) {
let mut operation = test_operation("http://127.0.0.1:9");
operation.id = crank_core::OperationId::new(format!("op_{name}"));
operation.name = name.to_owned();
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(&workspace_id(), &operation, Some("alice"))
.await
.expect("the Read Operation is created through the registry API");
registry
.publish_operation(PublishRequest {
workspace_id: &workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &time::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,
size: usize,
) {
let operation_name = "completion_lookup";
let options: Vec<String> = if size == 3 {
vec!["eu".into(), "us".into(), "apac".into()]
} else {
(0..size).map(|i| format!("item{i:04}")).collect()
};
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": options
}
}],
"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: workspace_id(),
resource_id: resource_id.clone(),
uri: format!("crank://templates/{}", resource_id.as_str()),
name: format!("{}_template", resource_id.as_str()),
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: time::OffsetDateTime::now_utc(),
})
.await
.expect("the template Draft is created through the registry API");
registry
.publish_resource_template_version(PublishResourceTemplateVersionRequest {
workspace_id: 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: time::OffsetDateTime::now_utc(),
})
.await
.expect("the template exact version publishes");
}
@@ -0,0 +1,258 @@
//! #107 logging: existing HTTP wire control before the independent SDK marker assertions.
use super::{CounterSet, observe, support::*};
use axum::{body::Body, response::Response};
use futures_util::{StreamExt, stream};
use serde_json::{Value, json};
use std::{sync::Arc, time::Duration};
#[path = "rmcp_logging_test_support.rs"]
mod fixtures;
use fixtures::Endpoint;
const LEVEL: &str = "io.modelcontextprotocol/logLevel";
fn counts(c: &CounterSet) -> [usize; 3] {
[
c.sdk_logging_dispatch(),
c.sdk_logging_level(),
c.sdk_logging_notification(),
]
}
fn observe_body(response: Response, counters: Arc<CounterSet>) -> Response {
let (parts, body) = response.into_parts();
let body = stream::unfold(
(body.into_data_stream(), counters),
|(mut body, c)| async move {
observe(c.clone(), body.next())
.await
.map(|chunk| (chunk, (body, c)))
},
);
Response::from_parts(parts, Body::from_stream(body))
}
fn notification(level: &str, event: &str, outcome: &str) -> Value {
json!({"jsonrpc":"2.0","method":"notifications/message","params":{
"level":level,"logger":"crank-mcp-server","data":{"event":event,"outcome":outcome}}})
}
async fn reply(response: reqwest::Response) -> (Value, Vec<Value>, String) {
let status = response.status();
assert!(
status == 200 || status == 404,
"unexpected HTTP status {status}"
);
let sse = response.headers()["content-type"]
.to_str()
.unwrap()
.starts_with("text/event-stream");
let raw = tokio::time::timeout(Duration::from_secs(5), response.text())
.await
.unwrap()
.unwrap();
let mut frames: Vec<Value> = if sse {
raw.lines()
.filter_map(|line| {
line.strip_prefix("data:")
.map(|s| serde_json::from_str(s.trim()).unwrap())
})
.collect()
} else {
vec![serde_json::from_str(&raw).unwrap()]
};
let terminal = frames.pop().expect("one terminal response");
assert_eq!(terminal["jsonrpc"], "2.0");
assert_eq!(terminal["id"], 51);
assert_eq!(
status.as_u16(),
if terminal["error"]["code"] == -32601 {
404
} else {
200
}
);
if !frames.is_empty() {
assert!(sse, "notifications require SSE");
}
assert!(frames.iter().all(|f| f.get("id").is_none()));
(terminal, frames, raw)
}
fn opted(level: Value) -> Value {
let mut meta = modern_meta();
meta[LEVEL] = level;
json!({"_meta":meta})
}
async fn control(revision: &str) -> [usize; 3] {
let h = Endpoint::started().await;
let session = h.session(revision).await;
let session = session.as_deref();
// Negative opt-in controls precede any accepted level; a silent response is not enough alone.
let (body, events, _) = reply(h.post(revision, session, "tools/list", json!({})).await).await;
assert!(body["result"]["tools"].is_array());
assert!(events.is_empty());
assert_eq!(counts(&h.counters), [0; 3]);
if revision == MODERN_REVISION {
for value in [
json!("verbose"),
json!(7),
json!(null),
json!("CANARY".repeat(1000)),
] {
let (body, events, _) =
reply(h.post(revision, session, "tools/list", opted(value)).await).await;
assert!(body["result"]["tools"].is_array());
assert!(events.is_empty());
assert_eq!(counts(&h.counters), [0; 3]);
}
let (body, events, _) = reply(
h.post(
revision,
session,
"logging/setLevel",
json!({"level":"notice"}),
)
.await,
)
.await;
assert_eq!(body["error"]["code"], -32601);
assert!(events.is_empty());
assert_eq!(counts(&h.counters), [0; 3]);
} else {
for params in [
json!({}),
json!({"level":7}),
json!({"level":"CANARY".repeat(1000)}),
] {
let (body, events, raw) =
reply(h.post(revision, session, "logging/setLevel", params).await).await;
assert_eq!(body["error"]["code"], -32602);
assert_eq!(body["error"]["message"], "invalid logging level");
assert!(body.get("result").is_none());
assert!(!raw.contains("CANARY"));
assert!(raw.len() < 4096);
assert!(events.is_empty());
assert_eq!(h.counters.sdk_logging_level(), 0);
assert_eq!(h.counters.sdk_logging_notification(), 0);
}
}
let before = counts(&h.counters);
let (method, params, expected) = if revision == LEGACY_REVISION {
(
"logging/setLevel",
json!({"level":"notice"}),
notification("notice", "mcp.logging.level_applied", "applied"),
)
} else {
(
"tools/list",
opted(json!("info")),
notification("info", "mcp.request.served", "ok"),
)
};
let (body, events, raw) = reply(h.post(revision, session, method, params).await).await;
assert!(body.get("error").is_none(), "{body}");
if revision == LEGACY_REVISION {
assert_eq!(body["result"], json!({}));
} else {
assert!(body["result"]["tools"].is_array());
}
assert_eq!(events, vec![expected]);
assert!(raw.len() < 4096);
let after = counts(&h.counters);
let delta = std::array::from_fn(|i| after[i] - before[i]);
// Legacy severity persists, modern opt-in does not leak into the next request.
let (body, events, _) = reply(h.post(revision, session, "tools/list", json!({})).await).await;
assert!(body["result"]["tools"].is_array());
assert!(events.is_empty());
h.registry
.revoke_platform_api_key(
&workspace_id(),
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
&time::OffsetDateTime::now_utc(),
)
.await
.unwrap();
let before = counts(&h.counters);
let era = h.counters.snapshot();
let response = h
.post(
revision,
session,
method,
if revision == LEGACY_REVISION {
json!({"level":"notice"})
} else {
opted(json!("info"))
},
)
.await;
assert_eq!(response.status(), 401);
let raw = response.text().await.unwrap();
assert!(!raw.contains("notifications/message"));
assert_eq!(counts(&h.counters), before);
let after = h.counters.snapshot();
assert_eq!(after.era_modern, era.era_modern);
assert_eq!(after.era_legacy, era.era_legacy);
eprintln!(
"existing GREEN logging HTTP {revision}: safe SSE, result, opt-in/invalid/era/auth controls passed; SDK positive delta={delta:?}"
);
delta
}
#[tokio::test]
async fn rmcp_logging_wire_legacy() {
control(LEGACY_REVISION).await;
}
#[tokio::test]
async fn rmcp_logging_wire_modern() {
control(MODERN_REVISION).await;
}
#[tokio::test]
async fn rmcp_logging_sdk_legacy() {
assert_eq!(
control(LEGACY_REVISION).await,
[1, 1, 1],
"missing SDK legacy request/level/notification after successful HTTP wire assertions"
);
}
#[tokio::test]
async fn rmcp_logging_sdk_modern() {
assert_eq!(
control(MODERN_REVISION).await,
[0, 1, 1],
"missing SDK modern level/notification after successful HTTP wire assertions"
);
}
#[tokio::test]
async fn rmcp_logging_observer_scope_control() {
use super::{
sdk_logging_dispatch_enter, sdk_logging_level_parsed, sdk_logging_notification_serialized,
};
let a = Arc::new(CounterSet::default());
let b = Arc::new(CounterSet::default());
sdk_logging_dispatch_enter();
sdk_logging_level_parsed();
sdk_logging_notification_serialized();
assert_eq!(counts(&a), [0; 3]);
tokio::join!(
observe(a.clone(), async {
sdk_logging_dispatch_enter();
tokio::task::yield_now().await;
sdk_logging_level_parsed();
}),
observe(b.clone(), async {
sdk_logging_notification_serialized();
})
);
assert_eq!(counts(&a), [1, 1, 0]);
assert_eq!(counts(&b), [0, 0, 1]);
let body = Body::from_stream(stream::once(async {
sdk_logging_notification_serialized();
Ok::<_, std::convert::Infallible>("data: terminal\n\n")
}));
let response = observe_body(Response::new(body), a.clone());
assert_eq!(counts(&a), [1, 1, 0]);
assert_eq!(
&axum::body::to_bytes(response.into_body(), 100)
.await
.unwrap()[..],
b"data: terminal\n\n"
);
assert_eq!(counts(&a), [1, 1, 1]);
assert_eq!(counts(&b), [0, 0, 1]);
}
@@ -0,0 +1,143 @@
//! Minimal logging HTTP fixture; shared registry/auth/lifecycle fixtures remain authoritative.
use super::*;
use crank_runtime::{
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
};
pub(super) struct Endpoint {
pub registry: crank_registry::PostgresRegistry,
pub counters: Arc<CounterSet>,
key: String,
url: String,
server: tokio::task::JoinHandle<()>,
}
impl Drop for Endpoint {
fn drop(&mut self) {
self.server.abort();
}
}
impl Endpoint {
pub async fn started() -> Self {
crank_test_support::postgres_schema_url_for_task("logging_owner", "t_c28c3800").await;
let registry = test_registry().await;
let operation = test_operation("http://127.0.0.1:9");
registry
.create_operation(&workspace_id(), &operation, Some("alice"))
.await
.unwrap();
registry
.publish_operation(crank_registry::PublishRequest {
workspace_id: &workspace_id(),
operation_id: &operation.id,
version: 1,
published_at: &test_time(),
published_by: Some("alice"),
})
.await
.unwrap();
publish_agent(&registry, &operation).await;
let key = create_api_key(&registry).await;
let counters = Arc::new(CounterSet::default());
let app = crate::build_app(
registry.clone(),
Duration::ZERO,
Some("https://crank.example.com".into()),
SecretCrypto::new("test-master-key-00000000000000000000000000000000").unwrap(),
crank_runtime::community_with_outbound_policy(
crank_runtime::OutboundHttpPolicy::allowing_hosts(["127.0.0.1"]),
)
.build(),
RequestRateLimiter::new(RequestRateLimitConfig::new(10_000, 10_000).unwrap()),
Arc::new(InMemoryCoordinationStateStore::default()),
Arc::new(crate::session::InMemorySessionStore::default()),
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
);
let scope = counters.clone();
let app = app.layer(axum::middleware::from_fn(
move |request: axum::extract::Request, next: axum::middleware::Next| {
let counters = scope.clone();
async move {
let response = observe(counters.clone(), next.run(request)).await;
observe_body(response, counters)
}
},
));
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!(
"http://{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}",
listener.local_addr().unwrap()
);
let server = tokio::spawn(async move {
axum::serve(listener, app).await.unwrap();
});
Self {
registry,
counters,
key,
url,
server,
}
}
pub async fn post(
&self,
revision: &str,
session: Option<&str>,
method: &str,
mut params: Value,
) -> reqwest::Response {
let mut request = reqwest::Client::new()
.post(&self.url)
.bearer_auth(&self.key)
.header("Accept", "text/event-stream, application/json")
.header("MCP-Protocol-Version", revision);
if let Some(session) = session {
request = request.header("MCP-Session-Id", session);
}
if revision == MODERN_REVISION {
request = request.header("Mcp-Method", method);
if params.get("_meta").is_none() {
params["_meta"] = modern_meta();
}
}
request
.json(&json!({"jsonrpc":"2.0", "id":51, "method":method, "params":params}))
.send()
.await
.unwrap()
}
pub async fn session(&self, revision: &str) -> Option<String> {
if revision == MODERN_REVISION {
return None;
}
let response = self
.post(
revision,
None,
"initialize",
json!({"protocolVersion":revision,"capabilities":{}}),
)
.await;
assert_eq!(response.status(), 200);
let session = response.headers()["MCP-Session-Id"]
.to_str()
.unwrap()
.to_owned();
assert_eq!(
reply(response).await.0["result"]["protocolVersion"],
revision
);
let response = reqwest::Client::new()
.post(&self.url)
.bearer_auth(&self.key)
.header("Accept", "application/json, text/event-stream")
.header("MCP-Protocol-Version", revision)
.header("MCP-Session-Id", &session)
.json(&initialized_notification())
.send()
.await
.unwrap();
assert_eq!(response.status(), 202);
response.bytes().await.unwrap();
Some(session)
}
}
+4
View File
@@ -37,6 +37,10 @@
Prompts-срез #107 подключает `prompts/list` и `prompts/get` обеих revisions к `app/rmcp_dispatch.rs`: реальные `PaginatedRequestParams`/`GetPromptRequestParams` передают cursor/name и JSON-значения аргументов прежнему shared Prompts service; Crank `limit` сохраняется отдельно. `app/response.rs` сериализует rmcp `ListPromptsResult`/`Prompt` и `GetPromptResult`/`PromptMessage`/`ContentBlock`, используемые штатным `build_app` HTTP JSON/SSE. Lossless-проекция сохраняет typed argument schemas/defaults, extensions/optional null и существующую роль `system`, которую pinned SDK Role не представляет; она восстанавливается после SDK serialization, не меняя опубликованные message boundaries. Прежний dispatch сохраняет revision-specific result/cache projections и ошибки. HTTP ATDD проверяет wire обеих revisions и реальный SDK request/result seam отдельно; affected Prompts/composition regression — exact binding, archive, typed rendering, pinned static/dynamic Resource content и fail-closed dependency errors. Handwritten list/get builders заменены; domain/storage/auth/envelopes/transport/lifecycle не меняются. Completion, notifications/subscriptions/progress/cancel/logging не объявляются перенесёнными. Полный #107 и feature qualification (UI/full/load/p95) этим срезом не завершены.
Completion-срез #107 на базе rc.20/rmcp3.9.0 подключает `completion/complete` обеих revisions к тому же request-scoped `app/rmcp_dispatch.rs`: настоящие `CompleteRequestParams`/`Reference`/`ArgumentInfo` передают reference и argument прежнему shared service. SDK context представляет только строки, поэтому исходный Crank JSON context сохраняется отдельно без фильтрации/приведения типов и проходит прежнюю domain validation. `app/response.rs` заменяет handwritten completion builder сериализацией `CompleteResult`/`CompletionInfo`, сохраняя omission `hasMore=false`, точный bounded total либо его отсутствие при partial scan и прежнюю внешнюю modern/legacy result projection. Потребитель — штатный `build_app` MCP HTTP JSON/SSE. Runtime ATDD отдельно наблюдает SDK request/result seam и сохранение Prompt/Resource refs, pinned/archive, populated/empty/bounded результатов, safe refusals/context, correlation/IDs и revoked-key rejection. Domain/storage/auth/envelopes/transport/lifecycle не меняются; signals/logging/subscriptions ещё не перенесены. Это не завершение #107, не external-client/feature qualification и не production deployment.
Logging-срез #107 на базе rc.22/rmcp3.9.0 использует существующий общий `protocol/logging.rs`, уже подключённый к штатному `build_app` HTTP: legacy `logging/setLevel` после прежней bounded string boundary декодируется в настоящий `SetLevelRequestParams`, а modern `_meta[io.modelcontextprotocol/logLevel]` — в SDK `LoggingLevel`. Неизвестные legacy поля, включая `_meta`, остаются игнорируемыми; неверные уровни дают прежний безопасный `INVALID_LEVEL`, modern отсутствие/неверное значение не включает logging. Domain severity ordering/store сохраняются явно: SDK enum не задаёт Ord. `notifications/message.params` сериализуется через `LoggingMessageNotificationParam` только из закрытого safe vocabulary; JSON-RPC envelope остаётся прежним. HTTP ATDD наблюдает реальные SDK decode/serialization обеих revisions и revoked-auth rejection; существующая logging-матрица и streamed progress regression сохраняют opt-in/isolation/filtering/JSON silence и carried scope. Очереди, try_lock/drop, transport/session/auth/lifecycle/capabilities не меняются; собственного runtime parsing уровня и handwritten params builder больше нет. Потребитель — действующий MCP HTTP клиент; signals/progress/cancel/subscriptions/прочие notifications и envelopes/transport/lifecycle ещё не объявляются перенесёнными. Полный #107, feature qualification и production deployment этим срезом не завершены.
Проверяемый результат:
- Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.