CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Successful in 40m16s
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
283 lines
9.9 KiB
Rust
283 lines
9.9 KiB
Rust
//! Small real catalog fixture; broader Resource/Prompt mutations stay in mcp_signals::scenarios.
|
|
use super::{CounterSet, support::*};
|
|
use crank_core::{AgentStatus, AgentVersion, ToolSelectionPolicy};
|
|
use crank_registry::{CreateAgentDraftVersionRequest, PublishAgentRequest, PublishRequest};
|
|
use crank_runtime::{
|
|
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
|
};
|
|
use serde_json::{Value, json};
|
|
use std::{sync::Arc, time::Duration};
|
|
|
|
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 {
|
|
// First caller labels the shared, exit-cleaned disposable PostgreSQL with this owner.
|
|
crank_test_support::postgres_schema_url_for_task("signals_owner", "t_35c2ce53").await;
|
|
let registry = test_registry().await;
|
|
// This fixture only lists/removes a Tool; no upstream execution is needed.
|
|
let operation = test_operation("http://127.0.0.1:9");
|
|
registry
|
|
.create_operation(&workspace_id(), &operation, Some("alice"))
|
|
.await
|
|
.unwrap();
|
|
registry
|
|
.publish_operation(PublishRequest {
|
|
workspace_id: &workspace_id(),
|
|
operation_id: &operation.id,
|
|
version: 1,
|
|
published_at: &test_time(),
|
|
published_by: Some("alice"),
|
|
})
|
|
.await
|
|
.unwrap();
|
|
publish_agent(®istry, &operation).await;
|
|
let key = create_api_key(®istry).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);
|
|
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,
|
|
) -> reqwest::Response {
|
|
let mut request = reqwest::Client::new()
|
|
.post(&self.url)
|
|
.bearer_auth(&self.key)
|
|
.header("Accept", "application/json, text/event-stream")
|
|
.header("MCP-Protocol-Version", revision);
|
|
if revision == MODERN_REVISION {
|
|
request = request.header("Mcp-Method", body["method"].as_str().unwrap());
|
|
}
|
|
if let Some(session) = session {
|
|
request = request.header("MCP-Session-Id", session);
|
|
}
|
|
tokio::time::timeout(Duration::from_secs(6), request.json(&body).send())
|
|
.await
|
|
.unwrap()
|
|
.unwrap()
|
|
}
|
|
pub async fn listen(&self, id: Value, notifications: Value) -> Events {
|
|
Events::open(
|
|
self.post(
|
|
MODERN_REVISION,
|
|
None,
|
|
json!({
|
|
"jsonrpc":"2.0", "id":id, "method":"subscriptions/listen",
|
|
"params":{"_meta":modern_meta(), "notifications":notifications}
|
|
}),
|
|
)
|
|
.await,
|
|
)
|
|
}
|
|
pub async fn session(&self) -> String {
|
|
let response = self.post(LEGACY_REVISION, None, legacy_initialize(1)).await;
|
|
assert_eq!(response.status(), 200);
|
|
let session = response.headers()["MCP-Session-Id"]
|
|
.to_str()
|
|
.unwrap()
|
|
.to_owned();
|
|
let body = terminal(response).await;
|
|
assert_eq!(body["result"]["protocolVersion"], LEGACY_REVISION);
|
|
let response = self
|
|
.post(LEGACY_REVISION, Some(&session), initialized_notification())
|
|
.await;
|
|
assert_eq!(response.status(), 202);
|
|
session
|
|
}
|
|
pub async fn legacy_stream(&self, session: &str) -> Events {
|
|
let response = tokio::time::timeout(
|
|
Duration::from_secs(6),
|
|
reqwest::Client::new()
|
|
.get(&self.url)
|
|
.bearer_auth(&self.key)
|
|
.header("Accept", "text/event-stream")
|
|
.header("MCP-Protocol-Version", LEGACY_REVISION)
|
|
.header("MCP-Session-Id", session)
|
|
.send(),
|
|
)
|
|
.await
|
|
.unwrap()
|
|
.unwrap();
|
|
Events::open(response)
|
|
}
|
|
pub async fn tools(&self, revision: &str, session: Option<&str>) -> Value {
|
|
let params = if revision == MODERN_REVISION {
|
|
json!({"_meta":modern_meta()})
|
|
} else {
|
|
json!({})
|
|
};
|
|
terminal(
|
|
self.post(
|
|
revision,
|
|
session,
|
|
json!({"jsonrpc":"2.0","id":2,"method":"tools/list","params":params}),
|
|
)
|
|
.await,
|
|
)
|
|
.await
|
|
}
|
|
pub async fn draft_without_tools(&self) {
|
|
self.registry
|
|
.create_agent_draft_version(CreateAgentDraftVersionRequest {
|
|
workspace_id: &workspace_id(),
|
|
agent_id: &agent_id(),
|
|
version: &AgentVersion {
|
|
agent_id: agent_id(),
|
|
version: 2,
|
|
status: AgentStatus::Draft,
|
|
instructions: json!({}),
|
|
tool_selection_policy: ToolSelectionPolicy::default(),
|
|
created_at: test_time(),
|
|
},
|
|
bindings: &[],
|
|
updated_at: &test_time(),
|
|
})
|
|
.await
|
|
.unwrap();
|
|
}
|
|
pub async fn publish_without_tools(&self) {
|
|
self.registry
|
|
.publish_agent(PublishAgentRequest {
|
|
workspace_id: &workspace_id(),
|
|
agent_id: &agent_id(),
|
|
version: 2,
|
|
published_at: &test_time(),
|
|
published_by: Some("alice"),
|
|
expected_state: None,
|
|
})
|
|
.await
|
|
.unwrap();
|
|
}
|
|
}
|
|
|
|
pub(super) struct Events {
|
|
response: reqwest::Response,
|
|
buffer: Vec<u8>,
|
|
}
|
|
impl Events {
|
|
pub fn open(response: reqwest::Response) -> Self {
|
|
assert_eq!(response.status(), 200, "notification stream must open");
|
|
assert!(
|
|
response.headers()["content-type"]
|
|
.to_str()
|
|
.unwrap()
|
|
.starts_with("text/event-stream")
|
|
);
|
|
Self {
|
|
response,
|
|
buffer: Vec::new(),
|
|
}
|
|
}
|
|
// One absolute deadline: keepalive comments cannot extend a missing-frame assertion forever.
|
|
pub async fn next(&mut self, wait: Duration) -> Option<Value> {
|
|
let deadline = tokio::time::Instant::now() + wait;
|
|
loop {
|
|
if let Some(index) = self.buffer.windows(2).position(|w| w == b"\n\n") {
|
|
let frame: Vec<u8> = self.buffer.drain(..index + 2).collect();
|
|
let frame = std::str::from_utf8(&frame).unwrap();
|
|
if let Some(data) = frame.lines().find_map(|line| line.strip_prefix("data:")) {
|
|
return Some(serde_json::from_str(data.trim()).expect("SSE data must be JSON"));
|
|
}
|
|
continue;
|
|
}
|
|
match tokio::time::timeout_at(deadline, self.response.chunk()).await {
|
|
Err(_) => return None,
|
|
Ok(Err(error)) => panic!("SSE transport failure, not silence: {error}"),
|
|
Ok(Ok(None)) => panic!("SSE closed unexpectedly, not silence"),
|
|
Ok(Ok(Some(bytes))) => self.buffer.extend_from_slice(&bytes),
|
|
}
|
|
}
|
|
}
|
|
pub async fn frame(&mut self) -> Value {
|
|
self.next(Duration::from_secs(6))
|
|
.await
|
|
.expect("notification must arrive before deadline")
|
|
}
|
|
pub async fn silent(&mut self) {
|
|
assert_eq!(
|
|
self.next(Duration::from_millis(2200)).await,
|
|
None,
|
|
"no duplicate/unrequested signal"
|
|
);
|
|
}
|
|
}
|
|
|
|
pub(super) async fn terminal(response: reqwest::Response) -> Value {
|
|
let status = response.status();
|
|
assert!(
|
|
status == 200 || status == 404,
|
|
"unexpected terminal status {status}"
|
|
);
|
|
let sse = response.headers()["content-type"]
|
|
.to_str()
|
|
.unwrap()
|
|
.starts_with("text/event-stream");
|
|
let raw = tokio::time::timeout(Duration::from_secs(6), response.text())
|
|
.await
|
|
.unwrap()
|
|
.unwrap();
|
|
let body: Value = if sse {
|
|
let frames: Vec<Value> = raw
|
|
.lines()
|
|
.filter_map(|line| line.strip_prefix("data:"))
|
|
.map(|data| serde_json::from_str(data.trim()).unwrap())
|
|
.collect();
|
|
assert_eq!(
|
|
frames.len(),
|
|
1,
|
|
"one terminal frame, no notification: {raw}"
|
|
);
|
|
frames.into_iter().next().unwrap()
|
|
} else {
|
|
serde_json::from_str(&raw).unwrap()
|
|
};
|
|
assert_eq!(
|
|
status.as_u16(),
|
|
if body["error"]["code"] == -32601 {
|
|
404
|
|
} else {
|
|
200
|
|
}
|
|
);
|
|
body
|
|
}
|