mcp_apps_server/lib.rs
1//! Typed MCP Apps registration and resources for rmcp servers.
2//!
3//! Start with [`StaticUiResource`] for embedded HTML. With the `server` feature,
4//! `AppRouter` groups rmcp tools and resources and checks their associations;
5//! `AppServer` provides the common server handling. With `macros`, the optional
6//! derive declares fixed views and `app_router` associates each UI tool with its
7//! view in one place. Manual declarations and routing remain directly usable.
8//! Consumers choose their runtime and transport and own business logic/access checks.
9//!
10//! # Simple application (`server` and `macros`)
11//!
12//! The consumer enables rmcp's `server` and `macros` features. The HTML below is
13//! this project's bundled example; use a path relative to your own declaring file.
14//! rmcp generates both schemas from the Rust models; no input schema JSON is needed.
15//!
16//! ```
17//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
18//! # #[cfg(all(feature = "server", feature = "macros"))] {
19//! use mcp_apps_server::{AppServer, StaticUiResource, app_router};
20//! use rmcp::{tool, schemars::JsonSchema, ServerHandler,
21//! handler::server::wrapper::{Json, Parameters}};
22//! use serde::{Deserialize, Serialize};
23//!
24//! #[derive(StaticUiResource)]
25//! #[ui_resource(id = "inventory/dashboard", name = "dashboard",
26//! html_file = "../examples/dashboard.html")]
27//! struct Dashboard;
28//!
29//! #[derive(Deserialize, JsonSchema)]
30//! #[schemars(crate = "rmcp::schemars")]
31//! #[serde(deny_unknown_fields)]
32//! struct Input { sku: String }
33//! #[derive(Serialize, JsonSchema)]
34//! #[schemars(crate = "rmcp::schemars")]
35//! struct Snapshot { sku: String, available: u32 }
36//! struct Inventory;
37//! #[app_router]
38//! impl Inventory {
39//! #[tool(description = "Read inventory")]
40//! #[ui(resource = Dashboard)]
41//! fn snapshot(&self, Parameters(input): Parameters<Input>) -> Json<Snapshot> {
42//! Json(Snapshot { sku: input.sku, available: 12 })
43//! }
44//! }
45//! let server = AppServer::new(Inventory, Inventory::app_router()?)?;
46//! assert!(server.get_info().capabilities.resources.is_some());
47//! assert!(server.get_tool("snapshot").is_some());
48//! # }
49//! # Ok(())
50//! # }
51//! ```
52//!
53//! Construction performs no request or transport activity. Call rmcp's
54//! `ServiceExt::serve` with the transport you choose when ready to serve. The
55//! repository's `examples/server.rs` supplies the complete stdio lifecycle.
56//!
57//! # Custom integration
58//!
59//! Keep your own `ServerHandler` when you need authorization middleware, prompts,
60//! unrelated resources or custom lifecycle behavior. Prepare the same router,
61//! call its validation before serving, then delegate with the original request
62//! and context. Its lists are unpaginated; your handler owns filtering, pagination
63//! and selecting other resource owners. Callback errors are not fallback signals.
64//! See `AppRouter` for executable tool and dynamic-resource examples and
65//! `AppServer` for the supported ready-server methods. The repository's
66//! `examples/custom_server.rs` implements the complete manual equivalent.
67//!
68//! <details>
69//! <summary>Implement your own handler over the same prepared router</summary>
70//!
71//! This handler replaces the ready adapter. With macros, obtain the same router
72//! from `Inventory::app_router()`; with manual declarations, register resources
73//! and associate rmcp tools explicitly. Validate the router and
74//! store it with your application state. These methods let you insert access
75//! checks and retain other MCP methods. A fully manual resource declaration is
76//! demonstrated on [`StaticUiResource`].
77//!
78//! ```
79//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
80//! # #[cfg(feature = "server")] {
81//! use mcp_apps_server::{AppRouter, UiResource, UiResourceRoute, UiResourceUri};
82//! use rmcp::{ErrorData, RoleServer, ServerHandler, model::*, service::RequestContext};
83//!
84//! struct ExistingServer<S> { state: S, apps: AppRouter<S> }
85//! impl<S: Send + Sync + 'static> ServerHandler for ExistingServer<S> {
86//! fn get_info(&self) -> ServerConfig {
87//! let mut info = ServerConfig::default();
88//! self.apps.declare_capabilities(&mut info.capabilities);
89//! info
90//! }
91//! fn get_tool(&self, name: &str) -> Option<Tool> { self.apps.get_tool(name) }
92//! async fn list_tools(&self, request: Option<PaginatedRequestParams>, _: RequestContext<RoleServer>)
93//! -> Result<ListToolsResult, ErrorData> { self.apps.list_tools(request) }
94//! async fn list_resources(&self, request: Option<PaginatedRequestParams>, _: RequestContext<RoleServer>)
95//! -> Result<ListResourcesResult, ErrorData> { self.apps.list_resources(request) }
96//! async fn call_tool(&self, request: CallToolRequestParams, context: RequestContext<RoleServer>)
97//! -> Result<CallToolResponse, ErrorData> {
98//! // Authorize the original request before delegating.
99//! self.apps.call_tool(&self.state, request, context).await
100//! }
101//! async fn read_resource(&self, request: ReadResourceRequestParams, context: RequestContext<RoleServer>)
102//! -> Result<ReadResourceResponse, ErrorData> {
103//! // Select other resource owners by URI here when needed.
104//! self.apps.read_resource(&self.state, request, context).await
105//! }
106//! }
107//! # let mut apps = AppRouter::<()>::new();
108//! # apps.register_resource(UiResourceRoute::static_html(
109//! # UiResource::new(UiResourceUri::new("ui://inventory/dashboard.html")?, "dashboard"),
110//! # "<!doctype html><html><body>Inventory</body></html>"))?;
111//! # apps.validate()?;
112//! # let server = ExistingServer { state: (), apps };
113//! # assert!(server.get_info().capabilities.resources.is_some());
114//! # }
115//! # Ok(())
116//! # }
117//! ```
118//!
119//! </details>
120//!
121//! # Low-level declarations
122//!
123//! [`UiResource`] prepares a descriptor and matching HTML contents. [`ToolUi`]
124//! and [`ResourceUi`] prepare typed declarations and compose them into open rmcp
125//! metadata, preserving unknown keys. Omitted fields leave existing values intact;
126//! unequal supplied scalar/array values return [`MetadataError::Conflict`] without
127//! a partial update. These primitives remain usable without either optional feature.
128//!
129//! ```
130//! use mcp_apps_server::{ResourceUi, UiResource, UiResourceUri};
131//! let resource = UiResource::new(UiResourceUri::new("ui://inventory/dashboard")?, "dashboard");
132//! let mut ui = ResourceUi::default();
133//! ui.prefers_border = Some(true);
134//! let contents = resource.html_contents("<!doctype html><html><body>Inventory</body></html>")
135//! .with_meta(ui.to_meta()?);
136//! # let _ = contents;
137//! # Ok::<(), Box<dyn std::error::Error>>(())
138//! ```
139//!
140//! # Capabilities, security and limits
141//!
142//! [`ui_capability`] inspects caller-supplied client capabilities and distinguishes
143//! absent, malformed and valid non-HTML support. On current rmcp requests use
144//! `RequestContext::client_capabilities()` rather than assume initialization is
145//! always the source. The consuming application chooses its fallback behavior.
146//!
147//! HTML is supplied by the consumer, without parsing, sanitization or bundling.
148//! CSP, permissions and visibility are declarations for the host, not access
149//! control implemented by the server. The browser renders the interface and the
150//! host mediates communication. Local protocol checks do not establish real-host
151//! rendering or permission behavior. No runtime, transport or background work is
152//! started by this crate.
153
154#![forbid(unsafe_code)]
155#![deny(missing_docs)]
156#![deny(rustdoc::broken_intra_doc_links)]
157
158mod capabilities;
159mod metadata;
160mod resource;
161#[cfg(feature = "server")]
162mod router;
163#[cfg(feature = "server")]
164mod server;
165mod ui;
166mod uri;
167
168pub use capabilities::{CapabilityError, UiCapability, declare_ui_extension, ui_capability};
169/// Derive a static resource's declaration, embedded HTML and optional metadata.
170///
171/// Requires `macros` (or its compatibility alias `derive`). Supply `name`, either
172/// `id` or `uri`, and either `html_file` or `html` as string literals in
173/// `#[ui_resource(...)]`. `id` is a nonempty logical identifier without `ui://`;
174/// that prefix is added and the resulting URI is validated. `uri` supplies a
175/// complete URI. Neither form requires an `.html` suffix or derives identity from
176/// the filesystem. `html` retains the original file-path meaning of `html_file`.
177/// Supplying both alternatives of a pair is a compilation error.
178/// Optional `description` is a string; `ui` is a function path returning
179/// [`ResourceUi`], `meta` is a function path returning `Result<MetaObject,
180/// MetadataError>`, and `crate` is the path of a renamed dependency. The complete
181/// open map from `meta` is composed with `ui` at registration; omitted options
182/// retain trait defaults. See [`StaticUiResource::meta`] for extension ownership,
183/// preparation errors and the placement of returned annotations.
184/// The compiler includes the UTF-8 HTML file relative to the declaring Rust file.
185/// Nothing is read from the filesystem by the running server. Generic struct
186/// parameters and bounds are retained without adding field-trait requirements.
187/// For a fixed view, prefer a fieldless struct. Its type identifies the resource;
188/// registration never constructs an instance or reads any struct fields.
189///
190/// Invalid literal URIs are compilation errors, using the runtime's parser:
191///
192/// ```compile_fail
193/// use mcp_apps_server::StaticUiResource;
194/// #[derive(StaticUiResource)]
195/// #[ui_resource(uri = "https://example.com/view", name = "view", html = "../examples/dashboard.html")]
196/// struct InvalidView;
197/// ```
198#[cfg(feature = "macros")]
199pub use mcp_apps_server_macros::StaticUiResource;
200/// Declare an application's rmcp tools and their static UI resources together.
201///
202/// Requires `macros` and `server`; the consumer enables rmcp's `macros` feature.
203/// Apply this to an inherent impl with directly annotated rmcp `#[tool]` methods.
204/// Mark UI tools with `#[ui(resource = ResourceType)]`; the type must implement
205/// [`StaticUiResource`]. Unmarked tools keep their original declarations.
206/// Do not also apply rmcp's `tool_router` to this block.
207///
208/// The generated public `app_router()` method prepares an [`AppRouter`] and returns
209/// registration errors before serving. It registers resources first, composes each
210/// association into rmcp's original tool metadata, then registers checked routes.
211/// Custom rmcp tool names, schemas, annotations and callbacks are retained. Several
212/// tools can share a URI only with identical descriptors, HTML and content metadata.
213/// Metadata conflicts and duplicate tool names fail rather than overwrite routes.
214/// A failed preparation returns no router; tool handlers are never called by it.
215/// Resource declaration methods and rmcp metadata factories must have no side effects.
216///
217/// Use `#[app_router(crate = apps_sdk)]` for a renamed runtime dependency. Generic
218/// impl bounds are preserved; router preparation requires `Self: Sized + Send +
219/// Sync + 'static`. Method `cfg` and gating `cfg_attr` attributes also
220/// gate registration; put `tool` and `ui` directly on the method, outside `cfg_attr`.
221/// Helper methods remain unchanged; the method name `app_router` is reserved.
222/// The macro does not implement `ServerHandler`, start a transport or load assets.
223/// Pass its router to [`AppServer::new`] or invoke it from your custom handler.
224/// See the crate's getting-started example for a complete typed workflow.
225#[cfg(all(feature = "macros", feature = "server"))]
226pub use mcp_apps_server_macros::app_router;
227pub use metadata::MetadataError;
228pub use resource::{StaticUiResource, UiResource};
229/// An open MCP metadata map, reused from rmcp for extension annotations.
230///
231/// This is the same type as [`rmcp::model::MetaObject`]; its keys and values are
232/// owned by the extension that defines them. See [`StaticUiResource::meta`] for
233/// composition with generic MCP Apps resource settings.
234pub use rmcp::model::MetaObject;
235#[cfg(feature = "server")]
236pub use router::{AppRouter, HtmlFuture, RegistrationError, UiResourceRoute};
237#[cfg(feature = "server")]
238pub use server::AppServer;
239pub use ui::{PermissionRequest, ResourceUi, ToolUi, UiCsp, UiPermissions, UiVisibility};
240pub use uri::{UiResourceUri, UiUriError};
241
242/// The MCP Apps HTML MIME type required on returned resource contents.
243pub const UI_MIME_TYPE: &str = "text/html;profile=mcp-app";
244
245/// The standard MCP Apps capability extension identifier.
246pub const UI_EXTENSION_ID: &str = "io.modelcontextprotocol/ui";