CI / UI Checks (pull_request) Successful in 14s
CI / Rust Checks (pull_request) Successful in 37m47s
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
493 lines
17 KiB
Rust
493 lines
17 KiB
Rust
//! #107 Prompts: existing wire GREEN and an independent SDK typed-path RED 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_prompts_test_support.rs"]
|
|
mod fixtures;
|
|
use super::rmcp_prompts_handler_runtime_tests as handler;
|
|
use fixtures::Endpoint;
|
|
|
|
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, counters)| async move {
|
|
observe(counters.clone(), body.next())
|
|
.await
|
|
.map(|chunk| (chunk, (body, counters)))
|
|
},
|
|
);
|
|
Response::from_parts(parts, Body::from_stream(body))
|
|
}
|
|
fn counts(c: &CounterSet) -> [usize; 3] {
|
|
[
|
|
c.sdk_prompts_dispatch(),
|
|
c.sdk_prompts_list_result(),
|
|
c.sdk_prompts_get_result(),
|
|
]
|
|
}
|
|
fn request(revision: &str, method: &str, mut params: Value) -> Value {
|
|
if revision == MODERN_REVISION {
|
|
params["_meta"] = modern_meta();
|
|
}
|
|
json!({"jsonrpc":"2.0","id":9007199254740993_u64,"method":method,"params":params})
|
|
}
|
|
async fn wire(response: reqwest::Response, id: &Value, sse: bool) -> Value {
|
|
assert_eq!(response.status(), 200);
|
|
assert_eq!(response.headers()["x-request-id"], "sdk-prompts-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(id)).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"], id);
|
|
body
|
|
}
|
|
fn era(result: &Value, revision: &str, method: &str) {
|
|
if revision == MODERN_REVISION {
|
|
assert_eq!(result["resultType"], "complete", "{result}");
|
|
if method == "prompts/list" {
|
|
assert_eq!(result["ttlMs"], 0);
|
|
assert_eq!(result["cacheScope"], "private");
|
|
} else {
|
|
assert!(result.get("ttlMs").is_none(), "{result}");
|
|
assert!(result.get("cacheScope").is_none(), "{result}");
|
|
}
|
|
} else {
|
|
for key in ["resultType", "ttlMs", "cacheScope"] {
|
|
assert!(result.get(key).is_none(), "{result}");
|
|
}
|
|
}
|
|
assert!(result.get("_meta").is_none(), "{result}");
|
|
}
|
|
async fn success(
|
|
h: &Endpoint,
|
|
revision: &str,
|
|
session: Option<&str>,
|
|
method: &str,
|
|
params: Value,
|
|
sse: bool,
|
|
) -> (Value, [usize; 3]) {
|
|
let req = request(revision, method, params);
|
|
let before = counts(&h.counters);
|
|
let body = wire(h.post(revision, session, &req, sse).await, &req["id"], sse).await;
|
|
assert!(body.get("error").is_none(), "{body}");
|
|
era(&body["result"], revision, method);
|
|
let after = counts(&h.counters);
|
|
(
|
|
body["result"].clone(),
|
|
std::array::from_fn(|i| after[i] - before[i]),
|
|
)
|
|
}
|
|
pub(super) async fn control(
|
|
revision: &str,
|
|
require_handler: bool,
|
|
) -> Vec<([usize; 3], [usize; 3])> {
|
|
let h = Endpoint::started().await;
|
|
let session = h.session(revision).await;
|
|
let session = session.as_deref();
|
|
let mut deltas = Vec::new();
|
|
let mut handlers = Vec::new();
|
|
let mut first_cursor = None;
|
|
// Both revisions' JSON contract, plus modern terminal SSE through the same normal app.
|
|
let modes: &[bool] = if revision == MODERN_REVISION {
|
|
&[false, true]
|
|
} else {
|
|
&[false]
|
|
};
|
|
for &sse in modes {
|
|
let mut cursor = None;
|
|
for (page, name) in ["greeting", "archived-prompt"].iter().enumerate() {
|
|
let mut params = json!({"limit":1});
|
|
if let Some(ref cursor) = cursor {
|
|
params["cursor"] = json!(cursor);
|
|
}
|
|
let before = handler::counts(&h.counters);
|
|
let (result, delta) = success(&h, revision, session, "prompts/list", params, sse).await;
|
|
handlers.push(handler::delta(&h.counters, before, "prompts/list"));
|
|
let prompts = result["prompts"].as_array().unwrap();
|
|
assert_eq!(prompts.len(), 1, "{result}");
|
|
assert_eq!(
|
|
prompts[0],
|
|
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"}
|
|
]
|
|
})
|
|
);
|
|
cursor = result
|
|
.get("nextCursor")
|
|
.map(|v| v.as_str().unwrap().to_owned());
|
|
assert_eq!(cursor.is_some(), page == 0, "{result}");
|
|
if page == 0 {
|
|
assert_ne!(cursor.as_deref(), Some("1"));
|
|
first_cursor = cursor.clone();
|
|
}
|
|
deltas.push((delta, [1, 1, 0]));
|
|
}
|
|
for (name, args, text) in [
|
|
(
|
|
"greeting",
|
|
json!({"name":"Ada"}),
|
|
"Hello Ada count=2 enabled=true tone=warm",
|
|
),
|
|
(
|
|
"greeting",
|
|
json!({"name":"Ada","count":7,"enabled":false,"tone":"dry"}),
|
|
"Hello Ada count=7 enabled=false tone=dry",
|
|
),
|
|
(
|
|
"archived-prompt",
|
|
json!({"name":"Ada"}),
|
|
"Hello Ada count=2 enabled=true tone=warm",
|
|
),
|
|
] {
|
|
let mut previous = None;
|
|
for _ in 0..2 {
|
|
let before = handler::counts(&h.counters);
|
|
let (result, delta) = success(
|
|
&h,
|
|
revision,
|
|
session,
|
|
"prompts/get",
|
|
json!({"name":name,"arguments":args}),
|
|
sse,
|
|
)
|
|
.await;
|
|
handlers.push(handler::delta(&h.counters, before, "prompts/get"));
|
|
assert_eq!(result["description"], format!("Published {name}"));
|
|
assert_eq!(
|
|
result["messages"],
|
|
json!([
|
|
{"role":"system","content":{"type":"text","text":"Be brief."}},
|
|
{"role":"user","content":{"type":"text","text":text}}
|
|
])
|
|
);
|
|
if let Some(ref previous) = previous {
|
|
assert_eq!(&result, previous);
|
|
}
|
|
previous = Some(result);
|
|
deltas.push((delta, [1, 0, 1]));
|
|
}
|
|
}
|
|
for (arguments, reason, argument) in [
|
|
(json!({}), "missing_argument", "name"),
|
|
(
|
|
json!({"name":"Ada","extra":"x"}),
|
|
"unknown_argument",
|
|
"extra",
|
|
),
|
|
(json!({"name":5}), "argument_invalid", "name"),
|
|
(
|
|
json!({"name":"Ada","count":"7"}),
|
|
"argument_invalid",
|
|
"count",
|
|
),
|
|
(
|
|
json!({"name":"Ada","enabled":"false"}),
|
|
"argument_invalid",
|
|
"enabled",
|
|
),
|
|
(
|
|
json!({"name":"Ada","tone":"loud"}),
|
|
"argument_invalid",
|
|
"tone",
|
|
),
|
|
(
|
|
json!({"name":"x".repeat(crank_core::prompt::MAX_TEXT_BYTES + 1)}),
|
|
"argument_too_large",
|
|
"name",
|
|
),
|
|
] {
|
|
let req = request(
|
|
revision,
|
|
"prompts/get",
|
|
json!({"name":"greeting","arguments":arguments}),
|
|
);
|
|
let before = handler::counts(&h.counters);
|
|
let body = wire(h.post(revision, session, &req, sse).await, &req["id"], sse).await;
|
|
handlers.push(handler::delta(&h.counters, before, "prompts/get"));
|
|
assert_eq!(body["error"]["code"], -32602, "{body}");
|
|
assert_eq!(body["error"]["data"]["reason"], reason, "{body}");
|
|
assert_eq!(body["error"]["data"]["argument"], argument);
|
|
assert!(body.get("result").is_none(), "{body}");
|
|
for leaked in [
|
|
"Be brief.",
|
|
"Hello ",
|
|
"Changed ",
|
|
"Published unbound-prompt",
|
|
] {
|
|
assert!(!body.to_string().contains(leaked), "{body}");
|
|
}
|
|
}
|
|
let mut unavailable = None;
|
|
for name in [
|
|
"draft-prompt",
|
|
"unbound-prompt",
|
|
"other-agent-prompt",
|
|
"never-existed",
|
|
"prm_a",
|
|
] {
|
|
let req = request(revision, "prompts/get", json!({"name":name}));
|
|
let before = handler::counts(&h.counters);
|
|
let body = wire(h.post(revision, session, &req, sse).await, &req["id"], sse).await;
|
|
handlers.push(handler::delta(&h.counters, before, "prompts/get"));
|
|
assert_eq!(body["error"]["code"], -32602, "{body}");
|
|
assert_eq!(
|
|
body["error"]["message"],
|
|
"the requested prompt is not available"
|
|
);
|
|
assert!(body.get("result").is_none());
|
|
if let Some(ref previous) = unavailable {
|
|
assert_eq!(&body, previous);
|
|
}
|
|
unavailable = Some(body);
|
|
}
|
|
}
|
|
for params in [json!({"cursor":"invalid"}), json!({"limit":"invalid"})] {
|
|
let before = handler::counts(&h.counters);
|
|
let req = request(revision, "prompts/list", params.clone());
|
|
let body = wire(
|
|
h.post(revision, session, &req, false).await,
|
|
&req["id"],
|
|
false,
|
|
)
|
|
.await;
|
|
assert_eq!(body["error"]["code"], -32602, "{body}");
|
|
if params.get("cursor").is_some() {
|
|
handlers.push(handler::delta(&h.counters, before, "prompts/list"));
|
|
} else {
|
|
assert_eq!(
|
|
handler::counts(&h.counters),
|
|
before,
|
|
"parsing rejects must not enter handlers"
|
|
);
|
|
}
|
|
}
|
|
let other = if revision == MODERN_REVISION {
|
|
LEGACY_REVISION
|
|
} else {
|
|
MODERN_REVISION
|
|
};
|
|
let other_session = h.session(other).await;
|
|
let req = request(
|
|
other,
|
|
"prompts/list",
|
|
json!({"cursor":first_cursor.unwrap()}),
|
|
);
|
|
let body = wire(
|
|
h.post(other, other_session.as_deref(), &req, false).await,
|
|
&req["id"],
|
|
false,
|
|
)
|
|
.await;
|
|
assert_eq!(
|
|
body["error"]["code"], -32602,
|
|
"cross-revision cursor: {body}"
|
|
);
|
|
// Archive keeps serving v1 above, but disallows new publications and bindings.
|
|
use crank_core::ids::PromptId;
|
|
use crank_registry::model::{
|
|
AgentPromptBinding, PublishPromptRequest, SaveAgentCatalogConfigRequest,
|
|
};
|
|
let publication = h
|
|
.registry
|
|
.publish_prompt_draft(PublishPromptRequest {
|
|
workspace_id: workspace_id(),
|
|
prompt_id: PromptId::new("prm_b"),
|
|
expected_updated_at: h.archived_at,
|
|
published_at: time::OffsetDateTime::now_utc(),
|
|
})
|
|
.await;
|
|
assert!(
|
|
matches!(
|
|
publication,
|
|
Err(crank_registry::RegistryError::PromptNotDraft { .. })
|
|
),
|
|
"{publication:?}"
|
|
);
|
|
let binding = h
|
|
.registry
|
|
.save_agent_catalog_config_editable_with_prompts(
|
|
SaveAgentCatalogConfigRequest {
|
|
workspace_id: &workspace_id(),
|
|
agent_id: &agent_id(),
|
|
agent_version: 1,
|
|
bindings: &[],
|
|
tool_selection_policy: &crank_core::ToolSelectionPolicy::default(),
|
|
resource_bindings: &[],
|
|
expected_state: None,
|
|
},
|
|
&[AgentPromptBinding {
|
|
prompt_id: PromptId::new("prm_b"),
|
|
prompt_version: 1,
|
|
}],
|
|
)
|
|
.await;
|
|
assert!(
|
|
matches!(
|
|
binding,
|
|
Err(crank_registry::RegistryError::PromptArchived { .. })
|
|
),
|
|
"{binding:?}"
|
|
);
|
|
sqlx::query(
|
|
"update platform_api_keys set scopes_json = '[]'::jsonb where id = 'pk_dispatch_observer'",
|
|
)
|
|
.execute(h.registry.pool())
|
|
.await
|
|
.unwrap();
|
|
for (method, params) in [
|
|
("prompts/list", json!({})),
|
|
("prompts/get", json!({"name":"greeting"})),
|
|
] {
|
|
let before = handler::counts(&h.counters);
|
|
let req = request(revision, method, params);
|
|
assert_eq!(h.post(revision, session, &req, false).await.status(), 403);
|
|
assert_eq!(
|
|
handler::counts(&h.counters),
|
|
before,
|
|
"scope rejects must precede handlers"
|
|
);
|
|
}
|
|
sqlx::query("update platform_api_keys set scopes_json = '[\"read\",\"write\"]'::jsonb where id = 'pk_dispatch_observer'")
|
|
.execute(h.registry.pool()).await.unwrap();
|
|
h.registry
|
|
.revoke_platform_api_key(
|
|
&workspace_id(),
|
|
&crank_core::PlatformApiKeyId::new("pk_dispatch_observer"),
|
|
&time::OffsetDateTime::now_utc(),
|
|
)
|
|
.await
|
|
.unwrap();
|
|
for (method, params) in [
|
|
("prompts/list", json!({})),
|
|
(
|
|
"prompts/get",
|
|
json!({"name":"greeting","arguments":{"name":"Ada"}}),
|
|
),
|
|
] {
|
|
let before = handler::counts(&h.counters);
|
|
assert_eq!(
|
|
h.post(revision, session, &request(revision, method, params), false)
|
|
.await
|
|
.status(),
|
|
401
|
|
);
|
|
assert_eq!(
|
|
handler::counts(&h.counters),
|
|
before,
|
|
"revocation must precede handlers"
|
|
);
|
|
}
|
|
eprintln!(
|
|
"existing GREEN Prompts wire {revision}: populated pagination, typed metadata/values, exact immutable rendering, archive, structured refusals/non-disclosure, correlation/ID/cache, revoked401; SDK actual/expected={deltas:?}"
|
|
);
|
|
if require_handler {
|
|
assert!(
|
|
handlers.iter().all(|(actual, expected)| actual == expected),
|
|
"SDK Prompts handler completion/consumption missing after successful HTTP wire/error/guard checks: {handlers:?}"
|
|
);
|
|
}
|
|
deltas
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_prompts_wire_legacy() {
|
|
control(LEGACY_REVISION, false).await;
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_prompts_wire_modern() {
|
|
control(MODERN_REVISION, false).await;
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_prompts_sdk_legacy() {
|
|
let deltas = control(LEGACY_REVISION, false).await;
|
|
assert!(
|
|
deltas.iter().all(|(a, e)| a == e),
|
|
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
|
);
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_prompts_sdk_modern() {
|
|
let deltas = control(MODERN_REVISION, false).await;
|
|
assert!(
|
|
deltas.iter().all(|(a, e)| a == e),
|
|
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
|
);
|
|
}
|
|
#[tokio::test]
|
|
async fn rmcp_prompts_observer_scope_control() {
|
|
use super::{
|
|
sdk_prompts_dispatch_enter, sdk_prompts_get_result_serialized,
|
|
sdk_prompts_list_result_serialized,
|
|
};
|
|
let a = Arc::new(CounterSet::default());
|
|
let b = Arc::new(CounterSet::default());
|
|
sdk_prompts_dispatch_enter();
|
|
assert_eq!(counts(&a), [0; 3]);
|
|
let snapshot = a.snapshot();
|
|
observe(a.clone(), async {
|
|
sdk_prompts_dispatch_enter();
|
|
sdk_prompts_list_result_serialized();
|
|
sdk_prompts_get_result_serialized();
|
|
})
|
|
.await;
|
|
observe(b.clone(), async {
|
|
sdk_prompts_get_result_serialized();
|
|
})
|
|
.await;
|
|
assert_eq!(counts(&a), [1; 3]);
|
|
assert_eq!(counts(&b), [0, 0, 1]);
|
|
assert_eq!(a.snapshot(), snapshot);
|
|
let body = Body::from_stream(stream::once(async {
|
|
sdk_prompts_list_result_serialized();
|
|
Ok::<_, std::convert::Infallible>("terminal")
|
|
}));
|
|
let response = observe_body(Response::new(body), b.clone());
|
|
assert_eq!(
|
|
&axum::body::to_bytes(response.into_body(), 100)
|
|
.await
|
|
.unwrap()[..],
|
|
b"terminal"
|
|
);
|
|
assert_eq!(counts(&b), [0, 1, 1]);
|
|
assert_eq!(counts(&a), [1; 3]);
|
|
}
|