pmcp 2.2.0

High-quality Rust SDK for Model Context Protocol (MCP) with full TypeScript SDK compatibility
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
// Allow doc_markdown since this module has many technical terms (ChatGPT, MCP-UI, etc.)
#![allow(clippy::doc_markdown)]

//! UI Resource builders for multi-platform support.

use super::adapter::{
    ChatGptAdapter, McpAppsAdapter, McpUiAdapter, TransformedResource, UIAdapter,
};
use crate::types::mcp_apps::{ChatGptToolMeta, HostType, WidgetCSP, WidgetMeta};
use std::collections::HashMap;

/// A UI resource that can be transformed for multiple platforms.
///
/// This allows a single tool implementation to return content that works
/// across ChatGPT Apps, MCP Apps, and MCP-UI hosts.
///
/// # Example
///
/// ```rust
/// use pmcp::server::mcp_apps::{MultiPlatformResource, ChatGptAdapter, McpAppsAdapter};
/// use pmcp::types::mcp_apps::HostType;
///
/// let html = "<html><body>Chess board here</body></html>";
///
/// let mut multi = MultiPlatformResource::new(
///     "ui://chess/board.html",
///     "Chess Board",
///     html,
/// )
/// .with_adapter(ChatGptAdapter::new())
/// .with_adapter(McpAppsAdapter::new());
///
/// // Get content for a specific host
/// if let Some(transformed) = multi.for_host(HostType::ChatGpt) {
///     // Use transformed.content and transformed.metadata
///     assert!(!transformed.content.is_empty());
/// }
/// ```
pub struct MultiPlatformResource {
    /// Resource URI.
    uri: String,
    /// Display name.
    name: String,
    /// HTML content.
    html: String,
    /// Registered adapters.
    adapters: Vec<Box<dyn UIAdapter>>,
    /// Cached transformations.
    cache: HashMap<HostType, TransformedResource>,
}

impl std::fmt::Debug for MultiPlatformResource {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MultiPlatformResource")
            .field("uri", &self.uri)
            .field("name", &self.name)
            .field("html", &self.html)
            .field("adapters", &format!("[{} adapters]", self.adapters.len()))
            .field("cache", &self.cache)
            .finish()
    }
}

impl MultiPlatformResource {
    /// Create a new multi-platform resource.
    #[must_use]
    pub fn new(uri: impl Into<String>, name: impl Into<String>, html: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            name: name.into(),
            html: html.into(),
            adapters: Vec::new(),
            cache: HashMap::new(),
        }
    }

    /// Add an adapter for a specific platform.
    #[must_use]
    pub fn with_adapter<A: UIAdapter + 'static>(mut self, adapter: A) -> Self {
        self.adapters.push(Box::new(adapter));
        self
    }

    /// Add all standard adapters (ChatGPT, MCP Apps, MCP-UI).
    #[must_use]
    pub fn with_all_adapters(self) -> Self {
        self.with_adapter(ChatGptAdapter::new())
            .with_adapter(McpAppsAdapter::new())
            .with_adapter(McpUiAdapter::new())
    }

    /// Get the transformed resource for a specific host type.
    ///
    /// Returns `None` if no adapter is registered for this host.
    pub fn for_host(&mut self, host: HostType) -> Option<&TransformedResource> {
        // Check cache first
        if self.cache.contains_key(&host) {
            return self.cache.get(&host);
        }

        // Find matching adapter
        let adapter = self.adapters.iter().find(|a| a.host_type() == host)?;
        let transformed = adapter.transform(&self.uri, &self.name, &self.html);
        self.cache.insert(host, transformed);
        self.cache.get(&host)
    }

    /// Get all transformed resources.
    pub fn all_transforms(&mut self) -> Vec<&TransformedResource> {
        // Transform with all adapters
        for adapter in &self.adapters {
            let host = adapter.host_type();
            if !self.cache.contains_key(&host) {
                let transformed = adapter.transform(&self.uri, &self.name, &self.html);
                self.cache.insert(host, transformed);
            }
        }
        self.cache.values().collect()
    }

    /// Get the original HTML content.
    #[must_use]
    pub fn html(&self) -> &str {
        &self.html
    }

    /// Get the resource URI.
    #[must_use]
    pub fn uri(&self) -> &str {
        &self.uri
    }

    /// Get the resource name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }
}

