feat(mcp): serialize Tools responses through rmcp SDK models
CI / UI Checks (pull_request) Successful in 10s
CI / Rust Checks (pull_request) Successful in 24m38s
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 10s
CI / Rust Checks (pull_request) Successful in 24m38s
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
7f18bce679
commit
bf773d61b8
8 files changed
+683
-100
No files matched your search
@@ -161,19 +161,18 @@ pub(super) async fn handle_modern_request(
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ToolsOutcome::List { tools, next_cursor } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
crate::protocol::project_modern_cacheable_result(
|
||||
version,
|
||||
tools_list_result(tools, next_cursor),
|
||||
ToolsOutcome::List { tools, next_cursor } => {
|
||||
match tools_list_result(tools, next_cursor, version) {
|
||||
Ok(result) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), result),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
),
|
||||
response_mode,
|
||||
None,
|
||||
Some(version),
|
||||
),
|
||||
Err(error) => internal_jsonrpc_error(message, error),
|
||||
}
|
||||
}
|
||||
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, message_text),
|
||||
|
||||
@@ -52,6 +52,8 @@ pub(crate) struct CounterSet {
|
||||
era_legacy: AtomicUsize,
|
||||
tools_service: AtomicUsize,
|
||||
sdk_tools_dispatch: AtomicUsize,
|
||||
sdk_tools_list_result: AtomicUsize,
|
||||
sdk_tools_call_result: AtomicUsize,
|
||||
}
|
||||
|
||||
impl CounterSet {
|
||||
@@ -60,6 +62,16 @@ impl CounterSet {
|
||||
self.sdk_tools_dispatch.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Successfully serialized SDK ListToolsResult values, not dispatch entries.
|
||||
pub(crate) fn sdk_tools_list_result(&self) -> usize {
|
||||
self.sdk_tools_list_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Successfully serialized SDK CallToolResult values, not dispatch entries.
|
||||
pub(crate) fn sdk_tools_call_result(&self) -> usize {
|
||||
self.sdk_tools_call_result.load(Ordering::SeqCst)
|
||||
}
|
||||
|
||||
/// Read the counters of one observed request as one comparable snapshot.
|
||||
pub(crate) fn snapshot(&self) -> Snapshot {
|
||||
Snapshot {
|
||||
@@ -145,6 +157,16 @@ pub(crate) fn sdk_tools_dispatch_enter() {
|
||||
increment(|counters| &counters.sdk_tools_dispatch);
|
||||
}
|
||||
|
||||
/// Mark only after serializing a real SDK ListToolsResult successfully.
|
||||
pub(crate) fn sdk_tools_list_result_serialized() {
|
||||
increment(|counters| &counters.sdk_tools_list_result);
|
||||
}
|
||||
|
||||
/// Mark only after serializing a real SDK CallToolResult successfully.
|
||||
pub(crate) fn sdk_tools_call_result_serialized() {
|
||||
increment(|counters| &counters.sdk_tools_call_result);
|
||||
}
|
||||
|
||||
fn increment(counter: impl Fn(&CounterSet) -> &AtomicUsize) {
|
||||
let _ = OBSERVER.try_with(|counters| {
|
||||
counter(counters).fetch_add(1, Ordering::SeqCst);
|
||||
|
||||
@@ -143,13 +143,18 @@ pub(super) async fn handle_legacy_request(
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
ToolsOutcome::List { tools, next_cursor } => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), tools_list_result(tools, next_cursor)),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
ToolsOutcome::List { tools, next_cursor } => {
|
||||
match tools_list_result(tools, next_cursor, &session.protocol_version) {
|
||||
Ok(result) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_result(request_id(message), result),
|
||||
response_mode,
|
||||
None,
|
||||
Some(&session.protocol_version),
|
||||
),
|
||||
Err(error) => internal_jsonrpc_error(message, error),
|
||||
}
|
||||
}
|
||||
ToolsOutcome::InvalidParams(message_text) => transport_response(
|
||||
StatusCode::OK,
|
||||
jsonrpc_error(request_id(message), -32602, message_text),
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
use axum::{http::StatusCode, response::Response};
|
||||
use rmcp::model::{CacheScope, CallToolResult, ContentBlock, ListToolsResult, ResultType, Tool};
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use crate::{
|
||||
jsonrpc::{jsonrpc_result, request_id},
|
||||
protocol::project_modern_result,
|
||||
tool_error::{ToolErrorContract, tool_error_text, tool_error_value},
|
||||
transport::{ResponseMode, transport_response},
|
||||
};
|
||||
@@ -30,22 +30,7 @@ pub(super) fn success_tool_payload(
|
||||
protocol_version: &str,
|
||||
output: Value,
|
||||
) -> Value {
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
project_modern_result(
|
||||
protocol_version,
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": serde_json::to_string_pretty(&output).unwrap_or_else(|_| "{}".to_owned())
|
||||
}
|
||||
],
|
||||
"structuredContent": output,
|
||||
"isError": false
|
||||
}),
|
||||
),
|
||||
)
|
||||
call_result_payload(message, protocol_version, sdk_success_tool_result(output))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -69,39 +54,80 @@ pub(super) fn tool_error_payload(
|
||||
protocol_version: &str,
|
||||
error: ToolErrorContract,
|
||||
) -> Value {
|
||||
let error_message = tool_error_text(&error);
|
||||
let error_value = tool_error_value(&error);
|
||||
|
||||
jsonrpc_result(
|
||||
request_id(message),
|
||||
project_modern_result(
|
||||
protocol_version,
|
||||
json!({
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": error_message
|
||||
}
|
||||
],
|
||||
"structuredContent": {
|
||||
"error": error_value
|
||||
},
|
||||
"isError": true
|
||||
}),
|
||||
),
|
||||
)
|
||||
call_result_payload(message, protocol_version, sdk_error_tool_result(error))
|
||||
}
|
||||
|
||||
/// The era-neutral `tools/list` result shape built from the shared command outcome. Object keys end
|
||||
/// up byte-lexicographically ordered, exactly as before the extraction.
|
||||
pub(super) fn tools_list_result(tools: Vec<Value>, next_cursor: Option<String>) -> Value {
|
||||
let mut result = json!({ "tools": tools });
|
||||
if let Some(next_cursor) = next_cursor {
|
||||
result["nextCursor"] = Value::String(next_cursor);
|
||||
}
|
||||
pub(super) fn sdk_success_tool_result(output: Value) -> CallToolResult {
|
||||
let text = serde_json::to_string_pretty(&output).expect("JSON value serializes");
|
||||
let mut result = CallToolResult::success(vec![ContentBlock::text(text)]);
|
||||
result.structured_content = Some(output);
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn sdk_error_tool_result(error: ToolErrorContract) -> CallToolResult {
|
||||
let mut result = CallToolResult::error(vec![ContentBlock::text(tool_error_text(&error))]);
|
||||
result.structured_content = Some(json!({ "error": tool_error_value(&error) }));
|
||||
result
|
||||
}
|
||||
|
||||
fn call_result_payload(message: &Value, version: &str, mut result: CallToolResult) -> Value {
|
||||
result.result_type =
|
||||
(version == crate::jsonrpc::MODERN_PROTOCOL_VERSION).then_some(ResultType::COMPLETE);
|
||||
let result = serde_json::to_value(result).expect("SDK call result contains JSON values");
|
||||
#[cfg(test)]
|
||||
super::dispatch_observer::sdk_tools_call_result_serialized();
|
||||
jsonrpc_result(request_id(message), result)
|
||||
}
|
||||
|
||||
pub(super) fn sdk_tools_list_result(
|
||||
tools: &[Value],
|
||||
next_cursor: Option<String>,
|
||||
) -> Result<ListToolsResult, serde_json::Error> {
|
||||
Ok(ListToolsResult {
|
||||
tools: tools
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(serde_json::from_value::<Tool>)
|
||||
.collect::<Result<Vec<_>, _>>()?,
|
||||
next_cursor,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
/// Serialize the SDK model, preserving catalog extensions that pinned Tool serde cannot represent.
|
||||
pub(super) fn tools_list_result(
|
||||
tools: Vec<Value>,
|
||||
next_cursor: Option<String>,
|
||||
version: &str,
|
||||
) -> Result<Value, serde_json::Error> {
|
||||
let mut result = sdk_tools_list_result(&tools, next_cursor)?;
|
||||
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_tools_list_result_serialized();
|
||||
for (raw, serialized) in tools
|
||||
.iter()
|
||||
.zip(result["tools"].as_array_mut().expect("SDK tools array"))
|
||||
{
|
||||
let serialized = serialized.as_object_mut().expect("SDK Tool object");
|
||||
for (key, value) in raw.as_object().expect("validated Tool object") {
|
||||
if matches!(key.as_str(), "annotations" | "icons")
|
||||
|| !matches!(
|
||||
key.as_str(),
|
||||
"name" | "title" | "description" | "inputSchema" | "outputSchema" | "_meta"
|
||||
)
|
||||
|| value.is_null()
|
||||
{
|
||||
serialized.insert(key.clone(), value.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
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 {
|
||||
@@ -301,6 +327,87 @@ pub(super) fn resource_error_response(
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod sdk_result_tests {
|
||||
use super::*;
|
||||
use crate::jsonrpc::{LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION};
|
||||
|
||||
#[test]
|
||||
fn catalog_projection_preserves_extensions_null_and_empty() {
|
||||
let descriptor = json!({
|
||||
"name":"tool", "title":"", "description":null,
|
||||
"inputSchema":{"type":"object", "x-schema":{"nested":null}},
|
||||
"outputSchema":{"type":"object", "x-output":[]},
|
||||
"_meta":{"custom":{"empty":{}}}, "x-tool":{"nested":[]},
|
||||
"annotations":{"readOnlyHint":true,"x-annotation":{"nested":null}},
|
||||
"icons":[{"src":"https://example.test/icon", "x-icon":{"nested":[]}}]
|
||||
});
|
||||
for version in [LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION] {
|
||||
for raw in [
|
||||
descriptor.clone(),
|
||||
json!({"name":"tool","inputSchema":{},
|
||||
"title":null,"description":"","outputSchema":null,"_meta":null,
|
||||
"annotations":null,"icons":null}),
|
||||
json!({"name":"tool","inputSchema":{},
|
||||
"annotations":{},"icons":[]}),
|
||||
] {
|
||||
for cursor in [None, Some(String::new()), Some("next".to_owned())] {
|
||||
let value =
|
||||
tools_list_result(vec![raw.clone()], cursor.clone(), version).unwrap();
|
||||
assert_eq!(value["tools"], json!([raw]));
|
||||
assert_eq!(
|
||||
value.get("nextCursor"),
|
||||
cursor.as_ref().map(|s| Value::String(s.clone())).as_ref()
|
||||
);
|
||||
assert_eq!(
|
||||
value.get("resultType").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
value.get("ttlMs").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
assert_eq!(
|
||||
value.get("cacheScope").is_some(),
|
||||
version == MODERN_PROTOCOL_VERSION
|
||||
);
|
||||
}
|
||||
}
|
||||
assert_eq!(
|
||||
tools_list_result(vec![], None, version).unwrap()["tools"],
|
||||
json!([])
|
||||
);
|
||||
assert!(tools_list_result(vec![json!({"name":42})], None, version).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn null_success_and_rpc_failures_keep_their_distinct_shapes() {
|
||||
for version in [LEGACY_PROTOCOL_VERSION, MODERN_PROTOCOL_VERSION] {
|
||||
let message = json!({"id":9007199254740993_u64});
|
||||
let payload = success_tool_payload(&message, version, Value::Null);
|
||||
assert_eq!(payload["id"], message["id"]);
|
||||
assert_eq!(
|
||||
payload["result"]["content"],
|
||||
json!([{"type":"text","text":"null"}])
|
||||
);
|
||||
assert_eq!(
|
||||
payload["result"].get("structuredContent"),
|
||||
Some(&Value::Null)
|
||||
);
|
||||
assert_eq!(payload["result"]["isError"], false);
|
||||
let correlation = CorrelationContext::generate();
|
||||
let internal = tool_command_payload(
|
||||
&message,
|
||||
version,
|
||||
&correlation,
|
||||
ToolsOutcome::Call(ToolCallOutcome::InternalFailure),
|
||||
);
|
||||
assert!(matches!(internal, ToolCommandPayload::Internal(_)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn internal_jsonrpc_error(message: &Value, _error: impl std::fmt::Display) -> Response {
|
||||
transport_response(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
|
||||
@@ -90,10 +90,7 @@ impl RmcpTools {
|
||||
}
|
||||
}
|
||||
use rmcp::ErrorData as McpError;
|
||||
use rmcp::model::{
|
||||
CallToolRequestParams, CallToolResult, ContentBlock, ListToolsResult, PaginatedRequestParams,
|
||||
Tool,
|
||||
};
|
||||
use rmcp::model::{CallToolRequestParams, ListToolsResult, PaginatedRequestParams};
|
||||
use rmcp::service::RequestContext;
|
||||
use rmcp::{RoleServer, ServerHandler};
|
||||
|
||||
@@ -138,18 +135,8 @@ impl ServerHandler for RmcpTools {
|
||||
};
|
||||
match self.list_tools(&identity, command, None).await {
|
||||
crate::protocol::ToolsOutcome::List { tools, next_cursor } => {
|
||||
let tools = tools
|
||||
.into_iter()
|
||||
.map(serde_json::from_value::<Tool>)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|_| {
|
||||
McpError::internal_error("invalid tool catalog entry", None)
|
||||
})?;
|
||||
Ok(ListToolsResult {
|
||||
tools,
|
||||
next_cursor,
|
||||
..Default::default()
|
||||
})
|
||||
super::response::sdk_tools_list_result(&tools, next_cursor)
|
||||
.map_err(|_| McpError::internal_error("invalid tool catalog entry", None))
|
||||
}
|
||||
crate::protocol::ToolsOutcome::InvalidParams(message) => {
|
||||
Err(McpError::invalid_params(message, None))
|
||||
@@ -223,27 +210,24 @@ impl ServerHandler for RmcpTools {
|
||||
crate::protocol::ToolsOutcome::Call(outcome) => match outcome {
|
||||
crate::protocol::ToolCallOutcome::Completed(value)
|
||||
| crate::protocol::ToolCallOutcome::ApprovalPending(value) => {
|
||||
let text = value.to_string();
|
||||
let mut result = CallToolResult::default();
|
||||
result.content = vec![ContentBlock::text(text)];
|
||||
result.structured_content = if value.is_null() { None } else { Some(value) };
|
||||
Ok(result.into())
|
||||
Ok(super::response::sdk_success_tool_result(value).into())
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::ApprovalUnavailable(_) => {
|
||||
let mut result = CallToolResult::default();
|
||||
result.is_error = Some(true);
|
||||
result.content = vec![ContentBlock::text("approval elicitation not supported")];
|
||||
Ok(result.into())
|
||||
crate::protocol::ToolCallOutcome::ApprovalUnavailable(error) => {
|
||||
Ok(super::response::sdk_error_tool_result(
|
||||
crate::tool_error::control_tool_error_contract(
|
||||
error,
|
||||
identity.correlation.request_id().as_str(),
|
||||
identity.correlation.trace_id().as_str(),
|
||||
identity.locale,
|
||||
),
|
||||
)
|
||||
.into())
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::InvalidParams(message) => {
|
||||
Err(McpError::invalid_params(message, None))
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::Error(contract) => {
|
||||
let text = serde_json::to_string(&contract).unwrap_or_default();
|
||||
let mut result = CallToolResult::default();
|
||||
result.is_error = Some(true);
|
||||
result.content = vec![ContentBlock::text(text)];
|
||||
Ok(result.into())
|
||||
Ok(super::response::sdk_error_tool_result(contract).into())
|
||||
}
|
||||
crate::protocol::ToolCallOutcome::InternalFailure => {
|
||||
Err(McpError::internal_error("tool execution failed", None))
|
||||
|
||||
@@ -0,0 +1,437 @@
|
||||
//! #107 result serialization: wire controls run independently of the structural SDK oracle.
|
||||
use super::*;
|
||||
use axum::{
|
||||
Json,
|
||||
body::Body,
|
||||
extract::State,
|
||||
http::StatusCode,
|
||||
response::{IntoResponse, Response},
|
||||
};
|
||||
use futures_util::{StreamExt, stream};
|
||||
|
||||
const ERROR_EMAIL: &str = "upstream-error@example.test";
|
||||
const REQUEST_ID: &str = "sdk-result-wire";
|
||||
const TRACE_ID: &str = "11111111111111111111111111111111";
|
||||
|
||||
pub(super) async fn upstream(state: State<Arc<AtomicUsize>>, payload: Json<Value>) -> Response {
|
||||
if payload.0["email"] == ERROR_EMAIL {
|
||||
state.0.fetch_add(1, Ordering::SeqCst);
|
||||
return (
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
Json(json!({"error":"fixture rejection"})),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
create_lead(state, payload).await.into_response()
|
||||
}
|
||||
|
||||
// The HTTP body is polled after next.run returns. Carry only the test observer, not a new lifecycle.
|
||||
pub(super) 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))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_http_pagination_both_revisions() {
|
||||
let h = Endpoint::started().await;
|
||||
let mut operation = test_operation(&h._upstream.1);
|
||||
operation.id = crank_core::OperationId::new("op_second_lead");
|
||||
operation.name = "second_lead".to_owned();
|
||||
h.registry
|
||||
.create_operation(&workspace_id(), &operation, Some("alice"))
|
||||
.await
|
||||
.unwrap();
|
||||
h.registry
|
||||
.publish_operation(PublishRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
operation_id: &operation.id,
|
||||
version: 1,
|
||||
published_at: &test_time(),
|
||||
published_by: Some("alice"),
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let now = time::OffsetDateTime::now_utc();
|
||||
h.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: now,
|
||||
},
|
||||
bindings: &[
|
||||
AgentOperationBinding {
|
||||
operation_id: crank_core::OperationId::new("op_create_lead"),
|
||||
operation_version: 1,
|
||||
tool_name: TOOL_NAME.into(),
|
||||
tool_title: "Create Lead".into(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
},
|
||||
AgentOperationBinding {
|
||||
operation_id: operation.id,
|
||||
operation_version: 1,
|
||||
tool_name: "second_lead".into(),
|
||||
tool_title: "Second Lead".into(),
|
||||
tool_description_override: None,
|
||||
enabled: true,
|
||||
},
|
||||
],
|
||||
updated_at: &now,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
h.registry
|
||||
.publish_agent(PublishAgentRequest {
|
||||
workspace_id: &workspace_id(),
|
||||
agent_id: &agent_id(),
|
||||
version: 2,
|
||||
published_at: &now,
|
||||
published_by: Some("alice"),
|
||||
expected_state: None,
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
for revision in [LEGACY_REVISION, MODERN_REVISION] {
|
||||
let session = h.session(revision).await;
|
||||
let mut names = Vec::new();
|
||||
for (cursor, expected_next, expected_len) in [
|
||||
(None, Some("1"), 1),
|
||||
(Some("1"), None, 1),
|
||||
(Some("2"), None, 0),
|
||||
] {
|
||||
let id = json!(format!("page-{cursor:?}"));
|
||||
let mut request =
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"tools/list","params":{"limit":1}});
|
||||
if let Some(cursor) = cursor {
|
||||
request["params"]["cursor"] = json!(cursor);
|
||||
}
|
||||
if revision == MODERN_REVISION {
|
||||
request["params"]["_meta"] = modern_meta();
|
||||
}
|
||||
let before = h.counters.sdk_tools_list_result();
|
||||
let body = wire_body(
|
||||
h.post(revision, session.as_deref(), &request).await,
|
||||
&id,
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_era(&body["result"], revision, true);
|
||||
assert_eq!(
|
||||
body["result"].get("nextCursor"),
|
||||
expected_next.map(|s| json!(s)).as_ref()
|
||||
);
|
||||
let tools = body["result"]["tools"].as_array().unwrap();
|
||||
assert_eq!(tools.len(), expected_len);
|
||||
names.extend(
|
||||
tools
|
||||
.iter()
|
||||
.map(|tool| tool["name"].as_str().unwrap().to_owned()),
|
||||
);
|
||||
assert_eq!(h.counters.sdk_tools_list_result() - before, 1);
|
||||
}
|
||||
names.sort();
|
||||
let mut expected = vec![TOOL_NAME.to_owned(), "second_lead".to_owned()];
|
||||
expected.sort();
|
||||
assert_eq!(names, expected);
|
||||
}
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
||||
}
|
||||
|
||||
fn assert_era(result: &Value, revision: &str, list: bool) {
|
||||
if revision == MODERN_REVISION {
|
||||
assert_eq!(result["resultType"], "complete", "{result}");
|
||||
if list {
|
||||
assert_eq!(result["ttlMs"], 0);
|
||||
assert_eq!(result["cacheScope"], "private");
|
||||
}
|
||||
} else {
|
||||
assert!(result.get("resultType").is_none(), "{result}");
|
||||
assert!(result.get("ttlMs").is_none(), "{result}");
|
||||
assert!(result.get("cacheScope").is_none(), "{result}");
|
||||
}
|
||||
assert!(result.get("_meta").is_none(), "{result}");
|
||||
}
|
||||
|
||||
async fn wire_body(response: reqwest::Response, id: &Value, sse: bool) -> Value {
|
||||
assert_eq!(response.status(), 200);
|
||||
assert_eq!(response.headers()["x-request-id"], REQUEST_ID);
|
||||
assert_eq!(response.headers()["x-trace-id"], TRACE_ID);
|
||||
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}"
|
||||
);
|
||||
let frames: Vec<Value> = text
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
line.strip_prefix("data:")
|
||||
.map(|data| serde_json::from_str(data.trim()).unwrap())
|
||||
})
|
||||
.collect();
|
||||
let terminal: Vec<_> = frames
|
||||
.iter()
|
||||
.filter(|frame| frame.get("id") == Some(id))
|
||||
.collect();
|
||||
assert_eq!(terminal.len(), 1, "{frames:?}");
|
||||
assert_eq!(frames.last(), Some(terminal[0]), "terminal must be last");
|
||||
assert!(
|
||||
frames
|
||||
.iter()
|
||||
.any(|frame| frame["method"] == "notifications/progress"
|
||||
&& frame["params"]["progressToken"] == "result-progress"),
|
||||
"{frames:?}"
|
||||
);
|
||||
terminal[0].clone()
|
||||
} else {
|
||||
assert!(
|
||||
content_type.starts_with("application/json"),
|
||||
"{content_type}"
|
||||
);
|
||||
serde_json::from_str(&text).unwrap()
|
||||
};
|
||||
assert_eq!(body["jsonrpc"], "2.0");
|
||||
assert_eq!(&body["id"], id);
|
||||
body
|
||||
}
|
||||
|
||||
fn assert_call_result(body: &Value, revision: &str, email: &str) {
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
let result = &body["result"];
|
||||
assert_era(result, revision, false);
|
||||
let (output, text, is_error) = if email == ERROR_EMAIL {
|
||||
let contract = crate::tool_error::tool_error_contract_from_runtime(
|
||||
&crank_runtime::RuntimeError::ProtocolAdapter(
|
||||
crank_core::ProtocolAdapterError::UnexpectedStatus {
|
||||
status: 422,
|
||||
dispatch: crank_core::DispatchEvidence::MayHaveDispatched,
|
||||
},
|
||||
),
|
||||
REQUEST_ID,
|
||||
TRACE_ID,
|
||||
crank_core::ExecutionLocale::En,
|
||||
);
|
||||
(
|
||||
json!({"error":crate::tool_error::tool_error_value(&contract)}),
|
||||
crate::tool_error::tool_error_text(&contract),
|
||||
true,
|
||||
)
|
||||
} else {
|
||||
let output = json!({"id":format!("lead_for_{email}")});
|
||||
let text = serde_json::to_string_pretty(&output).unwrap();
|
||||
(output, text, false)
|
||||
};
|
||||
assert_eq!(result["structuredContent"], output, "{body}");
|
||||
assert_eq!(result["content"], json!([{"type":"text", "text":text}]));
|
||||
assert_eq!(result["isError"], is_error);
|
||||
assert_eq!(
|
||||
result.as_object().unwrap().len(),
|
||||
if revision == MODERN_REVISION { 4 } else { 3 },
|
||||
"no unexpected optional fields: {result}"
|
||||
);
|
||||
}
|
||||
|
||||
async fn result_control(revision: &str) -> Vec<usize> {
|
||||
let h = Endpoint::started().await;
|
||||
let session = h.session(revision).await;
|
||||
let session = session.as_deref();
|
||||
let mut counts = Vec::new();
|
||||
// Actual published descriptor and schema, then the empty page at the catalog boundary.
|
||||
for (cursor, expected_tools, id) in [
|
||||
(
|
||||
None,
|
||||
json!([{"name":TOOL_NAME,"title":"Create Lead","description":"Creates a CRM lead","inputSchema":{"type":"object","properties":{"email":{"type":"string"}},"required":["email"]}}]),
|
||||
json!("list-string-id"),
|
||||
),
|
||||
(Some("1"), json!([]), json!(9007199254740993_u64)),
|
||||
] {
|
||||
let mut request =
|
||||
json!({"jsonrpc":"2.0","id":id,"method":"tools/list","params":{"limit":1}});
|
||||
if revision == MODERN_REVISION {
|
||||
request["params"]["_meta"] = modern_meta();
|
||||
}
|
||||
if let Some(cursor) = cursor {
|
||||
request["params"]["cursor"] = json!(cursor);
|
||||
}
|
||||
let before = h.counters.sdk_tools_list_result();
|
||||
let before_call = h.counters.sdk_tools_call_result();
|
||||
let before_dispatch = h.counters.sdk_tools_dispatch();
|
||||
let body = wire_body(h.post(revision, session, &request).await, &id, false).await;
|
||||
assert!(body.get("error").is_none(), "{body}");
|
||||
assert_eq!(body["result"]["tools"], expected_tools);
|
||||
assert!(body["result"].get("nextCursor").is_none(), "{body}");
|
||||
assert_era(&body["result"], revision, true);
|
||||
assert_eq!(h.counters.sdk_tools_call_result(), before_call);
|
||||
assert_eq!(h.counters.sdk_tools_dispatch() - before_dispatch, 1);
|
||||
counts.push(h.counters.sdk_tools_list_result() - before);
|
||||
}
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), 0);
|
||||
for (email, id, sse) in [
|
||||
(
|
||||
"result-success@example.test",
|
||||
json!(9007199254740993_u64),
|
||||
false,
|
||||
),
|
||||
(ERROR_EMAIL, json!("tool-error-string-id"), false),
|
||||
("result-sse@example.test", json!("sse-string-id"), true),
|
||||
(ERROR_EMAIL, json!(92), true),
|
||||
] {
|
||||
if sse && revision != MODERN_REVISION {
|
||||
continue;
|
||||
}
|
||||
let mut request = if revision == MODERN_REVISION {
|
||||
modern_tool_call(90, email)
|
||||
} else {
|
||||
legacy_tool_call(90, email)
|
||||
};
|
||||
request["id"] = id.clone();
|
||||
if sse {
|
||||
request["params"]["_meta"]["progressToken"] = json!("result-progress");
|
||||
}
|
||||
let before = h.counters.sdk_tools_call_result();
|
||||
let before_list = h.counters.sdk_tools_list_result();
|
||||
let before_dispatch = h.counters.sdk_tools_dispatch();
|
||||
let arrivals = h.calls.load(Ordering::SeqCst);
|
||||
let response = h
|
||||
.post_accept(
|
||||
revision,
|
||||
session,
|
||||
&request,
|
||||
if sse {
|
||||
"application/json, text/event-stream"
|
||||
} else {
|
||||
"application/json"
|
||||
},
|
||||
)
|
||||
.await;
|
||||
let body = wire_body(response, &id, sse).await;
|
||||
assert_call_result(&body, revision, email);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst) - arrivals, 1);
|
||||
assert_eq!(h.counters.sdk_tools_list_result(), before_list);
|
||||
assert_eq!(h.counters.sdk_tools_dispatch() - before_dispatch, 1);
|
||||
counts.push(h.counters.sdk_tools_call_result() - before);
|
||||
}
|
||||
// Unknown tool is a command InvalidParams, not an execution tool-error result.
|
||||
let mut invalid = if revision == MODERN_REVISION {
|
||||
modern_tool_call(93, "unused@example.test")
|
||||
} else {
|
||||
legacy_tool_call(93, "unused@example.test")
|
||||
};
|
||||
invalid["params"]["name"] = json!("missing_tool");
|
||||
invalid["id"] = json!("invalid-params-id");
|
||||
let before = h.counters.sdk_tools_call_result();
|
||||
let arrivals = h.calls.load(Ordering::SeqCst);
|
||||
let body = wire_body(
|
||||
h.post(revision, session, &invalid).await,
|
||||
&invalid["id"],
|
||||
false,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(body["error"]["code"], -32602, "{body}");
|
||||
assert!(body.get("result").is_none(), "{body}");
|
||||
assert_eq!(body["error"]["data"]["request_id"], REQUEST_ID);
|
||||
assert_eq!(body["error"]["data"]["trace_id"], TRACE_ID);
|
||||
assert_eq!(h.counters.sdk_tools_call_result(), before);
|
||||
assert_eq!(h.calls.load(Ordering::SeqCst), arrivals);
|
||||
eprintln!(
|
||||
"existing GREEN result wire {revision}: published list/schema + empty page, exact success/error JSON{}; InvalidParams/no result/no marker/no outbound; SDK result deltas={counts:?}",
|
||||
if revision == MODERN_REVISION {
|
||||
" + success/error terminal SSE"
|
||||
} else {
|
||||
" (legacy JSON-only)"
|
||||
}
|
||||
);
|
||||
counts
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_wire_modern() {
|
||||
result_control(MODERN_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_wire_legacy() {
|
||||
result_control(LEGACY_REVISION).await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_sdk_serialization_modern() {
|
||||
assert_eq!(
|
||||
result_control(MODERN_REVISION).await,
|
||||
vec![1; 6],
|
||||
"structural oracle: SDK list/final-empty/success/error/SSE-success/SSE-error must each serialize once after successful real HTTP wire controls"
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_sdk_serialization_legacy() {
|
||||
assert_eq!(
|
||||
result_control(LEGACY_REVISION).await,
|
||||
vec![1; 4],
|
||||
"structural oracle: SDK list/final-empty/success/error must each serialize once after successful real HTTP wire controls"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rmcp_result_observer_scope_control() {
|
||||
use crate::app::dispatch_observer::{
|
||||
sdk_tools_call_result_serialized, sdk_tools_list_result_serialized,
|
||||
};
|
||||
let a = Arc::new(CounterSet::default());
|
||||
let b = Arc::new(CounterSet::default());
|
||||
sdk_tools_list_result_serialized();
|
||||
sdk_tools_call_result_serialized();
|
||||
assert_eq!(
|
||||
(a.sdk_tools_list_result(), a.sdk_tools_call_result()),
|
||||
(0, 0)
|
||||
);
|
||||
observe(a.clone(), async {
|
||||
sdk_tools_list_result_serialized();
|
||||
sdk_tools_call_result_serialized();
|
||||
})
|
||||
.await;
|
||||
// A different request cannot alter a's result counters.
|
||||
observe(b.clone(), async {
|
||||
sdk_tools_list_result_serialized();
|
||||
})
|
||||
.await;
|
||||
assert_eq!(
|
||||
(a.sdk_tools_list_result(), a.sdk_tools_call_result()),
|
||||
(1, 1)
|
||||
);
|
||||
assert_eq!(
|
||||
(b.sdk_tools_list_result(), b.sdk_tools_call_result()),
|
||||
(1, 0)
|
||||
);
|
||||
// Prove the stream-body scope actually records deferred work after the header scope ended.
|
||||
let stream_counters = b.clone();
|
||||
let body = Body::from_stream(stream::once(async move {
|
||||
sdk_tools_call_result_serialized();
|
||||
Ok::<_, std::convert::Infallible>("terminal")
|
||||
}));
|
||||
let response = observe_body(Response::new(body), stream_counters);
|
||||
let bytes = axum::body::to_bytes(response.into_body(), 100)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(&bytes[..], b"terminal");
|
||||
assert_eq!(b.sdk_tools_call_result(), 1);
|
||||
assert_eq!(a.sdk_tools_call_result(), 1);
|
||||
}
|
||||
@@ -23,6 +23,9 @@ use serde_json::{Value, json};
|
||||
|
||||
use super::{CounterSet, observe, sdk_tools_dispatch_enter, support::*};
|
||||
|
||||
#[path = "rmcp_result_runtime_tests.rs"]
|
||||
mod result_serialization;
|
||||
|
||||
struct Server(tokio::task::JoinHandle<()>, String);
|
||||
|
||||
impl Drop for Server {
|
||||
@@ -55,13 +58,13 @@ impl Endpoint {
|
||||
async fn started() -> Self {
|
||||
// First caller owns the process-wide fixture and its atexit cleanup, including RED panics.
|
||||
let _ =
|
||||
crank_test_support::postgres_schema_url_for_task("rmcp_runtime_owner", "t_aaaea124")
|
||||
crank_test_support::postgres_schema_url_for_task("rmcp_runtime_owner", "t_c559abb1")
|
||||
.await;
|
||||
let registry = test_registry().await;
|
||||
let calls = Arc::new(AtomicUsize::new(0));
|
||||
let upstream = serve(
|
||||
Router::new()
|
||||
.route("/crm/leads", post(create_lead))
|
||||
.route("/crm/leads", post(result_serialization::upstream))
|
||||
.with_state(calls.clone()),
|
||||
)
|
||||
.await;
|
||||
@@ -97,7 +100,17 @@ impl Endpoint {
|
||||
Arc::new(crate::session::InMemorySessionStore::default()),
|
||||
Arc::new(crate::auth::CommunityMachineCredentialVerifier),
|
||||
);
|
||||
let server = serve(observe_requests(app, counters.clone(), None)).await;
|
||||
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;
|
||||
result_serialization::observe_body(response, counters)
|
||||
}
|
||||
}
|
||||
}));
|
||||
let server = serve(app).await;
|
||||
Self {
|
||||
server,
|
||||
_upstream: upstream,
|
||||
@@ -109,6 +122,17 @@ impl Endpoint {
|
||||
}
|
||||
|
||||
async fn post(&self, revision: &str, session: Option<&str>, body: &Value) -> reqwest::Response {
|
||||
self.post_accept(revision, session, body, "application/json")
|
||||
.await
|
||||
}
|
||||
|
||||
async fn post_accept(
|
||||
&self,
|
||||
revision: &str,
|
||||
session: Option<&str>,
|
||||
body: &Value,
|
||||
accept: &str,
|
||||
) -> reqwest::Response {
|
||||
let mut request = reqwest::Client::new()
|
||||
.post(format!(
|
||||
"{}/v1/{WORKSPACE_SLUG}/{AGENT_SLUG}",
|
||||
@@ -116,7 +140,12 @@ impl Endpoint {
|
||||
))
|
||||
.bearer_auth(&self.key)
|
||||
// Also guards the legacy JSON-only contract; no SSE parsing fallback here.
|
||||
.header("Accept", "application/json")
|
||||
.header("Accept", accept)
|
||||
.header("x-request-id", "sdk-result-wire")
|
||||
.header(
|
||||
"traceparent",
|
||||
"00-11111111111111111111111111111111-2222222222222222-01",
|
||||
)
|
||||
.header("MCP-Protocol-Version", revision);
|
||||
if let Some(session) = session {
|
||||
request = request.header("MCP-Session-Id", session);
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
|
||||
Подключить SDK к действующему пути и перенести стандартные envelopes, dispatch, lifecycle и transport. Порядок переноса устанавливается по результату первого опыта, без параллельных writers одних MCP-файлов.
|
||||
|
||||
Первый срез #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 request dispatch/model seam: SDK response envelopes, остальные handlers, transport и lifecycle ещё не перенесены. Полный #107 не завершён; проверки #106 не являются доказательством завершения миграции.
|
||||
Первый срез #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 не являются доказательством завершения миграции.
|
||||
|
||||
Проверяемый результат:
|
||||
|
||||
|
||||
Reference in new issue
Block a user