Skip to main content

rustango_cms/mcp/
mod.rs

1//! MCP engine — operate the CMS from an AI agent.
2//!
3//! The framework ships the whole protocol layer (`rustango::mcp`: JSON-RPC
4//! transport, SSE, agent auth incl. raw-key bearers, OAuth 2.1, skills +
5//! fail-closed authorization); this module contributes the **CMS tools** —
6//! read/search content, create + edit + publish pages, upload media, write
7//! translations, upsert snippets — plus the per-tenant skill seeding
8//! (`crate::seed`) and the key-management UI (account preferences / user
9//! form).
10//!
11//! ## Identity model
12//!
13//! Every tool requires a **user-owned key**: the token's `uid` resolves to a
14//! `rustango_users` row, and the tool acts *as that user* — page/collection
15//! permissions are enforced with the same `crate::permissions` checks the
16//! admin handlers use, revisions and page-log entries are attributed to the
17//! user, and the key's tool scope re-resolves from the owner's live RBAC on
18//! every request. Machine agents (no `uid`) are refused: CMS writes always
19//! have an accountable actor.
20//!
21//! ## Host wiring
22//!
23//! ```ignore
24//! let api = cms_admin
25//!     .merge(rustango_cms::mcp::router(&settings.mcp))
26//!     .merge(rustango_cms::api::router());
27//! let csrf = CsrfConfig::default().exempt_prefix(rustango_cms::mcp::MCP_PREFIX);
28//! ```
29//!
30//! The CSRF exemption is **required** — the global `CsrfLayer` otherwise
31//! rejects every JSON-RPC POST (bearer-authenticated requests carry no CSRF
32//! token, and don't need one: the endpoint never trusts cookies).
33
34use rustango::mcp::{McpContext, McpError};
35
36mod tools_read;
37mod tools_templates;
38mod tools_write;
39
40/// Where the MCP endpoint mounts, on every tenant host. Host apps must
41/// CSRF-exempt this prefix (see the module docs).
42pub const MCP_PREFIX: &str = "/cms-admin/mcp";
43
44/// The CMS MCP router: the framework's secure tenant router (agent JWT or
45/// raw `prefix.secret` bearer, tenant-pinned, fail-closed skills) nested
46/// under [`MCP_PREFIX`]. Merge it into the host router OUTSIDE any
47/// session-auth layer — it carries its own authentication.
48#[must_use]
49pub fn router(settings: &rustango::config::McpSettings) -> axum::Router {
50    axum::Router::new().nest(
51        MCP_PREFIX,
52        rustango::mcp::secure_tenant_router_from_settings(settings),
53    )
54}
55
56/// JSON-RPC error code for an in-tool authorization denial. Matches the
57/// dispatcher's `TOOL_FORBIDDEN` so clients render both the skill-level
58/// and the per-object denial the same way.
59pub(crate) const FORBIDDEN: i64 = -32003;
60
61/// The user a tool call acts as — the key owner, loaded fresh per call.
62pub struct ToolActor {
63    pub id: i64,
64    pub username: String,
65    pub is_superuser: bool,
66}
67
68impl ToolActor {
69    pub(crate) fn as_page_edit_actor(&self) -> crate::admin::PageEditActor {
70        crate::admin::PageEditActor {
71            id: self.id,
72            username: self.username.clone(),
73            is_superuser: self.is_superuser,
74        }
75    }
76}
77
78/// Resolve the acting user for a tool call. Refuses machine agents (CMS
79/// writes need an accountable user) and keys whose owner is gone or
80/// deactivated — fail-closed, mirroring the admin session checks.
81///
82/// Public so a host application's own tools gate the same way. A host
83/// that reimplemented this would have to duplicate the user lookup and
84/// the active check, and the first thing to drift would be the
85/// fail-closed behaviour.
86pub async fn require_actor(ctx: &McpContext) -> Result<ToolActor, McpError> {
87    use rustango::core::Column as _;
88    use rustango::tenancy::auth::User;
89
90    let Some(uid) = ctx.agent.user_id else {
91        return Err(McpError::new(
92            FORBIDDEN,
93            "CMS tools require a user-owned key (create one under \
94             Account → MCP keys); standalone machine agents are not \
95             accepted",
96        ));
97    };
98    let user = User::objects()
99        .where_(User::id.eq(uid))
100        .first(&ctx.pool)
101        .await
102        .map_err(|e| McpError::internal(format!("actor lookup: {e}")))?
103        .filter(|u| u.active)
104        .ok_or_else(|| McpError::new(FORBIDDEN, "key owner is missing or deactivated"))?;
105    Ok(ToolActor {
106        id: uid,
107        username: user.username,
108        is_superuser: user.is_superuser,
109    })
110}
111
112/// Require a permission codename (`cms_page.view`, …) — the same
113/// role-union check the admin's codename gates run, superuser bypassing.
114///
115/// Public for host tools, which need their own codenames checked
116/// against the same role union — see [`require_actor`].
117pub async fn require_codename(
118    pool: &rustango::sql::Pool,
119    actor: &ToolActor,
120    codename: &str,
121) -> Result<(), McpError> {
122    require_any_codename(pool, actor, &[codename]).await
123}
124
125/// [`require_codename`] satisfied by any one of `codenames` — for a
126/// resource with a broad grant and a narrower one (`cms_library.edit`
127/// or `cms_library_item__<type>.edit`).
128pub async fn require_any_codename(
129    pool: &rustango::sql::Pool,
130    actor: &ToolActor,
131    codenames: &[&str],
132) -> Result<(), McpError> {
133    if actor.is_superuser {
134        return Ok(());
135    }
136    let names = crate::permissions::user_codenames(pool, actor.id)
137        .await
138        .map_err(|e| McpError::internal(format!("permission lookup: {e}")))?;
139    if codenames.iter().any(|c| names.contains(*c)) {
140        Ok(())
141    } else {
142        Err(McpError::new(
143            FORBIDDEN,
144            format!("permission `{}` required", codenames.join("` or `")),
145        ))
146    }
147}
148
149/// Require a page-scoped action (`crate::permissions::user_can` — walks
150/// the page-permission tree, superuser short-circuits inside).
151pub(crate) async fn require_page_action(
152    pool: &rustango::sql::Pool,
153    actor: &ToolActor,
154    page_id: i64,
155    action: crate::permissions::Action,
156) -> Result<(), McpError> {
157    let allowed = crate::permissions::user_can(pool, actor.id, page_id, action)
158        .await
159        .map_err(|e| McpError::internal(format!("permission lookup: {e}")))?;
160    if allowed {
161        Ok(())
162    } else {
163        Err(McpError::new(
164            FORBIDDEN,
165            format!("action `{}` on page {page_id} denied", action.as_str()),
166        ))
167    }
168}
169
170/// Mint a v4 UUID for a stream-block `id` when the agent didn't supply
171/// one. Block ids are the stable anchors translation field-paths key off,
172/// so they're generated once and never re-minted.
173pub(crate) fn mint_uuid4() -> String {
174    let mut b = [0u8; 16];
175    let _ = getrandom::fill(&mut b);
176    b[6] = (b[6] & 0x0f) | 0x40;
177    b[8] = (b[8] & 0x3f) | 0x80;
178    let h = |r: std::ops::Range<usize>| {
179        b[r].iter().fold(String::new(), |mut acc, x| {
180            use std::fmt::Write as _;
181            let _ = write!(acc, "{x:02x}");
182            acc
183        })
184    };
185    format!(
186        "{}-{}-{}-{}-{}",
187        h(0..4),
188        h(4..6),
189        h(6..8),
190        h(8..10),
191        h(10..16)
192    )
193}
194
195/// Render a stored extension/builder value as the form-string the save
196/// pipeline expects. Checkbox semantics: `true` → `"on"`, `false`/null →
197/// key omitted (`None`).
198pub(crate) fn value_to_form_string(v: &serde_json::Value) -> Option<String> {
199    match v {
200        serde_json::Value::Null => None,
201        serde_json::Value::Bool(true) => Some("on".to_owned()),
202        serde_json::Value::Bool(false) => None,
203        serde_json::Value::String(s) => Some(s.clone()),
204        serde_json::Value::Number(n) => Some(n.to_string()),
205        arr_or_obj => serde_json::to_string(arr_or_obj).ok(),
206    }
207}