/// Builder for creating UI resources with platform-specific configuration.
///
/// This builder provides a fluent API for configuring UI resources with
/// platform-specific metadata and CSP settings.
///
/// # Example
///
/// ```rust
/// use pmcp::server::mcp_apps::UIResourceBuilder;
///
/// let resource = UIResourceBuilder::new("ui://chess/board.html", "Chess Board")
///     .html("<html><body>Chess board</body></html>")
///     .chatgpt_invoking("Loading chess board...")
///     .chatgpt_widget_accessible(true)
///     .csp_connect("https://api.chess.com")
///     .build();
/// ```
#[derive(Debug, Default)]
pub struct UIResourceBuilder {
    /// Resource URI.
    uri: String,
    /// Display name.
    name: String,
    /// HTML content (if inline).
    html: Option<String>,
    /// Description.
    description: Option<String>,
    /// ChatGPT-specific tool metadata.
    chatgpt_meta: ChatGptToolMeta,
    /// Widget metadata for ChatGPT.
    widget_meta: WidgetMeta,
    /// Content Security Policy.
    csp: WidgetCSP,
}

impl UIResourceBuilder {
    /// Create a new UI resource builder.
    #[must_use]
    pub fn new(uri: impl Into<String>, name: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            name: name.into(),
            ..Default::default()
        }
    }

    /// Set inline HTML content.
    #[must_use]
    pub fn html(mut self, content: impl Into<String>) -> Self {
        self.html = Some(content.into());
        self
    }

    /// Set resource description.
    #[must_use]
    pub fn description(mut self, desc: impl Into<String>) -> Self {
        self.description = Some(desc.into());
        self
    }

    // =========================================================================
    // ChatGPT-specific configuration
    // =========================================================================

    /// Set ChatGPT output template URI.
    #[must_use]
    pub fn chatgpt_output_template(mut self, uri: impl Into<String>) -> Self {
        self.chatgpt_meta = self.chatgpt_meta.output_template(uri);
        self
    }

    /// Set ChatGPT invoking message.
    #[must_use]
    pub fn chatgpt_invoking(mut self, message: impl Into<String>) -> Self {
        self.chatgpt_meta = self.chatgpt_meta.invoking(message);
        self
    }

    /// Set ChatGPT invoked message.
    #[must_use]
    pub fn chatgpt_invoked(mut self, message: impl Into<String>) -> Self {
        self.chatgpt_meta = self.chatgpt_meta.invoked(message);
        self
    }

    /// Set whether the widget can call tools.
    #[must_use]
    pub fn chatgpt_widget_accessible(mut self, accessible: bool) -> Self {
        self.chatgpt_meta = self.chatgpt_meta.widget_accessible(accessible);
        self
    }

    /// Set widget border preference.
    #[must_use]
    pub fn widget_prefers_border(mut self, border: bool) -> Self {
        self.widget_meta = self.widget_meta.prefers_border(border);
        self
    }

    // =========================================================================
    // CSP configuration
    // =========================================================================

    /// Add allowed connect domain for CSP.
    #[must_use]
    pub fn csp_connect(mut self, domain: impl Into<String>) -> Self {
        self.csp = self.csp.connect(domain);
        self
    }

    /// Add allowed resource domain for CSP.
    #[must_use]
    pub fn csp_resource(mut self, domain: impl Into<String>) -> Self {
        self.csp = self.csp.resources(domain);
        self
    }

    /// Add allowed frame domain for CSP.
    #[must_use]
    pub fn csp_frame(mut self, domain: impl Into<String>) -> Self {
        self.csp = self.csp.frame(domain);
        self
    }

    // =========================================================================
    // Build methods
    // =========================================================================

    /// Build a `MultiPlatformResource`.
    ///
    /// Returns the resource info (uri, name) and the multi-platform resource.
    #[must_use]
    pub fn build(self) -> MultiPlatformResource {
        let html = self.html.unwrap_or_default();
        MultiPlatformResource::new(&self.uri, &self.name, html)
    }

    /// Build a `MultiPlatformResource` for ChatGPT only.
    #[must_use]
    pub fn build_chatgpt(self) -> MultiPlatformResource {
        let widget_meta = self.widget_meta.clone();
        let html = self.html.clone().unwrap_or_default();

        MultiPlatformResource::new(&self.uri, &self.name, html)
            .with_adapter(ChatGptAdapter::new().with_widget_meta(widget_meta))
    }

    /// Build a `MultiPlatformResource` for MCP Apps only.
    #[must_use]
    pub fn build_mcp_apps(self) -> MultiPlatformResource {
        let csp = self.csp.clone();
        let html = self.html.clone().unwrap_or_default();

        MultiPlatformResource::new(&self.uri, &self.name, html)
            .with_adapter(McpAppsAdapter::new().with_csp(csp))
    }

    /// Build a `MultiPlatformResource` for all platforms.
    #[must_use]
    pub fn build_all(self) -> MultiPlatformResource {
        let widget_meta = self.widget_meta.clone();
        let csp = self.csp.clone();
        let html = self.html.clone().unwrap_or_default();

        MultiPlatformResource::new(&self.uri, &self.name, html)
            .with_adapter(ChatGptAdapter::new().with_widget_meta(widget_meta))
            .with_adapter(McpAppsAdapter::new().with_csp(csp))
            .with_adapter(McpUiAdapter::new())
    }

    /// Get the ChatGPT tool metadata for use in tool definitions.
    #[must_use]
    pub fn chatgpt_tool_meta(&self) -> &ChatGptToolMeta {
        &self.chatgpt_meta
    }

    /// Get the widget metadata.
    #[must_use]
    pub fn widget_meta(&self) -> &WidgetMeta {
        &self.widget_meta
    }

    /// Get the CSP configuration.
    #[must_use]
    pub fn csp(&self) -> &WidgetCSP {
        &self.csp
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::mcp_apps::ExtendedUIMimeType;

    #[test]
    fn test_ui_resource_builder_basic() {
        let multi = UIResourceBuilder::new("ui://test/widget.html", "Test Widget")
            .html("<html><body>Test</body></html>")
            .description("A test widget")
            .build();

        assert_eq!(multi.uri(), "ui://test/widget.html");
        assert_eq!(multi.name(), "Test Widget");
    }

    #[test]
    fn test_ui_resource_builder_chatgpt_config() {
        let builder = UIResourceBuilder::new("ui://chess/board.html", "Chess Board")
            .html("<html><body>Board</body></html>")
            .chatgpt_invoking("Loading...")
            .chatgpt_invoked("Ready!")
            .chatgpt_widget_accessible(true);

        let meta = builder.chatgpt_tool_meta();
        // The meta should have the values set
        assert!(serde_json::to_value(meta).is_ok());
    }

    #[test]
    fn test_ui_resource_builder_csp() {
        let builder = UIResourceBuilder::new("ui://test/widget.html", "Test")
            .html("<html></html>")
            .csp_connect("https://api.example.com")
            .csp_resource("https://cdn.example.com");

        let csp = builder.csp();
        assert!(!csp.connect_domains.is_empty());
        assert!(!csp.resource_domains.is_empty());
    }

    #[test]
    fn test_multi_platform_resource() {
        let mut multi = MultiPlatformResource::new(
            "ui://test/widget.html",
            "Test Widget",
            "<html><body>Test</body></html>",
        )
        .with_all_adapters();

        let chatgpt = multi.for_host(HostType::ChatGpt);
        assert!(chatgpt.is_some());
        assert_eq!(
            chatgpt.unwrap().mime_type,
            ExtendedUIMimeType::HtmlSkybridge
        );

        let generic = multi.for_host(HostType::Generic);
        assert!(generic.is_some());
        assert_eq!(generic.unwrap().mime_type, ExtendedUIMimeType::HtmlMcpApp);
    }

    #[test]
    fn test_build_chatgpt() {
        let mut multi = UIResourceBuilder::new("ui://test/widget.html", "Test")
            .html("<html></html>")
            .chatgpt_invoking("Loading...")
            .build_chatgpt();

        let transformed = multi.for_host(HostType::ChatGpt);
        assert!(transformed.is_some());
    }

    #[test]
    fn test_build_all() {
        let mut multi = UIResourceBuilder::new("ui://test/widget.html", "Test")
            .html("<html></html>")
            .build_all();

        let transforms = multi.all_transforms();
        assert!(!transforms.is_empty());
    }
}