') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ', 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); fix: allow empty content in CallToolResult by anishathalye · Pull Request #681 · modelcontextprotocol/rust-sdk · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 1 addition & 40 deletions crates/rmcp/src/model.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2196,7 +2196,7 @@ pub type ElicitationCompletionNotification =
///
/// Contains the content returned by the tool execution and an optional
/// flag indicating whether the operation resulted in an error.
#[derive(Debug, Serialize, Clone, PartialEq)]
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CallToolResult {
Expand DownExpand Up@@ -2310,45 +2310,6 @@ impl CallToolResult {
}
}

// Custom deserialize implementation to validate mutual exclusivity
impl<'de> Deserialize<'de> for CallToolResult {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct CallToolResultHelper {
#[serde(skip_serializing_if = "Option::is_none")]
content: Option<Vec<Content>>,
#[serde(skip_serializing_if = "Option::is_none")]
structured_content: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
is_error: Option<bool>,
/// Accept `_meta` during deserialization
#[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
meta: Option<Meta>,
}

let helper = CallToolResultHelper::deserialize(deserializer)?;
let result = CallToolResult {
content: helper.content.unwrap_or_default(),
structured_content: helper.structured_content,
is_error: helper.is_error,
meta: helper.meta,
};

// Validate mutual exclusivity
if result.content.is_empty() && result.structured_content.is_none() {
return Err(serde::de::Error::custom(
"CallToolResult must have either content or structured_content",
));
}

Ok(result)
}
}

const_string!(ListToolsRequestMethod = "tools/list");
/// Request to list all available tools from a server
pub type ListToolsRequest = RequestOptionalParam<ListToolsRequestMethod, PaginatedRequestParams>;
Expand Down
60 changes: 59 additions & 1 deletion crates/rmcp/tests/test_structured_output.rs
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,7 +2,7 @@
use rmcp::{
Json, ServerHandler,
handler::server::{router::tool::ToolRouter, tool::IntoCallToolResult, wrapper::Parameters},
model::{CallToolResult, Content, Tool},
model::{CallToolResult, Content, ServerResult, Tool},
tool, tool_handler, tool_router,
};
use schemars::JsonSchema;
Expand DownExpand Up@@ -280,3 +280,61 @@ async fn test_output_schema_requires_structured_content() {
assert!(call_result.structured_content.is_some());
assert!(!call_result.content.is_empty());
}

#[tokio::test]
async fn test_empty_content_array_deserializes() {
let raw = json!({ "content": [] });
let result: CallToolResult = serde_json::from_value(raw).unwrap();
assert!(result.content.is_empty());
assert!(result.structured_content.is_none());
assert!(result.is_error.is_none());
}

#[tokio::test]
async fn test_empty_content_array_with_is_error() {
let raw = json!({ "content": [], "isError": false });
let result: CallToolResult = serde_json::from_value(raw).unwrap();
assert!(result.content.is_empty());
assert_eq!(result.is_error, Some(false));
}

#[tokio::test]
async fn test_missing_content_is_rejected() {
let raw = json!({ "isError": false });
let result: Result<CallToolResult, _> = serde_json::from_value(raw);
assert!(result.is_err());
}

#[tokio::test]
async fn test_missing_content_with_structured_content_is_rejected() {
let raw = json!({ "structuredContent": {"key": "value"}, "isError": false });
let result: Result<CallToolResult, _> = serde_json::from_value(raw);
assert!(result.is_err());
}

#[tokio::test]
async fn test_empty_content_deserializes_as_call_tool_result_variant() {
let raw = json!({ "content": [] });
let result: ServerResult = serde_json::from_value(raw).unwrap();
match result {
ServerResult::CallToolResult(call_result) => {
assert!(call_result.content.is_empty());
assert!(call_result.structured_content.is_none());
}
other => panic!("Expected CallToolResult, got {:?}", other),
}
}

#[tokio::test]
async fn test_empty_content_roundtrip() {
let result = CallToolResult {
content: vec![],
structured_content: None,
is_error: Some(false),
meta: None,
};
let v = serde_json::to_value(&result).unwrap();
assert_eq!(v["content"], json!([]));
let deserialized: CallToolResult = serde_json::from_value(v).unwrap();
assert_eq!(deserialized, result);
}