CI / UI Checks (pull_request) Successful in 11s
CI / Rust Checks (pull_request) Successful in 30m13s
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
678 lines
26 KiB
Rust
678 lines
26 KiB
Rust
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},
|
|
tool_error::{ToolErrorContract, tool_error_text, tool_error_value},
|
|
transport::{ResponseMode, transport_response},
|
|
};
|
|
|
|
use crate::jsonrpc::jsonrpc_error;
|
|
use crate::protocol::{ToolCallOutcome, ToolsOutcome};
|
|
use crate::tool_error::{control_tool_error_contract, execution_locale};
|
|
use crank_core::CorrelationContext;
|
|
|
|
pub(crate) fn take_confirmation_token(arguments: &mut Value) -> Option<String> {
|
|
let Value::Object(object) = arguments else {
|
|
return None;
|
|
};
|
|
object
|
|
.remove("_crank_confirmation_token")
|
|
.and_then(|value| value.as_str().map(str::to_owned))
|
|
.filter(|value| !value.trim().is_empty())
|
|
}
|
|
|
|
/// The era-neutral success payload of one `tools/call` (Story 3.4: the streamed response needs the
|
|
/// payload itself, because the terminal response is the last event of the request's stream).
|
|
pub(super) fn success_tool_payload(
|
|
message: &Value,
|
|
protocol_version: &str,
|
|
output: Value,
|
|
) -> Value {
|
|
call_result_payload(message, protocol_version, sdk_success_tool_result(output))
|
|
}
|
|
|
|
#[cfg(test)]
|
|
pub(crate) fn tool_error_response(
|
|
message: &Value,
|
|
response_mode: ResponseMode,
|
|
protocol_version: &str,
|
|
error: ToolErrorContract,
|
|
) -> Response {
|
|
transport_response(
|
|
StatusCode::OK,
|
|
tool_error_payload(message, protocol_version, error),
|
|
response_mode,
|
|
None,
|
|
Some(protocol_version),
|
|
)
|
|
}
|
|
|
|
pub(super) fn tool_error_payload(
|
|
message: &Value,
|
|
protocol_version: &str,
|
|
error: ToolErrorContract,
|
|
) -> Value {
|
|
call_result_payload(message, protocol_version, sdk_error_tool_result(error))
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
/// 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)
|
|
}
|
|
|
|
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)
|
|
}
|
|
|
|
pub(super) fn resource_templates_list_result(
|
|
templates: 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::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());
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// SDK pagination with lossless Crank argument schemas/defaults and optional nulls.
|
|
pub(super) fn prompts_list_result(
|
|
prompts: Vec<Value>,
|
|
next_cursor: Option<String>,
|
|
) -> Result<Value, serde_json::Error> {
|
|
let result = rmcp::model::ListPromptsResult {
|
|
prompts: prompts
|
|
.iter()
|
|
.cloned()
|
|
.map(serde_json::from_value)
|
|
.collect::<Result<Vec<rmcp::model::Prompt>, _>>()?,
|
|
next_cursor,
|
|
result_type: None,
|
|
ttl_ms: None,
|
|
cache_scope: None,
|
|
meta: None,
|
|
};
|
|
let mut result = serde_json::to_value(result)?;
|
|
preserve_resource_fields(
|
|
&prompts,
|
|
&mut result["prompts"],
|
|
&["name", "title", "description", "arguments", "_meta"],
|
|
);
|
|
for (raw, serialized) in prompts
|
|
.iter()
|
|
.zip(result["prompts"].as_array_mut().expect("SDK prompts"))
|
|
{
|
|
if let Some(arguments) = raw["arguments"].as_array() {
|
|
preserve_resource_fields(
|
|
arguments,
|
|
&mut serialized["arguments"],
|
|
&["name", "title", "description", "required"],
|
|
);
|
|
}
|
|
}
|
|
#[cfg(test)]
|
|
super::dispatch_observer::sdk_prompts_list_result_serialized();
|
|
Ok(result)
|
|
}
|
|
|
|
/// Preserve Crank's system role, which the pinned SDK's user/assistant Role cannot express.
|
|
pub(super) fn prompt_get_result(
|
|
description: Option<String>,
|
|
messages: Vec<Value>,
|
|
) -> Result<Value, serde_json::Error> {
|
|
let sdk_messages = messages
|
|
.iter()
|
|
.cloned()
|
|
.map(|mut message| {
|
|
if message["role"] == "system" {
|
|
message["role"] = json!("user");
|
|
}
|
|
serde_json::from_value::<rmcp::model::PromptMessage>(message)
|
|
})
|
|
.collect::<Result<Vec<_>, _>>()?;
|
|
let mut result = rmcp::model::GetPromptResult::new(sdk_messages);
|
|
result.description = description;
|
|
// Era-specific resultType/cache projection remains at the existing dispatch boundary.
|
|
result.result_type = None;
|
|
let mut result = serde_json::to_value(result)?;
|
|
preserve_resource_fields(&messages, &mut result["messages"], &["role", "content"]);
|
|
for (raw, serialized) in messages
|
|
.iter()
|
|
.zip(result["messages"].as_array_mut().expect("SDK messages"))
|
|
{
|
|
if raw["role"] == "system" {
|
|
serialized["role"] = raw["role"].clone();
|
|
}
|
|
// Content extensions/optional nulls are opaque to the pinned SDK.
|
|
let content = serialized["content"].as_object_mut().expect("SDK content");
|
|
for (key, value) in raw["content"].as_object().expect("validated content") {
|
|
if !content.contains_key(key)
|
|
|| value.is_null()
|
|
|| matches!(key.as_str(), "annotations" | "resource")
|
|
{
|
|
content.insert(key.clone(), value.clone());
|
|
}
|
|
}
|
|
}
|
|
#[cfg(test)]
|
|
super::dispatch_observer::sdk_prompts_get_result_serialized();
|
|
Ok(result)
|
|
}
|
|
|
|
/// The era-neutral `completion/complete` result shape (Story 3.17): the bounded `values[]`, the
|
|
/// option count where it is known exactly, and whether more options exist. Both supported revisions
|
|
/// declare the same `completion` object, so this shape is shared.
|
|
pub(super) fn completion_result(
|
|
values: Vec<String>,
|
|
total: Option<usize>,
|
|
has_more: bool,
|
|
) -> Value {
|
|
let mut completion = json!({ "values": values });
|
|
if let Some(total) = total {
|
|
completion["total"] = json!(total);
|
|
}
|
|
if has_more {
|
|
completion["hasMore"] = json!(true);
|
|
}
|
|
json!({ "completion": completion })
|
|
}
|
|
|
|
/// The structured `prompts/get` argument rejection (AT-3.14-02): a `-32602` error whose `data`
|
|
/// carries the typed reason and the argument name of the bound Prompt. No rendered message,
|
|
/// dependency content or other Prompt metadata is attached — the rejection happens before rendering.
|
|
pub(super) fn prompt_arguments_error_response(
|
|
message: &Value,
|
|
response_mode: ResponseMode,
|
|
protocol_version: &str,
|
|
reason: &str,
|
|
argument: Option<String>,
|
|
) -> Response {
|
|
let mut error = jsonrpc_error(
|
|
request_id(message),
|
|
-32602,
|
|
"the prompt arguments were rejected".to_owned(),
|
|
);
|
|
error["error"]["data"] = crate::jsonrpc::correlated_error_data(json!({
|
|
"reason": reason,
|
|
"argument": argument,
|
|
}));
|
|
|
|
transport_response(
|
|
StatusCode::OK,
|
|
error,
|
|
response_mode,
|
|
None,
|
|
Some(protocol_version),
|
|
)
|
|
}
|
|
|
|
/// One `tools/call` wire frame, or the adapter's own internal-error detail.
|
|
///
|
|
/// Story 3.4: the same projection serves the single response and the terminal event of a streamed
|
|
/// response, so both forms of one outcome can never drift apart.
|
|
pub(super) enum ToolCommandPayload {
|
|
Ok(Value),
|
|
Internal(&'static str),
|
|
}
|
|
|
|
/// Map one shared Tools-command outcome back to its era-specific wire payload (spec section 6.2).
|
|
///
|
|
/// This adapter function is the only place that turns a neutral outcome into a wire value: the shared
|
|
/// service never sees `ResponseMode`, the protocol revision, the request envelope or an
|
|
/// `axum::Response`. `ApprovalPending` is a success for the client (it still has to answer), while
|
|
/// an unavailable elicitation and a failing call keep their era-correct tool-error shape.
|
|
pub(super) fn tool_command_payload(
|
|
message: &Value,
|
|
protocol_version: &str,
|
|
correlation: &CorrelationContext,
|
|
outcome: ToolsOutcome,
|
|
) -> ToolCommandPayload {
|
|
match outcome {
|
|
ToolsOutcome::Call(ToolCallOutcome::Completed(output))
|
|
| ToolsOutcome::Call(ToolCallOutcome::ApprovalPending(output)) => {
|
|
ToolCommandPayload::Ok(success_tool_payload(message, protocol_version, output))
|
|
}
|
|
ToolsOutcome::Call(ToolCallOutcome::ApprovalUnavailable(control_error)) => {
|
|
ToolCommandPayload::Ok(tool_error_payload(
|
|
message,
|
|
protocol_version,
|
|
control_tool_error_contract(
|
|
control_error,
|
|
correlation.request_id().as_str(),
|
|
correlation.trace_id().as_str(),
|
|
execution_locale(message),
|
|
),
|
|
))
|
|
}
|
|
ToolsOutcome::Call(ToolCallOutcome::InvalidParams(detail)) => {
|
|
ToolCommandPayload::Ok(jsonrpc_error(request_id(message), -32602, detail))
|
|
}
|
|
ToolsOutcome::Call(ToolCallOutcome::Error(contract)) => {
|
|
ToolCommandPayload::Ok(tool_error_payload(message, protocol_version, contract))
|
|
}
|
|
// The pending approval could not be persisted: the adapter answers its internal error shape,
|
|
// as the previous wire path did.
|
|
ToolsOutcome::Call(ToolCallOutcome::InternalFailure) => {
|
|
ToolCommandPayload::Internal("the pending approval request could not be persisted")
|
|
}
|
|
// A call command never produces these variants; they are answered with the adapter's
|
|
// internal error instead of being silently ignored.
|
|
ToolsOutcome::List { .. }
|
|
| ToolsOutcome::InvalidParams(_)
|
|
| ToolsOutcome::CatalogUnavailable => {
|
|
ToolCommandPayload::Internal("unexpected shared tools outcome for a tools/call")
|
|
}
|
|
}
|
|
}
|
|
|
|
/// The single-response form of [`tool_command_payload`].
|
|
pub(super) fn tool_command_response(
|
|
message: &Value,
|
|
response_mode: ResponseMode,
|
|
protocol_version: &str,
|
|
correlation: &CorrelationContext,
|
|
outcome: ToolsOutcome,
|
|
) -> Response {
|
|
match tool_command_payload(message, protocol_version, correlation, outcome) {
|
|
ToolCommandPayload::Ok(payload) => transport_response(
|
|
StatusCode::OK,
|
|
payload,
|
|
response_mode,
|
|
None,
|
|
Some(protocol_version),
|
|
),
|
|
ToolCommandPayload::Internal(detail) => internal_jsonrpc_error(message, detail),
|
|
}
|
|
}
|
|
|
|
pub(super) fn resource_error_response(
|
|
message: &Value,
|
|
response_mode: ResponseMode,
|
|
protocol_version: &str,
|
|
contract: ToolErrorContract,
|
|
) -> Response {
|
|
let mut error = jsonrpc_error(request_id(message), -32000, contract.message.clone());
|
|
error["error"]["data"] = json!({
|
|
"code": contract.code,
|
|
"error_code": contract.error_code,
|
|
"stage": contract.stage,
|
|
"retryability": contract.retryability,
|
|
"outcome_certainty": contract.outcome_certainty,
|
|
"request_id": contract.request_id,
|
|
"trace_id": contract.trace_id,
|
|
});
|
|
transport_response(
|
|
StatusCode::OK,
|
|
error,
|
|
response_mode,
|
|
None,
|
|
Some(protocol_version),
|
|
)
|
|
}
|
|
|
|
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 prompts_sdk_projection_preserves_typed_extensions_and_system_content() {
|
|
let prompt = json!({"name":"p", "description":null, "icons":null,
|
|
"x-prompt":{}, "arguments":[{"name":"count", "description":null,
|
|
"required":false, "schema":{"type":"integer"}, "default":7}]});
|
|
for cursor in [None, Some(String::new()), Some("opaque".to_owned())] {
|
|
let result = prompts_list_result(vec![prompt.clone()], cursor.clone()).unwrap();
|
|
assert_eq!(result["prompts"], json!([prompt]));
|
|
assert_eq!(result.get("nextCursor"), cursor.map(Value::String).as_ref());
|
|
assert!(result.get("resultType").is_none());
|
|
}
|
|
let messages = vec![
|
|
json!({"role":"system", "x-message":null,
|
|
"content":{"type":"text", "text":"\0é\n", "annotations":null, "x-content":[]}}),
|
|
json!({"role":"assistant", "content":{"type":"text", "text":""}}),
|
|
];
|
|
assert_eq!(
|
|
prompt_get_result(None, messages.clone()).unwrap(),
|
|
json!({"messages":messages})
|
|
);
|
|
assert_eq!(
|
|
prompts_list_result(vec![], None).unwrap(),
|
|
json!({"prompts":[]})
|
|
);
|
|
assert_eq!(
|
|
prompt_get_result(Some(String::new()), vec![]).unwrap(),
|
|
json!({"description":"", "messages":[]})
|
|
);
|
|
assert!(prompts_list_result(vec![json!({"name":42})], None).is_err());
|
|
assert!(
|
|
prompt_get_result(
|
|
None,
|
|
vec![json!({"role":"invalid", "content":{"type":"text", "text":"secret"}})]
|
|
)
|
|
.is_err()
|
|
);
|
|
}
|
|
|
|
#[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!({
|
|
"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(_)));
|
|
}
|
|
}
|
|
}
|