mcp_apps_server/metadata.rs
1use std::{error::Error, fmt};
2
3use rmcp::model::{JsonObject, MetaObject, Tool};
4use serde_json::Value;
5
6use crate::{ResourceUi, ToolUi};
7
8/// Metadata could not be prepared or composed with existing annotations.
9///
10/// Failed composition leaves the destination unchanged, even when a conflict
11/// occurs after other fields would otherwise have been inserted.
12#[derive(Debug)]
13#[non_exhaustive]
14pub enum MetadataError {
15 /// The existing root `ui` value is present but is not an object.
16 InvalidUi,
17 /// A provided field differs from an existing value.
18 Conflict {
19 /// The conflicting protocol path, for example `_meta.ui.resourceUri`.
20 path: String,
21 },
22 /// Serialization of a typed declaration failed.
23 Serialization(serde_json::Error),
24 /// A static resource's metadata factory failed to prepare extension data.
25 ///
26 /// Wrap another SDK's error here to retain its cause without adding that
27 /// SDK's types or validation rules to this library.
28 Preparation(Box<dyn Error + Send + Sync>),
29}
30
31impl fmt::Display for MetadataError {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 match self {
34 Self::InvalidUi => f.write_str("existing _meta.ui must be an object"),
35 Self::Conflict { path } => write!(f, "metadata conflict at {path}"),
36 Self::Serialization(error) => {
37 write!(f, "cannot serialize metadata declaration: {error}")
38 }
39 Self::Preparation(error) => write!(f, "cannot prepare resource metadata: {error}"),
40 }
41 }
42}
43
44impl Error for MetadataError {
45 fn source(&self) -> Option<&(dyn Error + 'static)> {
46 match self {
47 Self::Serialization(error) => Some(error),
48 Self::Preparation(error) => Some(error.as_ref()),
49 _ => None,
50 }
51 }
52}
53
54impl From<serde_json::Error> for MetadataError {
55 fn from(error: serde_json::Error) -> Self {
56 Self::Serialization(error)
57 }
58}
59
60impl ToolUi {
61 /// Prepare complete metadata for an `rmcp` tool or tool macro.
62 ///
63 /// When `resource_uri` is supplied, the default emits only nested
64 /// `ui.resourceUri`. Opt in to the deprecated flat alias with
65 /// [`Self::with_legacy_uri`].
66 ///
67 /// # Errors
68 ///
69 /// Returns [`MetadataError::Serialization`] if serialization fails.
70 pub fn to_meta(&self) -> Result<MetaObject, MetadataError> {
71 let mut meta = MetaObject::default();
72 self.merge_into(&mut meta)?;
73 Ok(meta)
74 }
75
76 /// Compose this declaration with existing tool metadata atomically.
77 ///
78 /// Unknown keys, including nested ones, survive. Omitted fields leave existing
79 /// values intact. Equal values are accepted; different scalar or array values
80 /// are conflicts. Objects merge recursively. An empty declaration does not
81 /// create `ui`, but still rejects an existing non-object `ui` entry.
82 ///
83 /// When `resource_uri` is supplied, a present deprecated `ui/resourceUri`
84 /// must equal it. The alias is preserved by default and emitted when
85 /// [`Self::with_legacy_uri`] was selected. Resource existence is the consumer's
86 /// responsibility.
87 ///
88 /// # Errors
89 ///
90 /// Returns [`MetadataError::InvalidUi`] for a non-object `ui`,
91 /// [`MetadataError::Conflict`] for unequal provided fields or a mismatched
92 /// legacy alias, or [`MetadataError::Serialization`] on serialization failure.
93 pub fn merge_into(&self, meta: &mut MetaObject) -> Result<(), MetadataError> {
94 *meta = self.merged_meta(meta)?;
95 Ok(())
96 }
97
98 fn merged_meta(&self, meta: &MetaObject) -> Result<MetaObject, MetadataError> {
99 let patch = serde_json::to_value(self)?;
100 if let Some(uri) = &self.resource_uri
101 && let Some(existing) = meta.0.get("ui/resourceUri")
102 && existing.as_str() != Some(uri.as_str())
103 {
104 return Err(MetadataError::Conflict {
105 path: "_meta.ui/resourceUri".into(),
106 });
107 }
108 let mut candidate = merged_ui(meta, patch)?;
109 if self.legacy_uri
110 && let Some(uri) = &self.resource_uri
111 {
112 candidate
113 .0
114 .insert("ui/resourceUri".into(), Value::String(uri.to_string()));
115 }
116 Ok(candidate)
117 }
118
119 /// Associate an existing tool while preserving its other declarations.
120 ///
121 /// Only metadata changes. The name, schemas, annotations and handler remain
122 /// owned by the consumer. An empty patch leaves absent metadata absent.
123 /// The complete tool is unchanged on an error.
124 ///
125 /// # Errors
126 ///
127 /// Returns the same validation and conflict errors as [`Self::merge_into`].
128 pub fn apply_to(&self, tool: &mut Tool) -> Result<(), MetadataError> {
129 let meta = self.merged_meta(tool.meta.as_ref().unwrap_or(&MetaObject::default()))?;
130 if tool.meta.is_some() || !meta.0.is_empty() {
131 tool.meta = Some(meta);
132 }
133 Ok(())
134 }
135}
136
137impl ResourceUi {
138 /// Prepare resource-content metadata containing this `ui` declaration.
139 ///
140 /// Attach it to contents returned by `resources/read`. Security metadata on a
141 /// tool is not a substitute. An empty declaration produces an empty map.
142 ///
143 /// # Errors
144 ///
145 /// Returns [`MetadataError::Serialization`] if serialization fails.
146 pub fn to_meta(&self) -> Result<MetaObject, MetadataError> {
147 let mut meta = MetaObject::default();
148 self.merge_into(&mut meta)?;
149 Ok(meta)
150 }
151
152 /// Compose resource UI metadata without discarding existing extension data.
153 ///
154 /// Omitted fields leave existing values intact. Objects merge recursively,
155 /// including unknown CSP and permission fields; arrays and scalars must equal
156 /// existing values. Explicit false, empty arrays and empty permission objects
157 /// are declarations rather than omission. This does not validate host-specific
158 /// domain formats or grant permissions.
159 ///
160 /// # Errors
161 ///
162 /// Returns [`MetadataError::InvalidUi`] for a non-object `ui`,
163 /// [`MetadataError::Conflict`] for unequal provided fields, or
164 /// [`MetadataError::Serialization`] on serialization failure. No mutation
165 /// occurs on any error.
166 pub fn merge_into(&self, meta: &mut MetaObject) -> Result<(), MetadataError> {
167 *meta = merged_ui(meta, serde_json::to_value(self)?)?;
168 Ok(())
169 }
170}
171
172fn merged_ui(meta: &MetaObject, patch: Value) -> Result<MetaObject, MetadataError> {
173 let patch: JsonObject = serde_json::from_value(patch)?;
174 if meta.0.get("ui").is_some_and(|value| !value.is_object()) {
175 return Err(MetadataError::InvalidUi);
176 }
177 let mut candidate = meta.clone();
178 if !patch.is_empty() {
179 match candidate.0.get_mut("ui") {
180 Some(Value::Object(existing)) => merge_object(existing, patch, "_meta.ui")?,
181 None => {
182 candidate.0.insert("ui".into(), Value::Object(patch));
183 }
184 _ => return Err(MetadataError::InvalidUi),
185 }
186 }
187 Ok(candidate)
188}
189
190fn merge_object(
191 destination: &mut JsonObject,
192 patch: JsonObject,
193 path: &str,
194) -> Result<(), MetadataError> {
195 for (key, proposed) in patch {
196 let field_path = format!("{path}.{key}");
197 match destination.get_mut(&key) {
198 Some(Value::Object(existing)) if proposed.is_object() => {
199 if let Value::Object(fields) = proposed {
200 merge_object(existing, fields, &field_path)?;
201 }
202 }
203 Some(existing) if *existing != proposed => {
204 return Err(MetadataError::Conflict { path: field_path });
205 }
206 Some(_) => {}
207 None => {
208 destination.insert(key, proposed);
209 }
210 }
211 }
212 Ok(())
213}