refactor(mcp): route Resources requests and results through rmcp SDK
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
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
This commit is contained in:
1 parent
adabb2065a
commit
027e2cb911
8 files changed
+836
-51
No files matched your search
@@ -7,7 +7,9 @@
|
||||
|
||||
use super::request::{InitializeParams, ToolCallParams};
|
||||
use super::response::take_confirmation_token;
|
||||
use super::rmcp_dispatch::handle_tools_command;
|
||||
use super::rmcp_dispatch::{
|
||||
handle_resources_command, handle_tools_command, list_resource_templates,
|
||||
};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
jsonrpc::{
|
||||
@@ -20,7 +22,7 @@ use crate::{
|
||||
ResourceReadCommand, ResourcesCommand, ResourcesListCommand, ResourcesOutcome,
|
||||
ServiceContext, ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome,
|
||||
declared_mcp_method, discover_result, handle_completion_command, handle_prompts_command,
|
||||
handle_resources_command, validate_modern_request_name,
|
||||
validate_modern_request_name,
|
||||
},
|
||||
session::SessionState,
|
||||
tool_error::execution_locale,
|
||||
@@ -43,7 +45,7 @@ use super::response::{
|
||||
resource_templates_list_result, resources_list_result, tools_list_result,
|
||||
};
|
||||
use super::{AgentRoutePath, AppState, TRANSPORT_SESSION_TTL_MS};
|
||||
use crate::protocol::{ResourceTemplatesListError, list_resource_templates};
|
||||
use crate::protocol::ResourceTemplatesListError;
|
||||
const SERVER_NAME: &str = "crank-mcp-server";
|
||||
const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
|
||||
@@ -286,10 +288,10 @@ pub(super) async fn handle_modern_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
resources_list_result(resources, next_cursor),
|
||||
),
|
||||
match resources_list_result(resources, next_cursor, version) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -345,10 +347,10 @@ pub(super) async fn handle_modern_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
resource_read_result(contents),
|
||||
),
|
||||
match resource_read_result(contents, version) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -434,10 +436,10 @@ pub(super) async fn handle_modern_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
resource_templates_list_result(templates, next_cursor),
|
||||
),
|
||||
match resource_templates_list_result(templates, next_cursor, version) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
|
||||
@@ -54,9 +54,30 @@ pub(crate) struct CounterSet {
|
||||
sdk_tools_dispatch: AtomicUsize,
|
||||
sdk_tools_list_result: AtomicUsize,
|
||||
sdk_tools_call_result: AtomicUsize,
|
||||
sdk_resources_dispatch: AtomicUsize,
|
||||
sdk_resources_list_result: AtomicUsize,
|
||||
sdk_resources_read_result: AtomicUsize,
|
||||
sdk_resource_templates_list_result: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CounterSet {
|
||||
pub(crate) fn sdk_resources_dispatch(&self) -> usize {
|
||||
self.sdk_resources_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_resources_list_result(&self) -> usize {
|
||||
self.sdk_resources_list_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_resources_read_result(&self) -> usize {
|
||||
self.sdk_resources_read_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
pub(crate) fn sdk_resource_templates_list_result(&self) -> usize {
|
||||
self.sdk_resource_templates_list_result
|
||||
.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// SDK typed Tools dispatch entries, separate from the existing era/service snapshot.
|
||||
pub(crate) fn sdk_tools_dispatch(&self) -> usize {
|
||||
self.sdk_tools_dispatch.load(Ordering::SeqCst)
|
||||
@@ -167,6 +188,30 @@ pub(crate) fn sdk_tools_call_result_serialized() {
|
||||
increment(|counters| &counters.sdk_tools_call_result);
|
||||
}
|
||||
|
||||
/// Mark only after converting a Resources request through the real SDK typed path.
|
||||
pub(crate) fn sdk_resources_dispatch_enter() {
|
||||
increment(|counters| &counters.sdk_resources_dispatch);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK ListResourcesResult.
|
||||
pub(crate) fn sdk_resources_list_result_serialized() {
|
||||
increment(|counters| &counters.sdk_resources_list_result);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK ReadResourceResult.
|
||||
pub(crate) fn sdk_resources_read_result_serialized() {
|
||||
increment(|counters| &counters.sdk_resources_read_result);
|
||||
}
|
||||
|
||||
/// Mark only after successfully serializing a real SDK ListResourceTemplatesResult.
|
||||
pub(crate) fn sdk_resource_templates_list_result_serialized() {
|
||||
increment(|counters| &counters.sdk_resource_templates_list_result);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "../rmcp_resources_runtime_tests.rs"]
|
||||
mod rmcp_resources_runtime_tests;
|
||||
|
||||
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||
let _ = OBSERVER.try_with(|counters| {
|
||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
@@ -24,7 +24,9 @@ use super::response::{
|
||||
resource_templates_list_result, resources_list_result, take_confirmation_token,
|
||||
tools_list_result,
|
||||
};
|
||||
use super::rmcp_dispatch::handle_tools_command;
|
||||
use super::rmcp_dispatch::{
|
||||
handle_resources_command, handle_tools_command, list_resource_templates,
|
||||
};
|
||||
use super::{AgentRoutePath, AppState};
|
||||
use crate::{
|
||||
auth::VerifiedMachineCredential,
|
||||
@@ -38,7 +40,7 @@ use crate::{
|
||||
PromptsCommand, PromptsListCommand, PromptsOutcome, RequestIdentity, ResourceReadCommand,
|
||||
ResourcesCommand, ResourcesListCommand, ResourcesOutcome, ServiceContext, SetLevelCommand,
|
||||
ToolCallCommand, ToolsCommand, ToolsListCommand, ToolsOutcome, handle_completion_command,
|
||||
handle_logging_command, handle_prompts_command, handle_resources_command,
|
||||
handle_logging_command, handle_prompts_command,
|
||||
},
|
||||
tool_error::execution_locale,
|
||||
transport::{ResponseMode, session_id_from_headers, transport_response},
|
||||
@@ -283,7 +285,14 @@ pub(super) async fn handle_legacy_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
resources_list_result(resources, next_cursor),
|
||||
match resources_list_result(
|
||||
resources,
|
||||
next_cursor,
|
||||
&session.protocol_version,
|
||||
) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
@@ -340,7 +349,13 @@ pub(super) async fn handle_legacy_request(
|
||||
match outcome {
|
||||
ResourcesOutcome::Read { contents } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), resource_read_result(contents)),
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
match resource_read_result(contents, &session.protocol_version) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
@@ -399,7 +414,7 @@ pub(super) async fn handle_legacy_request(
|
||||
);
|
||||
}
|
||||
};
|
||||
let (templates, next_cursor) = match crate::protocol::list_resource_templates(
|
||||
let (templates, next_cursor) = match list_resource_templates(
|
||||
&state,
|
||||
&path.workspace_slug,
|
||||
&path.agent_slug,
|
||||
@@ -430,7 +445,14 @@ pub(super) async fn handle_legacy_request(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
resource_templates_list_result(templates, next_cursor),
|
||||
match resource_templates_list_result(
|
||||
templates,
|
||||
next_cursor,
|
||||
&session.protocol_version,
|
||||
) {
|
||||
Ok(result) => result,
|
||||
Err(error) => return internal_jsonrpc_error(message, error),
|
||||
},
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
|
||||
@@ -128,32 +128,115 @@ pub(super) fn tools_list_result(
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The era-neutral `resources/list` result shape (Story 3.8). Same pagination wire keys as
|
||||
/// `tools/list`; `nextCursor` is absent on the last page.
|
||||
pub(super) fn resources_list_result(resources: Vec<Value>, next_cursor: Option<String>) -> Value {
|
||||
let mut result = json!({ "resources": resources });
|
||||
if let Some(next_cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(next_cursor);
|
||||
}
|
||||
result
|
||||
/// SDK results are serialized before the minimal lossless projection of descriptor extensions.
|
||||
pub(super) fn resources_list_result(
|
||||
resources: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
let result = rmcp::model::ListResourcesResult {
|
||||
resources: resources
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(serde_json::from_value)
|
||||
.collect::<Result<_, _>>()?,
|
||||
next_cursor,
|
||||
result_type: modern.then_some(ResultType::COMPLETE),
|
||||
ttl_ms: modern.then_some(0),
|
||||
cache_scope: modern.then_some(CacheScope::Private),
|
||||
meta: None,
|
||||
};
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_list_result_serialized();
|
||||
preserve_resource_fields(
|
||||
&resources,
|
||||
&mut result["resources"],
|
||||
&[
|
||||
"uri",
|
||||
"name",
|
||||
"title",
|
||||
"description",
|
||||
"mimeType",
|
||||
"size",
|
||||
"_meta",
|
||||
],
|
||||
);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The era-neutral `resources/read` result shape: exactly the typed `contents[]` the revision
|
||||
/// converter produced.
|
||||
pub(super) fn resource_read_result(contents: Value) -> Value {
|
||||
json!({ "contents": contents })
|
||||
pub(super) fn resource_read_result(
|
||||
contents: Value,
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let mut result =
|
||||
rmcp::model::ReadResourceResult::new(serde_json::from_value(contents.clone())?);
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
result.result_type = modern.then_some(ResultType::COMPLETE);
|
||||
result.ttl_ms = modern.then_some(0);
|
||||
result.cache_scope = modern.then_some(CacheScope::Private);
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_read_result_serialized();
|
||||
preserve_resource_fields(
|
||||
contents.as_array().expect("validated contents array"),
|
||||
&mut result["contents"],
|
||||
&["uri", "mimeType", "text", "blob", "_meta"],
|
||||
);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
/// The era-neutral `resources/templates/list` result shape.
|
||||
pub(super) fn resource_templates_list_result(
|
||||
templates: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
) -> Value {
|
||||
let mut result = json!({ "resourceTemplates": templates });
|
||||
if let Some(cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(cursor);
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let modern = version == crate::jsonrpc::MODERN_PROTOCOL_VERSION;
|
||||
let result = rmcp::model::ListResourceTemplatesResult {
|
||||
resource_templates: templates
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(serde_json::from_value)
|
||||
.collect::<Result<_, _>>()?,
|
||||
next_cursor,
|
||||
result_type: modern.then_some(ResultType::COMPLETE),
|
||||
ttl_ms: modern.then_some(0),
|
||||
cache_scope: modern.then_some(CacheScope::Private),
|
||||
meta: None,
|
||||
};
|
||||
let mut result = serde_json::to_value(result)?;
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resource_templates_list_result_serialized();
|
||||
preserve_resource_fields(
|
||||
&templates,
|
||||
&mut result["resourceTemplates"],
|
||||
&[
|
||||
"uriTemplate",
|
||||
"name",
|
||||
"title",
|
||||
"description",
|
||||
"mimeType",
|
||||
"_meta",
|
||||
],
|
||||
);
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
// Pinned SDK serde drops unknown fields and optional nulls, including Crank template parameters.
|
||||
// Treat annotations/icons as opaque too: their nested extensions are not represented by the SDK.
|
||||
fn preserve_resource_fields(raw: &[Value], serialized: &mut Value, sdk_fields: &[&str]) {
|
||||
for (raw, serialized) in raw
|
||||
.iter()
|
||||
.zip(serialized.as_array_mut().expect("SDK array"))
|
||||
{
|
||||
let serialized = serialized.as_object_mut().expect("SDK object");
|
||||
for (key, value) in raw.as_object().expect("validated resource object") {
|
||||
if !sdk_fields.contains(&key.as_str()) || value.is_null() {
|
||||
serialized.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// The era-neutral `prompts/list` result shape (Story 3.14). Same pagination wire keys as
|
||||
@@ -327,11 +410,94 @@ pub(super) fn resource_error_response(
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn internal_jsonrpc_error(message: &Value, _error: impl std::fmt::Display) -> Response {
|
||||
transport_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
jsonrpc_error(request_id(message), -32603, "internal server error"),
|
||||
ResponseMode::Json,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sdk_result_tests {
|
||||
use super::*;
|
||||
use crate::jsonrpc::{LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION};
|
||||
|
||||
#[test]
|
||||
fn resources_sdk_projection_is_lossless_for_templates_contents_and_catalog() {
|
||||
for version in [LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION] {
|
||||
for optional in [Value::Null, json!({}), json!({"x-extension":[null,{}]})] {
|
||||
let raw = json!({"uri":"crank://r","name":"r","description":null,
|
||||
"mimeType":"text/plain","_meta":optional,"x-resource":[],
|
||||
"annotations":{"x-nested":null},"icons":[{"src":"icon","x-icon":{}}]});
|
||||
for cursor in [None, Some(String::new()), Some("opaque".to_owned())] {
|
||||
let list =
|
||||
resources_list_result(vec![raw.clone()], cursor.clone(), version).unwrap();
|
||||
assert_eq!(list["resources"], json!([raw]));
|
||||
assert_eq!(
|
||||
list.get("nextCursor"),
|
||||
cursor.as_ref().map(|s| json!(s)).as_ref()
|
||||
);
|
||||
assert_eq!(
|
||||
list.get("resultType").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
list.get("ttlMs").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
list.get("cacheScope").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert!(list.get("_meta").is_none());
|
||||
let template = json!({"uriTemplate":"crank://r/{id}","name":"r",
|
||||
"description":null,"mimeType":null,"_meta":optional,
|
||||
"parameters":[{"name":"id","required":true,"opaque":null}],
|
||||
"annotations":{"x-nested":[]},"icons":null});
|
||||
let list = resource_templates_list_result(
|
||||
vec![template.clone()],
|
||||
cursor.clone(),
|
||||
version,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(list["resourceTemplates"], json!([template]));
|
||||
assert_eq!(
|
||||
list.get("nextCursor"),
|
||||
cursor.as_ref().map(|s| json!(s)).as_ref()
|
||||
);
|
||||
}
|
||||
let contents = json!([
|
||||
{"uri":"crank://r","mimeType":null,"text":"\0é\n","_meta":optional,"x-content":[]},
|
||||
{"uri":"crank://b","mimeType":"application/octet-stream","blob":"AP8=","_meta":null}
|
||||
]);
|
||||
assert_eq!(
|
||||
resource_read_result(contents.clone(), version).unwrap()["contents"],
|
||||
contents
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
resources_list_result(vec![], None, version).unwrap()["resources"],
|
||||
json!([])
|
||||
);
|
||||
assert_eq!(
|
||||
resource_templates_list_result(vec![], None, version).unwrap()["resourceTemplates"],
|
||||
json!([])
|
||||
);
|
||||
assert_eq!(
|
||||
resource_read_result(json!([]), version).unwrap()["contents"],
|
||||
json!([])
|
||||
);
|
||||
assert!(resources_list_result(vec![json!({"uri":42})], None, version).is_err());
|
||||
assert!(
|
||||
resource_templates_list_result(vec![json!({"name":"r"})], None, version).is_err()
|
||||
);
|
||||
assert!(resource_read_result(json!([{"uri":"r"}]), version).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn catalog_projection_preserves_extensions_null_and_empty() {
|
||||
let descriptor = json!({
|
||||
@@ -407,13 +573,3 @@ mod sdk_result_tests {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn internal_jsonrpc_error(message: &Value, _error: impl std::fmt::Display) -> Response {
|
||||
transport_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
jsonrpc_error(request_id(message), -32603, "internal server error"),
|
||||
ResponseMode::Json,
|
||||
None,
|
||||
None,
|
||||
)
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
//! Runtime SDK Tools dispatch; admission, lifecycle and response projection stay with the caller.
|
||||
//! Runtime SDK dispatch; admission, lifecycle and response projection stay with the caller.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use rmcp::model::{CallToolRequestParams, PaginatedRequestParams};
|
||||
use rmcp::model::{CallToolRequestParams, PaginatedRequestParams, ReadResourceRequestParams};
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{AppState, lifecycle::ToolCallLifecycle};
|
||||
@@ -65,3 +65,47 @@ pub(super) async fn handle_tools_command(
|
||||
};
|
||||
crate::protocol::handle_tools_command(state, context, command, lifecycle).await
|
||||
}
|
||||
|
||||
pub(super) async fn handle_resources_command(
|
||||
state: &Arc<AppState>,
|
||||
context: ServiceContext<'_>,
|
||||
revision: &str,
|
||||
command: crate::protocol::ResourcesCommand,
|
||||
) -> crate::protocol::ResourcesOutcome {
|
||||
use crate::protocol::{ResourceReadCommand, ResourcesCommand};
|
||||
let command = match command {
|
||||
ResourcesCommand::List(list) => ResourcesCommand::List(sdk_resource_page(list)),
|
||||
ResourcesCommand::Read(read) => {
|
||||
let params = ReadResourceRequestParams::new(read.uri);
|
||||
ResourcesCommand::Read(ResourceReadCommand { uri: params.uri })
|
||||
}
|
||||
};
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_dispatch_enter();
|
||||
crate::protocol::handle_resources_command(state, context, revision, command).await
|
||||
}
|
||||
|
||||
pub(super) async fn list_resource_templates(
|
||||
state: &Arc<AppState>,
|
||||
workspace_slug: &str,
|
||||
agent_slug: &str,
|
||||
revision: &str,
|
||||
command: crate::protocol::ResourcesListCommand,
|
||||
) -> Result<(Vec<Value>, Option<String>), crate::protocol::ResourceTemplatesListError> {
|
||||
let command = sdk_resource_page(command);
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_resources_dispatch_enter();
|
||||
crate::protocol::list_resource_templates(state, workspace_slug, agent_slug, revision, command)
|
||||
.await
|
||||
}
|
||||
|
||||
fn sdk_resource_page(
|
||||
list: crate::protocol::ResourcesListCommand,
|
||||
) -> crate::protocol::ResourcesListCommand {
|
||||
let params = PaginatedRequestParams::default().with_cursor(list.cursor);
|
||||
// Crank's page limit is not an SDK field; retain its existing validation and clamping.
|
||||
crate::protocol::ResourcesListCommand {
|
||||
cursor: params.cursor,
|
||||
limit: list.limit,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
//! #107 Resources: existing wire GREEN is independent of the missing SDK typed-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_resources_test_support.rs"]
|
||||
mod fixtures;
|
||||
use fixtures::{Endpoint, TEXT, URI};
|
||||
|
||||
// As in rmcp_result_runtime_tests: deferred body polling keeps this request's observer.
|
||||
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; 4] {
|
||||
[
|
||||
c.sdk_resources_dispatch(),
|
||||
c.sdk_resources_list_result(),
|
||||
c.sdk_resources_read_result(),
|
||||
c.sdk_resource_templates_list_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-resources-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) {
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(result["resultType"], "complete", "{result}");
|
||||
assert_eq!(result["ttlMs"], 0);
|
||||
assert_eq!(result["cacheScope"], "private");
|
||||
} 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_accept: bool,
|
||||
) -> (Value, [usize; 4]) {
|
||||
let req = request(revision, method, params);
|
||||
let before = counts(&h.counters);
|
||||
let body = wire(
|
||||
h.post(revision, session, &req, sse_accept).await,
|
||||
&req["id"],
|
||||
sse_accept,
|
||||
)
|
||||
.await;
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
era(&body["result"], revision);
|
||||
let after = counts(&h.counters);
|
||||
(
|
||||
body["result"].clone(),
|
||||
std::array::from_fn(|i| after[i] - before[i]),
|
||||
)
|
||||
}
|
||||
async fn control(revision: &str) -> Vec<([usize; 4], [usize; 4])> {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
let mut deltas = Vec::new();
|
||||
// Preference order negotiates JSON or terminal SSE in both Resources revisions.
|
||||
for sse in [false, true] {
|
||||
let mut cursor = None;
|
||||
let mut names = Vec::new();
|
||||
for page in 0..2 {
|
||||
let mut params = json!({"limit":1});
|
||||
if let Some(ref cursor) = cursor {
|
||||
params["cursor"] = json!(cursor);
|
||||
}
|
||||
let (result, delta) =
|
||||
success(&h, revision, session, "resources/list", params, sse).await;
|
||||
let resources = result["resources"].as_array().unwrap();
|
||||
assert_eq!(resources.len(), 1, "{result}");
|
||||
let item = &resources[0];
|
||||
assert_eq!(item["mimeType"], "text/plain");
|
||||
assert!(
|
||||
item.get("description").is_none(),
|
||||
"static descriptors omit description: {item}"
|
||||
);
|
||||
names.push((item["name"].clone(), item["uri"].clone()));
|
||||
cursor = result
|
||||
.get("nextCursor")
|
||||
.map(|v| v.as_str().unwrap().to_owned());
|
||||
assert_eq!(cursor.is_some(), page == 0, "{result}");
|
||||
if let Some(ref cursor) = cursor {
|
||||
assert_ne!(cursor, "1", "opaque cursor required");
|
||||
}
|
||||
deltas.push((delta, [1, 1, 0, 0]));
|
||||
}
|
||||
names.sort_by_key(|n| n.0.as_str().unwrap().to_owned());
|
||||
assert_eq!(
|
||||
names,
|
||||
vec![
|
||||
(json!("sdk_a"), json!(URI)),
|
||||
(json!("sdk_b"), json!("crank://resources/sdk-b"))
|
||||
]
|
||||
);
|
||||
let (result, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
session,
|
||||
"resources/read",
|
||||
json!({"uri":URI}),
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
result["contents"],
|
||||
json!([{"uri":URI,"mimeType":"text/plain","text":TEXT}])
|
||||
);
|
||||
deltas.push((delta, [1, 0, 1, 0]));
|
||||
let (result, delta) = success(
|
||||
&h,
|
||||
revision,
|
||||
session,
|
||||
"resources/templates/list",
|
||||
json!({}),
|
||||
sse,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(result["resourceTemplates"], json!([]));
|
||||
assert!(result.get("nextCursor").is_none());
|
||||
deltas.push((delta, [1, 0, 0, 1]));
|
||||
}
|
||||
// Malformed parameters/cursors and indistinguishable unavailable URIs remain command errors.
|
||||
for (method, params) in [
|
||||
("resources/list", json!({"cursor":"invalid"})),
|
||||
("resources/list", json!({"limit":"invalid"})),
|
||||
("resources/templates/list", json!({"cursor":"invalid"})),
|
||||
("resources/templates/list", json!({"limit":"invalid"})),
|
||||
("resources/read", json!({"uri":"crank://resources/unbound"})),
|
||||
] {
|
||||
let req = request(revision, method, params);
|
||||
let body = wire(
|
||||
h.post(revision, session, &req, false).await,
|
||||
&req["id"],
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert!(body.get("result").is_none(), "{body}");
|
||||
}
|
||||
// An existing session does not preserve revoked authorization.
|
||||
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 [
|
||||
("resources/list", json!({})),
|
||||
("resources/read", json!({"uri":URI})),
|
||||
("resources/templates/list", json!({})),
|
||||
] {
|
||||
let req = request(revision, method, params);
|
||||
assert_eq!(h.post(revision, session, &req, false).await.status(), 401);
|
||||
}
|
||||
eprintln!(
|
||||
"existing GREEN Resources wire {revision}: pagination, exact content URI/bytes, empty templates, JSON/SSE negotiation, InvalidParams, revoked401; actual/expected SDK deltas={deltas:?}"
|
||||
);
|
||||
deltas
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_wire_legacy() {
|
||||
control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_wire_modern() {
|
||||
control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_sdk_legacy() {
|
||||
let deltas = control(LEGACY_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(actual, expected)| actual == expected),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_sdk_modern() {
|
||||
let deltas = control(MODERN_REVISION).await;
|
||||
assert!(
|
||||
deltas.iter().all(|(actual, expected)| actual == expected),
|
||||
"SDK typed dispatch/result missing after successful HTTP: {deltas:?}"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_resources_observer_scope_control() {
|
||||
use super::{
|
||||
sdk_resource_templates_list_result_serialized, sdk_resources_dispatch_enter,
|
||||
sdk_resources_list_result_serialized, sdk_resources_read_result_serialized,
|
||||
};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_resources_dispatch_enter();
|
||||
assert_eq!(counts(&a), [0; 4]);
|
||||
let snapshot = a.snapshot();
|
||||
observe(a.clone(), async {
|
||||
sdk_resources_dispatch_enter();
|
||||
sdk_resources_list_result_serialized();
|
||||
sdk_resources_read_result_serialized();
|
||||
sdk_resource_templates_list_result_serialized();
|
||||
})
|
||||
.await;
|
||||
observe(b.clone(), async {
|
||||
sdk_resources_read_result_serialized();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(counts(&a), [1; 4]);
|
||||
assert_eq!(counts(&b), [0, 0, 1, 0]);
|
||||
assert_eq!(a.snapshot(), snapshot, "old Snapshot stays unchanged");
|
||||
let body = Body::from_stream(stream::once(async {
|
||||
sdk_resource_templates_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, 0, 1, 1]);
|
||||
assert_eq!(counts(&a), [1; 4]);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
//! 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)
|
||||
}
|
||||
}
|
||||
@@ -33,6 +33,8 @@
|
||||
|
||||
Первый срез #107: `build_app` направляет `tools/list` обеих revisions и `tools/call` через `app/rmcp_dispatch.rs`. Параметры rmcp=3.7.0 (`PaginatedRequestParams`/`CallToolRequestParams`) определяют команду существующего shared Tools service; расширения Crank `limit`/confirmation сохраняются отдельно. Потребитель — штатный MCP HTTP клиент, не изолированный router #106. Текущие admission, свежая identity, lifecycle, era-specific ответы и PostgreSQL sessions остаются у прежнего transport; SDK HTTP transport не подключён. В следующем Tools response-срезе `app/response.rs` строит и сериализует настоящие rmcp `ListToolsResult`/`Tool` и `CallToolResult`/`ContentBlock`; эти builders используют оба HTTP dispatch и общий JSON/SSE terminal, а изолированный `rmcp_tools` переиспользует typed builders. Явная проекция сохраняет revision defaults, pretty text, tool-error contract, `isError` и present-null `structuredContent`; после SDK list serialization сохраняются исходные top-level extensions/optional null и непрозрачные annotations/icons. Штатный producer публикует name/title/description/inputSchema: расширения защищены локальной builder-регрессией, а не объявлены новыми runtime-полями. HTTP-тесты проверяют обе revisions, success/tool errors/InvalidParams, ID/correlation, modern SSE terminal и несколько страниц опубликованного каталога. JSON-RPC envelope/status остаются прежней внешней границей; остальные handlers, transport и lifecycle ещё не перенесены. Полный #107 не завершён; проверки #106 не являются доказательством завершения миграции.
|
||||
|
||||
Следующий Resources-срез #107 подключает `resources/list`, `resources/read` и `resources/templates/list` обеих revisions к тому же `app/rmcp_dispatch.rs`: `PaginatedRequestParams`/`ReadResourceRequestParams` передают cursor/URI прежнему shared Resources service, а Crank `limit` сохраняется отдельно. `app/response.rs` сериализует rmcp `ListResourcesResult`/`Resource`, `ReadResourceResult`/`ResourceContents` и `ListResourceTemplatesResult`/`ResourceTemplate` с прежними revision-specific cache defaults. Минимальная lossless-проекция сохраняет Crank template `parameters`, extensions/optional null и непрозрачные annotations/icons. Штатные producers по-прежнему публикуют прежние поля; builder-регрессия не добавляет runtime-возможностей. Потребитель — действующий `build_app` HTTP JSON/SSE terminal. Реальные HTTP-тесты отдельно подтверждают SDK request/result seam и сохранение wire; существующая Resources-матрица проверяет заполненные templates, exact-version binding, text/JSON/blob, scope/revocation и cursors. Handwritten builders этих трёх результатов заменены; domain/storage/auth, envelopes, transport и lifecycle не меняются. Subscribe/unsubscribe/notifications остаются прежними и не объявляются перенесёнными; остальные handlers и полный #107 ещё не завершены.
|
||||
|
||||
Проверяемый результат:
|
||||
|
||||
- Через SDK проходят действующие Tools, Resources, Prompts, completion, уведомления и подписки в применимых revisions, а также progress/cancel и существующая logging policy.
|
||||
|
||||
Reference in new issue
Block a user