CI / UI Checks (pull_request) Successful in 12s
CI / Rust Checks (pull_request) Successful in 30m41s
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
228 lines
9.7 KiB
Rust
228 lines
9.7 KiB
Rust
//! Small Resources fixture: existing observer helpers, exact artifact publications, normal app.
|
|
use super::*;
|
|
use crank_artifacts::ArtifactStore;
|
|
use crank_core::{Agent, AgentStatus, AgentVersion, ToolSelectionPolicy, ids::ResourceId};
|
|
use crank_registry::{
|
|
AgentResourceBinding, CreateAgentRequest, PublishAgentRequest, SaveAgentCatalogConfigRequest,
|
|
};
|
|
use crank_runtime::{
|
|
InMemoryCoordinationStateStore, RequestRateLimitConfig, RequestRateLimiter, SecretCrypto,
|
|
};
|
|
use sha2::{Digest, Sha256};
|
|
|
|
pub(super) const URI: &str = "crank://resources/sdk-a";
|
|
pub(super) const TEXT: &str = "published v1\n";
|
|
|
|
pub(super) struct Endpoint {
|
|
pub registry: crank_registry::PostgresRegistry,
|
|
pub counters: Arc<CounterSet>,
|
|
pub key: String,
|
|
pub url: String,
|
|
server: tokio::task::JoinHandle<()>,
|
|
root: std::path::PathBuf,
|
|
}
|
|
impl Drop for Endpoint {
|
|
fn drop(&mut self) {
|
|
self.server.abort();
|
|
let _ = std::fs::remove_dir_all(&self.root);
|
|
}
|
|
}
|
|
impl Endpoint {
|
|
pub async fn started() -> Self {
|
|
crank_test_support::postgres_schema_url_for_task("resources_owner", "t_73561633").await;
|
|
let registry = test_registry().await;
|
|
let root = std::env::temp_dir().join(format!("rmcp-resources-{}", uuid::Uuid::now_v7()));
|
|
std::fs::create_dir(&root).unwrap();
|
|
use std::os::unix::fs::PermissionsExt;
|
|
std::fs::set_permissions(&root, std::fs::Permissions::from_mode(0o700)).unwrap();
|
|
let store = ArtifactStore::open(&root).unwrap();
|
|
// Same immutable row shapes and real ArtifactStore::put as static_resources/fixtures.rs.
|
|
for (id, uri, name, bytes) in [
|
|
("res_sdk_a", URI, "sdk_a", TEXT),
|
|
(
|
|
"res_sdk_b",
|
|
"crank://resources/sdk-b",
|
|
"sdk_b",
|
|
"second published resource\n",
|
|
),
|
|
] {
|
|
let stored = store.put(bytes.as_bytes()).unwrap();
|
|
let digest = format!("{:x}", Sha256::digest(bytes.as_bytes()));
|
|
let source = format!("src_{id}");
|
|
sqlx::query("insert into artifact_blobs (digest, artifact_ref, size_bytes, storage_lifecycle, created_at, updated_at) values ($1,$2,$3,'available',now(),now())")
|
|
.bind(&digest).bind(format!("sha256:{digest}")).bind(stored.size_bytes as i64).execute(registry.pool()).await.unwrap();
|
|
sqlx::query("insert into artifact_sources (workspace_id,source_id,blob_digest,mime_type,sensitivity,lifecycle,created_at,updated_at) values ('ws_default',$1,$2,'text/plain','internal','active',now(),now())")
|
|
.bind(&source).bind(&digest).execute(registry.pool()).await.unwrap();
|
|
sqlx::query("insert into resources (workspace_id,resource_id,uri,name,description,status,kind,current_draft_version,created_at,updated_at) values ('ws_default',$1,$2,$3,'','published','text',1,now(),now())")
|
|
.bind(id).bind(uri).bind(name).execute(registry.pool()).await.unwrap();
|
|
sqlx::query("insert into resource_versions (workspace_id,resource_id,version,kind,mime_type,size_bytes,digest,sensitivity,artifact_source_id,created_at,superseded_at) values ('ws_default',$1,1,'text','text/plain',$2,$3,'internal',$4,now(),null)")
|
|
.bind(id).bind(stored.size_bytes as i64).bind(&digest).bind(&source).execute(registry.pool()).await.unwrap();
|
|
sqlx::query("insert into resource_publications (workspace_id,resource_id,version,uri,name,description,kind,mime_type,size_bytes,digest,sensitivity,artifact_source_id,published_at) values ('ws_default',$1,1,$2,$3,'','text','text/plain',$4,$5,'internal',$6,now())")
|
|
.bind(id).bind(uri).bind(name).bind(stored.size_bytes as i64).bind(&digest).bind(&source).execute(registry.pool()).await.unwrap();
|
|
}
|
|
registry
|
|
.create_agent(CreateAgentRequest {
|
|
agent: &Agent {
|
|
id: agent_id(),
|
|
workspace_id: workspace_id(),
|
|
slug: AGENT_SLUG.into(),
|
|
display_name: "SDK Resources".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: agent_id(),
|
|
version: 1,
|
|
status: AgentStatus::Draft,
|
|
instructions: json!({}),
|
|
tool_selection_policy: ToolSelectionPolicy::default(),
|
|
created_at: test_time(),
|
|
},
|
|
bindings: &[],
|
|
})
|
|
.await
|
|
.unwrap();
|
|
registry
|
|
.save_agent_catalog_config(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_sdk_a"),
|
|
resource_version: 1,
|
|
},
|
|
AgentResourceBinding {
|
|
resource_id: ResourceId::new("res_sdk_b"),
|
|
resource_version: 1,
|
|
},
|
|
],
|
|
expected_state: None,
|
|
})
|
|
.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();
|
|
let key = create_api_key(®istry).await;
|
|
let counters = Arc::new(CounterSet::default());
|
|
// Normal build_app composition with its sanctioned artifact root, not the isolated SDK router.
|
|
let app = crate::build_app_with_artifacts(
|
|
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),
|
|
16,
|
|
store,
|
|
);
|
|
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 {
|
|
let response = 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,
|
|
root,
|
|
}
|
|
}
|
|
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-resources-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());
|
|
if let Some(uri) = body["params"]["uri"].as_str() {
|
|
request = request.header("Mcp-Name", uri);
|
|
}
|
|
}
|
|
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)
|
|
}
|
|
}
|