Skip to main content

mz_environmentd/http/
mcp.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Model Context Protocol (MCP) HTTP handlers.
11//!
12//! Exposes Materialize data products to AI agents via JSON-RPC 2.0 over HTTP POST.
13//!
14//! ## Endpoints
15//!
16//! - `/api/mcp/agent` - User data products for customer AI agents
17//! - `/api/mcp/developer` - System catalog (`mz_*`) for troubleshooting
18//! - `/api/mcp` - The unified route that replaces both
19//!
20//! ## Tools
21//!
22//! **Agent:** `get_data_products`, `get_data_product_details`, `read_data_product`, `query`
23//! **Developer:** `query_system_catalog`, `query`
24//! **Unified:** `list_data_products`, `get_data_product_details`, `query`
25//!
26//! `read_data_product` and the agent and developer `query` tools are
27//! dyncfg-gated. `list_data_products` and `get_data_products` are one tool, and
28//! either name works on the agent route and on `/api/mcp`.
29//!
30//! Data products are discovered via `mz_internal.mz_mcp_data_products` system view.
31
32use std::borrow::Cow;
33use std::collections::BTreeSet;
34use std::sync::Arc;
35
36use anyhow::anyhow;
37use axum::Extension;
38use axum::Json;
39use axum::body::Bytes;
40use axum::extract::rejection::{JsonRejection, MissingJsonContentType};
41use axum::response::IntoResponse;
42use base64::Engine;
43use base64::engine::general_purpose::STANDARD as BASE64;
44use http::{HeaderMap, HeaderValue, StatusCode, header};
45use mz_adapter_types::dyncfgs::{
46    ENABLE_MCP_AGENT, ENABLE_MCP_AGENT_QUERY_TOOL, ENABLE_MCP_AGENT_READ_DATA_PRODUCT_TOOL,
47    ENABLE_MCP_DEVELOPER, ENABLE_MCP_DEVELOPER_QUERY_TOOL, ENABLE_MCP_UNIFIED,
48    MCP_MAX_RESPONSE_SIZE, MCP_REQUEST_TIMEOUT,
49};
50use mz_ore::cast::CastLossy;
51use mz_repr::namespaces::{self, SYSTEM_SCHEMAS};
52use mz_sql::names::ResolvedDatabaseSpecifier;
53use mz_sql::parse::{parse_item_name_with_limit, parse_with_limit};
54use mz_sql::plan::is_side_effecting_func_name;
55use mz_sql::session::metadata::SessionMetadata;
56use mz_sql::session::vars::{APPLICATION_NAME, Var, VarInput};
57use mz_sql_parser::ast::display::{AstDisplay, escaped_string_literal};
58use mz_sql_parser::ast::visit::{self, Visit};
59use mz_sql_parser::ast::visit_mut::{self, VisitMut};
60use mz_sql_parser::ast::{
61    CteBlock, Function, Ident, Raw, RawItemName, ShowStatement, Statement, UnresolvedItemName,
62    UnresolvedSchemaName,
63};
64use serde::{Deserialize, Serialize};
65use serde_json::json;
66use thiserror::Error;
67use tracing::{debug, warn};
68
69use crate::http::AuthedClient;
70use crate::http::mcp_metrics::{McpCallStatus, McpMetrics, ToolCallGuard};
71use crate::http::sql::{SqlRequest, SqlResponse, SqlResult, execute_request};
72
73// To add a tool: a `ToolsCallParams` variant and its `route_name` arm, an entry in
74// `handle_tools_list`, a `handle_tools_call` arm, and a mention in each route's
75// `endpoint_instructions`. Nothing checks the instructions at compile time.
76
77/// JSON-RPC protocol version used in all MCP requests and responses.
78const JSONRPC_VERSION: &str = "2.0";
79
80/// MCP protocol version returned in the `initialize` response.
81/// Spec: <https://modelcontextprotocol.io/specification/2025-11-25>
82const MCP_PROTOCOL_VERSION: &str = ProtocolVersion::V2025_11_25.as_str();
83
84/// The protocol revision a request is served on.
85#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86enum ProtocolVersion {
87    /// `initialize` handshake. Also serves 2025-06-18 and earlier clients.
88    V2025_11_25,
89    /// Per-request `_meta`, no handshake.
90    V2026_07_28,
91}
92
93impl ProtocolVersion {
94    /// Picks the revision from the `MCP-Protocol-Version` header's value, not
95    /// its presence: 2025-06-18 and 2025-11-25 clients send the header too.
96    ///
97    /// Anything else falls back to 2025-11-25 on purpose, never a 400. A 400
98    /// with a 2026-07-28 error tells dual-era clients the server speaks that
99    /// revision, so they stop falling back to `initialize`.
100    ///
101    /// Any copy naming 2026-07-28 selects it. Serving 2025-11-25 there would
102    /// skip the header check while a proxy that reads that copy trusts
103    /// `Mcp-Name`. `McpHeaders::check` then refuses the repetition.
104    fn select(values: &[HeaderValue]) -> Self {
105        if asks_for_2026_07_28(values) {
106            Self::V2026_07_28
107        } else {
108            Self::V2025_11_25
109        }
110    }
111
112    const fn as_str(self) -> &'static str {
113        match self {
114            Self::V2025_11_25 => "2025-11-25",
115            Self::V2026_07_28 => "2026-07-28",
116        }
117    }
118
119    /// Whether this is a modern revision, the spec's term for 2026-07-28 and
120    /// later: no handshake, and each request carries its version and client
121    /// capabilities in `params._meta`, with the method and tool name mirrored in
122    /// headers.
123    fn is_modern(self) -> bool {
124        matches!(self, Self::V2026_07_28)
125    }
126}
127
128/// The body read as untyped JSON, for the 2026-07-28 checks on fields the typed
129/// parse drops. Only 2026-07-28 requests pay for the second read.
130#[derive(Debug, Default, Deserialize)]
131struct RawRequest {
132    jsonrpc: Option<serde_json::Value>,
133    #[serde(default, deserialize_with = "present_id")]
134    id: Option<serde_json::Value>,
135    method: Option<serde_json::Value>,
136    params: Option<serde_json::Value>,
137}
138
139impl RawRequest {
140    /// `None` when the body is not a JSON object.
141    fn parse(body: &[u8]) -> Option<Self> {
142        serde_json::from_slice(body).ok()
143    }
144
145    fn method(&self) -> Option<&str> {
146        self.method.as_ref()?.as_str()
147    }
148
149    fn tool(&self) -> ToolName<'_> {
150        if self.method() != Some("tools/call") {
151            return ToolName::NotToolsCall;
152        }
153        match self.params.as_ref().and_then(|params| params.get("name")) {
154            Some(serde_json::Value::String(name)) => ToolName::Name(name),
155            _ => ToolName::Missing,
156        }
157    }
158}
159
160/// The tool name a request's `Mcp-Name` header must mirror.
161#[derive(Debug, Clone, Copy)]
162enum ToolName<'a> {
163    /// Not a `tools/call`, so `Mcp-Name` is not checked.
164    NotToolsCall,
165    /// A `tools/call` that names no tool, which no header matches.
166    Missing,
167    Name(&'a str),
168}
169
170/// Runs the checks every 2026-07-28 request gets before dispatch: a JSON-RPC
171/// 2.0 envelope, the mirrored headers, and `params._meta`.
172fn check_modern_request(headers: &McpHeaders, raw: &RawRequest) -> Result<(), McpRequestError> {
173    let method = raw
174        .method()
175        .filter(|_| raw.jsonrpc.as_ref().and_then(|v| v.as_str()) == Some(JSONRPC_VERSION))
176        .ok_or_else(|| McpRequestError::InvalidRequest("not a JSON-RPC 2.0 request".into()))?;
177    headers.check(method, raw.tool())?;
178    check_request_meta(raw.params.as_ref())
179}
180
181/// Whether any `MCP-Protocol-Version` copy names 2026-07-28, also inside a
182/// comma-joined list.
183fn asks_for_2026_07_28<'a>(values: impl IntoIterator<Item = &'a HeaderValue>) -> bool {
184    // Bytes, since a copy with a non-ASCII byte elsewhere still names it.
185    let modern = ProtocolVersion::V2026_07_28.as_str().as_bytes();
186    values
187        .into_iter()
188        .flat_map(|value| value.as_bytes().split(|byte| *byte == b','))
189        .any(|version| version.trim_ascii() == modern)
190}
191
192/// Checks the `params._meta` fields every 2026-07-28 request must carry: the
193/// protocol version, matching its header, and the client capabilities.
194fn check_request_meta(params: Option<&serde_json::Value>) -> Result<(), McpRequestError> {
195    let invalid = |message: String| McpRequestError::InvalidParams(message);
196    let meta = match params.and_then(|params| params.get("_meta")) {
197        None => return Err(invalid("missing params._meta".into())),
198        Some(serde_json::Value::Object(meta)) => meta,
199        Some(_) => return Err(invalid("params._meta must be an object".into())),
200    };
201
202    let version_key = "io.modelcontextprotocol/protocolVersion";
203    let body_version = match meta.get(version_key) {
204        None => return Err(invalid(format!("missing {version_key} in params._meta"))),
205        Some(serde_json::Value::String(version)) => version,
206        Some(_) => {
207            return Err(invalid(format!(
208                "{version_key} in params._meta must be a string"
209            )));
210        }
211    };
212    // The header check already pinned the header to this version.
213    let header_version = ProtocolVersion::V2026_07_28.as_str();
214    if body_version != header_version {
215        return Err(McpRequestError::HeaderMismatch(format!(
216            "MCP-Protocol-Version header value '{header_version}' does not match body value '{body_version}'"
217        )));
218    }
219
220    let capabilities_key = "io.modelcontextprotocol/clientCapabilities";
221    match meta.get(capabilities_key) {
222        None => Err(invalid(format!(
223            "missing {capabilities_key} in params._meta"
224        ))),
225        Some(serde_json::Value::Object(_)) => Ok(()),
226        Some(_) => Err(invalid(format!(
227            "{capabilities_key} in params._meta must be an object"
228        ))),
229    }
230}
231
232/// The request headers the Streamable HTTP transport defines, with every
233/// occurrence kept: a repeated header is rejected rather than reduced to one.
234struct McpHeaders {
235    protocol_version: Vec<HeaderValue>,
236    method: Vec<HeaderValue>,
237    name: Vec<HeaderValue>,
238}
239
240impl McpHeaders {
241    fn from_map(headers: &HeaderMap) -> Self {
242        let all = |name| headers.get_all(name).iter().cloned().collect();
243        Self {
244            protocol_version: all("mcp-protocol-version"),
245            method: all("mcp-method"),
246            name: all("mcp-name"),
247        }
248    }
249
250    /// Rejects a request whose mirrored headers are missing or disagree with
251    /// the body, so a proxy routing on the headers sees what we execute.
252    fn check(&self, method: &str, tool: ToolName<'_>) -> Result<(), McpRequestError> {
253        let version = header_text(&self.protocol_version, "MCP-Protocol-Version")?;
254        let modern = ProtocolVersion::V2026_07_28.as_str();
255        if version != modern {
256            return Err(McpRequestError::HeaderMismatch(format!(
257                "MCP-Protocol-Version header value '{version}' is not '{modern}'"
258            )));
259        }
260        let header_method = header_text(&self.method, "Mcp-Method")?;
261        if header_method != method {
262            return Err(McpRequestError::HeaderMismatch(format!(
263                "Mcp-Method header value '{header_method}' does not match body value '{method}'"
264            )));
265        }
266        let tool = match tool {
267            ToolName::NotToolsCall => return Ok(()),
268            ToolName::Missing => None,
269            ToolName::Name(name) => Some(name),
270        };
271        let header_name = decode_mcp_name(header_text(&self.name, "Mcp-Name")?)?;
272        if Some(header_name.as_ref()) != tool {
273            return Err(McpRequestError::HeaderMismatch(format!(
274                "Mcp-Name header value '{header_name}' does not match body value '{}'",
275                tool.unwrap_or_default()
276            )));
277        }
278        Ok(())
279    }
280}
281
282fn header_text<'a>(values: &'a [HeaderValue], name: &str) -> Result<&'a str, McpRequestError> {
283    let value = match values {
284        [value] => value,
285        [] => {
286            return Err(McpRequestError::HeaderMismatch(format!(
287                "missing {name} header"
288            )));
289        }
290        _ => {
291            return Err(McpRequestError::HeaderMismatch(format!(
292                "repeated {name} header"
293            )));
294        }
295    };
296    value.to_str().map_err(|_| {
297        McpRequestError::HeaderMismatch(format!("{name} header has invalid characters"))
298    })
299}
300
301/// Decodes the `=?base64?...?=` form clients use for names that are not plain
302/// ASCII. Any other value is the name as is.
303fn decode_mcp_name(value: &str) -> Result<Cow<'_, str>, McpRequestError> {
304    let Some(encoded) = value
305        .strip_prefix("=?base64?")
306        .and_then(|rest| rest.strip_suffix("?="))
307    else {
308        return Ok(Cow::Borrowed(value));
309    };
310    let invalid = || McpRequestError::HeaderMismatch("Mcp-Name header has invalid Base64".into());
311    let bytes = BASE64.decode(encoded).map_err(|_| invalid())?;
312    String::from_utf8(bytes)
313        .map(Cow::Owned)
314        .map_err(|_| invalid())
315}
316
317// Discovery uses the lightweight view (no JSON schema computation).
318const DISCOVERY_QUERY: &str = "SELECT * FROM mz_internal.mz_mcp_data_products";
319const DETAILS_QUERY_PREFIX: &str =
320    "SELECT * FROM mz_internal.mz_mcp_data_product_details WHERE object_name = ";
321
322/// MCP request errors, mapped to JSON-RPC error codes.
323#[derive(Debug, Error)]
324enum McpRequestError {
325    #[error("Invalid JSON-RPC version: expected 2.0")]
326    InvalidJsonRpcVersion,
327    #[error("Method not found: {0}")]
328    MethodNotFound(String),
329    #[error("Tool not found: {0}")]
330    ToolNotFound(String),
331    #[error("Data product not found: {0}")]
332    DataProductNotFound(String),
333    #[error("Query validation failed: {0}")]
334    QueryValidationFailed(String),
335    #[error("Query execution failed: {0}")]
336    QueryExecutionFailed(String),
337    #[error("Internal error: {0}")]
338    Internal(#[from] anyhow::Error),
339    #[error("Header mismatch: {0}")]
340    HeaderMismatch(String),
341    #[error("Invalid params: {0}")]
342    InvalidParams(String),
343    #[error("Invalid request: {0}")]
344    InvalidRequest(String),
345    #[error("Parse error: {0}")]
346    ParseError(String),
347}
348
349impl McpRequestError {
350    fn error_code(&self) -> i32 {
351        match self {
352            Self::InvalidJsonRpcVersion => error_codes::INVALID_REQUEST,
353            Self::MethodNotFound(_) => error_codes::METHOD_NOT_FOUND,
354            Self::ToolNotFound(_) => error_codes::INVALID_PARAMS,
355            Self::DataProductNotFound(_) => error_codes::INVALID_PARAMS,
356            Self::QueryValidationFailed(_) => error_codes::INVALID_PARAMS,
357            Self::QueryExecutionFailed(_) | Self::Internal(_) => error_codes::INTERNAL_ERROR,
358            Self::HeaderMismatch(_) => error_codes::HEADER_MISMATCH,
359            Self::InvalidParams(_) => error_codes::INVALID_PARAMS,
360            Self::InvalidRequest(_) => error_codes::INVALID_REQUEST,
361            Self::ParseError(_) => error_codes::PARSE_ERROR,
362        }
363    }
364
365    fn error_type(&self) -> &'static str {
366        match self {
367            Self::InvalidJsonRpcVersion => "InvalidRequest",
368            Self::MethodNotFound(_) => "MethodNotFound",
369            Self::ToolNotFound(_) => "ToolNotFound",
370            Self::DataProductNotFound(_) => "DataProductNotFound",
371            Self::QueryValidationFailed(_) => "ValidationError",
372            Self::QueryExecutionFailed(_) => "ExecutionError",
373            Self::Internal(_) => "InternalError",
374            Self::HeaderMismatch(_) => "HeaderMismatch",
375            Self::InvalidParams(_) => "InvalidParams",
376            Self::InvalidRequest(_) => "InvalidRequest",
377            Self::ParseError(_) => "ParseError",
378        }
379    }
380}
381
382/// JSON-RPC 2.0 request. Requests have `id`; notifications don't.
383#[derive(Debug, Deserialize)]
384pub(crate) struct McpRequest {
385    jsonrpc: String,
386    #[serde(default, deserialize_with = "present_id")]
387    id: Option<serde_json::Value>,
388    #[serde(flatten)]
389    method: McpMethod,
390}
391
392/// Wraps a `null` id in `Some`, so it stays a request. A missing `id` is `None`
393/// through `#[serde(default)]` on the field, and only that is a notification.
394fn present_id<'de, D>(deserializer: D) -> Result<Option<serde_json::Value>, D::Error>
395where
396    D: serde::Deserializer<'de>,
397{
398    serde_json::Value::deserialize(deserializer).map(Some)
399}
400
401/// MCP request ids are strings or numbers. Any other id, `null` included, gets
402/// `-32600` with no id in the reply.
403fn is_valid_request_id(id: &serde_json::Value) -> bool {
404    matches!(
405        id,
406        serde_json::Value::String(_) | serde_json::Value::Number(_)
407    )
408}
409
410fn invalid_id() -> McpRequestError {
411    McpRequestError::InvalidRequest("id must be a string or a number".into())
412}
413
414/// MCP method variants with their associated parameters.
415#[derive(Debug, Deserialize)]
416#[serde(tag = "method", content = "params")]
417enum McpMethod {
418    #[serde(rename = "initialize")]
419    Initialize(#[allow(dead_code)] InitializeParams),
420    /// `params` is accepted and ignored: clients may attach `_meta`, and a unit
421    /// variant would fail the whole request with a non-JSON-RPC 422.
422    #[serde(rename = "tools/list")]
423    ToolsList(#[allow(dead_code)] Option<serde_json::Value>),
424    #[serde(rename = "tools/call")]
425    ToolsCall(#[serde(deserialize_with = "deserialize_tools_call")] ToolsCallParams),
426    /// Keepalive, and the post-initialize acknowledgement. Named so their
427    /// `params` deserialize and they keep their own metric label. Other methods
428    /// with `params` reach `Unknown` through [`as_unknown_method`].
429    #[serde(rename = "ping")]
430    Ping(#[allow(dead_code)] Option<serde_json::Value>),
431    #[serde(rename = "notifications/initialized")]
432    NotificationsInitialized(#[allow(dead_code)] Option<serde_json::Value>),
433    /// `params` is accepted and ignored, as on `tools/list`.
434    #[serde(rename = "server/discover")]
435    ServerDiscover(#[allow(dead_code)] Option<serde_json::Value>),
436    /// Catch-all for unrecognized methods.
437    #[serde(other)]
438    Unknown,
439}
440
441impl std::fmt::Display for McpMethod {
442    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
443        match self {
444            McpMethod::Initialize(_) => write!(f, "initialize"),
445            McpMethod::ToolsList(_) => write!(f, "tools/list"),
446            McpMethod::ToolsCall(_) => write!(f, "tools/call"),
447            McpMethod::Ping(_) => write!(f, "ping"),
448            McpMethod::NotificationsInitialized(_) => write!(f, "notifications/initialized"),
449            McpMethod::ServerDiscover(_) => write!(f, "server/discover"),
450            McpMethod::Unknown => write!(f, "unknown"),
451        }
452    }
453}
454
455/// The client's `initialize` params. Deserialized so a malformed request fails,
456/// but no field is read.
457#[derive(Debug, Deserialize)]
458struct InitializeParams {
459    #[serde(rename = "protocolVersion")]
460    #[allow(dead_code)]
461    protocol_version: String,
462    #[serde(default)]
463    #[allow(dead_code)]
464    capabilities: serde_json::Value,
465    #[serde(rename = "clientInfo")]
466    #[allow(dead_code)]
467    client_info: Option<ClientInfo>,
468}
469
470#[derive(Debug, Deserialize)]
471struct ClientInfo {
472    #[allow(dead_code)]
473    name: String,
474    #[allow(dead_code)]
475    version: String,
476}
477
478/// Tool call parameters, deserialized via adjacently tagged enum.
479/// Serde maps `name` to the variant and `arguments` to the variant's data.
480#[derive(Debug, Deserialize)]
481#[serde(tag = "name", content = "arguments")]
482#[serde(rename_all = "snake_case")]
483enum ToolsCallParams {
484    // Agent endpoint tools
485    GetDataProducts(NoArguments),
486    GetDataProductDetails(GetDataProductDetailsParams),
487    ReadDataProduct(ReadDataProductParams),
488    Query(QueryParams),
489    // Developer endpoint tools
490    QuerySystemCatalog(QuerySystemCatalogParams),
491}
492
493/// Arguments of a tool that takes none. A struct rather than `()`: read from a
494/// `serde_json::Value`, `()` accepts `{}` only if serde buffers `arguments`
495/// ahead of `name`, which depends on key order (`preserve_order` keeps the
496/// client's order).
497#[derive(Debug, Deserialize)]
498#[serde(deny_unknown_fields)]
499struct NoArguments {}
500
501/// `arguments` is optional in the MCP spec, but adjacent tagging requires the
502/// content key, so a call that omits it, or sends `null`, is given `{}`.
503fn deserialize_tools_call<'de, D>(deserializer: D) -> Result<ToolsCallParams, D::Error>
504where
505    D: serde::Deserializer<'de>,
506{
507    let mut params = serde_json::Value::deserialize(deserializer)?;
508    if let serde_json::Value::Object(fields) = &mut params {
509        let arguments = fields.entry("arguments").or_insert(serde_json::Value::Null);
510        if arguments.is_null() {
511            *arguments = json!({});
512        }
513        // Mapped here because `#[serde(alias)]` would add the new name to the
514        // "expected one of" list in the unknown tool error the old routes
515        // return, which they must keep unchanged.
516        if fields.get("name").and_then(serde_json::Value::as_str) == Some(LIST_DATA_PRODUCTS) {
517            fields.insert("name".to_string(), json!("get_data_products"));
518        }
519    }
520    serde_json::from_value(params).map_err(serde::de::Error::custom)
521}
522
523/// The `/api/mcp` name of `get_data_products`.
524const LIST_DATA_PRODUCTS: &str = "list_data_products";
525
526impl ToolsCallParams {
527    /// The name `endpoint_type` shows for this tool, also used as the
528    /// `tool_name` metric label so a route's metric keeps its name whichever
529    /// name the client sent.
530    fn route_name(&self, endpoint_type: McpEndpointType) -> &'static str {
531        match (self, endpoint_type) {
532            (ToolsCallParams::GetDataProducts(_), McpEndpointType::Unified) => LIST_DATA_PRODUCTS,
533            (ToolsCallParams::GetDataProducts(_), _) => "get_data_products",
534            (ToolsCallParams::GetDataProductDetails(_), _) => "get_data_product_details",
535            (ToolsCallParams::ReadDataProduct(_), _) => "read_data_product",
536            (ToolsCallParams::Query(_), _) => "query",
537            (ToolsCallParams::QuerySystemCatalog(_), _) => "query_system_catalog",
538        }
539    }
540}
541
542#[derive(Debug, Deserialize)]
543struct GetDataProductDetailsParams {
544    name: String,
545}
546
547#[derive(Debug, Deserialize)]
548struct ReadDataProductParams {
549    name: String,
550    #[serde(default = "default_read_limit")]
551    limit: u32,
552    cluster: Option<String>,
553}
554
555/// Default row cap for `read_data_product` when the caller omits `limit`.
556const DEFAULT_READ_LIMIT: u32 = 500;
557
558fn default_read_limit() -> u32 {
559    DEFAULT_READ_LIMIT
560}
561
562#[derive(Debug, Deserialize)]
563struct QueryParams {
564    /// Required on the developer endpoint. The agent and unified endpoints
565    /// accept `None` (omitted or JSON null) so products whose cluster discovery
566    /// hides stay readable (DEX-71).
567    cluster: Option<String>,
568    /// Honored on the developer and unified endpoints. The agent endpoint's
569    /// dispatch arm drops it, since replica pinning is not part of the agent
570    /// surface.
571    cluster_replica: Option<String>,
572    sql_query: String,
573}
574
575impl QueryParams {
576    fn developer_placement(&self) -> Result<Placement<'_>, McpRequestError> {
577        match (self.cluster.as_deref(), self.cluster_replica.as_deref()) {
578            (None, _) => Err(McpRequestError::QueryValidationFailed(
579                "cluster is required".to_string(),
580            )),
581            (Some(cluster), None) => Ok(Placement::Cluster(cluster)),
582            (Some(cluster), Some(replica)) => Ok(Placement::Replica { cluster, replica }),
583        }
584    }
585
586    fn unified_placement(&self) -> Result<Placement<'_>, McpRequestError> {
587        match (self.cluster.as_deref(), self.cluster_replica.as_deref()) {
588            (None, None) => Ok(Placement::SessionDefault),
589            // A lone replica would pin a replica of the session's default
590            // cluster.
591            (None, Some(_)) => Err(McpRequestError::QueryValidationFailed(
592                "cluster_replica requires cluster".to_string(),
593            )),
594            (Some(cluster), None) => Ok(Placement::Cluster(cluster)),
595            (Some(cluster), Some(replica)) => Ok(Placement::Replica { cluster, replica }),
596        }
597    }
598}
599
600/// Where a read runs. Each endpoint builds it under its own rule.
601#[derive(Debug, Clone, Copy, PartialEq, Eq)]
602enum Placement<'a> {
603    SessionDefault,
604    Cluster(&'a str),
605    /// One replica of `cluster`, e.g. for `EXPLAIN ANALYZE` on a cluster with
606    /// more than one replica.
607    Replica {
608        cluster: &'a str,
609        replica: &'a str,
610    },
611}
612
613impl<'a> Placement<'a> {
614    fn cluster_or_default(cluster: Option<&'a str>) -> Self {
615        cluster.map_or(Placement::SessionDefault, Placement::Cluster)
616    }
617
618    /// The `SET` clause scoping a read to this placement. Names are escaped,
619    /// since they are interpolated into SQL string literals.
620    fn set_clause(&self) -> Option<String> {
621        match self {
622            Placement::SessionDefault => None,
623            Placement::Cluster(cluster) => {
624                Some(format!("SET CLUSTER = {}", escaped_string_literal(cluster)))
625            }
626            Placement::Replica { cluster, replica } => Some(format!(
627                "SET CLUSTER = {}; SET CLUSTER_REPLICA = {}",
628                escaped_string_literal(cluster),
629                escaped_string_literal(replica),
630            )),
631        }
632    }
633
634    /// Rejects an empty or whitespace-only name, which would otherwise reach
635    /// the engine as `SET CLUSTER = ''` and fail there as an opaque execution
636    /// error.
637    fn validate(&self) -> Result<(), McpRequestError> {
638        let names = match self {
639            Placement::SessionDefault => [None, None],
640            Placement::Cluster(cluster) => [Some(("cluster", *cluster)), None],
641            Placement::Replica { cluster, replica } => [
642                Some(("cluster", *cluster)),
643                Some(("cluster_replica", *replica)),
644            ],
645        };
646        for (field, value) in names.into_iter().flatten() {
647            if value.trim().is_empty() {
648                return Err(McpRequestError::QueryValidationFailed(format!(
649                    "{field} must not be empty or whitespace-only"
650                )));
651            }
652        }
653        Ok(())
654    }
655}
656
657#[derive(Debug, Deserialize)]
658struct QuerySystemCatalogParams {
659    sql_query: String,
660}
661
662#[derive(Debug, Serialize)]
663struct McpResponse {
664    jsonrpc: String,
665    /// `None` when the request's id is unknown. MCP ids cannot be `null`.
666    #[serde(skip_serializing_if = "Option::is_none")]
667    id: Option<serde_json::Value>,
668    #[serde(skip_serializing_if = "Option::is_none")]
669    result: Option<McpResultBody>,
670    #[serde(skip_serializing_if = "Option::is_none")]
671    error: Option<McpError>,
672}
673
674impl McpResponse {
675    /// A successful JSON-RPC response carrying `result`.
676    fn success(id: serde_json::Value, result: McpResultBody) -> Self {
677        Self {
678            jsonrpc: JSONRPC_VERSION.to_string(),
679            id: Some(id),
680            result: Some(result),
681            error: None,
682        }
683    }
684
685    /// A JSON-RPC error response carrying `error`.
686    fn error(id: impl Into<Option<serde_json::Value>>, error: McpError) -> Self {
687        Self {
688            jsonrpc: JSONRPC_VERSION.to_string(),
689            id: id.into(),
690            result: None,
691            error: Some(error),
692        }
693    }
694}
695
696/// Typed MCP response results.
697#[derive(Debug, Serialize)]
698#[serde(untagged)]
699enum McpResult {
700    Initialize(InitializeResult),
701    Discover(DiscoverResult),
702    ToolsList(ToolsListResult),
703    ToolContent(ToolContentResult),
704}
705
706impl McpResult {
707    fn into_body(self, protocol: ProtocolVersion, endpoint_type: McpEndpointType) -> McpResultBody {
708        let common = protocol.is_modern().then(|| CommonResultFields {
709            result_type: "complete",
710            cache: self.cache_hints(),
711            meta: ResultMeta {
712                server_info: server_info(endpoint_type),
713            },
714        });
715        McpResultBody {
716            result: self,
717            common,
718        }
719    }
720
721    fn cache_hints(&self) -> Option<CacheHints> {
722        match self {
723            // `private` so a shared cache never serves it to a caller who
724            // cannot authenticate to this environment.
725            McpResult::Discover(_) | McpResult::ToolsList(_) => Some(CacheHints {
726                ttl_ms: CACHE_TTL_MS,
727                cache_scope: "private",
728            }),
729            McpResult::Initialize(_) | McpResult::ToolContent(_) => None,
730        }
731    }
732}
733
734/// How long a client may consider a cacheable result fresh, in milliseconds.
735/// Kept short so flag changes reach clients soon.
736const CACHE_TTL_MS: u64 = 60_000;
737
738/// A result as sent. `common` is `None` on 2025-11-25, whose results carry
739/// neither field.
740#[derive(Debug, Serialize)]
741struct McpResultBody {
742    #[serde(flatten)]
743    result: McpResult,
744    #[serde(flatten)]
745    common: Option<CommonResultFields>,
746}
747
748#[derive(Debug, Serialize)]
749struct CommonResultFields {
750    #[serde(rename = "resultType")]
751    result_type: &'static str,
752    #[serde(flatten)]
753    cache: Option<CacheHints>,
754    #[serde(rename = "_meta")]
755    meta: ResultMeta,
756}
757
758/// Required on cacheable results, such as `tools/list`.
759#[derive(Debug, Serialize)]
760struct CacheHints {
761    #[serde(rename = "ttlMs")]
762    ttl_ms: u64,
763    #[serde(rename = "cacheScope")]
764    cache_scope: &'static str,
765}
766
767#[derive(Debug, Serialize)]
768struct ResultMeta {
769    #[serde(rename = "io.modelcontextprotocol/serverInfo")]
770    server_info: ServerInfo,
771}
772
773#[derive(Debug, Serialize)]
774struct InitializeResult {
775    #[serde(rename = "protocolVersion")]
776    protocol_version: String,
777    capabilities: Capabilities,
778    #[serde(rename = "serverInfo")]
779    server_info: ServerInfo,
780    #[serde(skip_serializing_if = "Option::is_none")]
781    instructions: Option<String>,
782}
783
784#[derive(Debug, Serialize)]
785struct DiscoverResult {
786    #[serde(rename = "supportedVersions")]
787    supported_versions: [&'static str; 2],
788    capabilities: Capabilities,
789    #[serde(skip_serializing_if = "Option::is_none")]
790    instructions: Option<String>,
791}
792
793#[derive(Debug, Serialize)]
794struct Capabilities {
795    tools: serde_json::Value,
796}
797
798#[derive(Debug, Serialize)]
799struct ServerInfo {
800    name: String,
801    version: String,
802}
803
804#[derive(Debug, Serialize)]
805struct ToolsListResult {
806    tools: Vec<ToolDefinition>,
807}
808
809#[derive(Debug, Serialize)]
810struct ToolDefinition {
811    name: String,
812    #[serde(skip_serializing_if = "Option::is_none")]
813    title: Option<String>,
814    description: String,
815    #[serde(rename = "inputSchema")]
816    input_schema: serde_json::Value,
817    #[serde(skip_serializing_if = "Option::is_none")]
818    annotations: Option<ToolAnnotations>,
819}
820
821/// MCP 2025-11-25 tool annotations that describe tool behavior.
822/// These hints help clients make trust and safety decisions.
823#[derive(Debug, Serialize)]
824struct ToolAnnotations {
825    #[serde(rename = "readOnlyHint", skip_serializing_if = "Option::is_none")]
826    read_only_hint: Option<bool>,
827    #[serde(rename = "destructiveHint", skip_serializing_if = "Option::is_none")]
828    destructive_hint: Option<bool>,
829    #[serde(rename = "idempotentHint", skip_serializing_if = "Option::is_none")]
830    idempotent_hint: Option<bool>,
831    #[serde(rename = "openWorldHint", skip_serializing_if = "Option::is_none")]
832    open_world_hint: Option<bool>,
833}
834
835/// Annotations for all MCP tools: read-only, non-destructive, idempotent.
836const READ_ONLY_ANNOTATIONS: ToolAnnotations = ToolAnnotations {
837    read_only_hint: Some(true),
838    destructive_hint: Some(false),
839    idempotent_hint: Some(true),
840    open_world_hint: Some(false),
841};
842
843#[derive(Debug, Serialize)]
844struct ToolContentResult {
845    content: Vec<ContentBlock>,
846    /// Always `false`: tool failures surface as JSON-RPC errors instead.
847    #[serde(rename = "isError")]
848    is_error: bool,
849}
850
851#[derive(Debug, Serialize)]
852struct ContentBlock {
853    #[serde(rename = "type")]
854    content_type: String,
855    text: String,
856}
857
858/// JSON-RPC 2.0 error codes.
859mod error_codes {
860    pub const PARSE_ERROR: i32 = -32700;
861    pub const INVALID_REQUEST: i32 = -32600;
862    pub const METHOD_NOT_FOUND: i32 = -32601;
863    pub const INVALID_PARAMS: i32 = -32602;
864    pub const INTERNAL_ERROR: i32 = -32603;
865    pub const HEADER_MISMATCH: i32 = -32020;
866}
867
868#[derive(Debug, Serialize)]
869struct McpError {
870    code: i32,
871    message: String,
872    #[serde(skip_serializing_if = "Option::is_none")]
873    data: Option<serde_json::Value>,
874}
875
876impl From<McpRequestError> for McpError {
877    fn from(err: McpRequestError) -> Self {
878        McpError {
879            code: err.error_code(),
880            message: err.to_string(),
881            data: Some(json!({
882                "error_type": err.error_type(),
883            })),
884        }
885    }
886}
887
888#[derive(Debug, Clone, Copy)]
889enum McpEndpointType {
890    Agent,
891    Developer,
892    Unified,
893}
894
895impl McpEndpointType {
896    /// Static label for metrics. Avoids per-request allocation that would
897    /// come from going through `Display`.
898    fn as_label(self) -> &'static str {
899        match self {
900            McpEndpointType::Agent => "agent",
901            McpEndpointType::Developer => "developer",
902            McpEndpointType::Unified => "unified",
903        }
904    }
905}
906
907impl std::fmt::Display for McpEndpointType {
908    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
909        f.write_str(self.as_label())
910    }
911}
912
913/// MCP 2025-11-25 requires servers to return 405 for GET requests
914/// on endpoints that only support POST.
915pub async fn handle_mcp_method_not_allowed() -> impl IntoResponse {
916    StatusCode::METHOD_NOT_ALLOWED
917}
918
919/// Agent endpoint: exposes user data products.
920pub async fn handle_mcp_agent(
921    headers: HeaderMap,
922    Extension(allowed_origins): Extension<Arc<Vec<HeaderValue>>>,
923    Extension(metrics): Extension<McpMetrics>,
924    client: AuthedClient,
925    body: Bytes,
926) -> axum::response::Response {
927    if let Some(resp) = validate_origin(&headers, &allowed_origins) {
928        return resp;
929    }
930    handle_mcp_request(
931        client,
932        parse_mcp_request(&headers, &body),
933        McpHeaders::from_map(&headers),
934        body,
935        McpEndpointType::Agent,
936        metrics,
937    )
938    .await
939    .into_response()
940}
941
942/// Developer endpoint: exposes system catalog (mz_*) only.
943pub async fn handle_mcp_developer(
944    headers: HeaderMap,
945    Extension(allowed_origins): Extension<Arc<Vec<HeaderValue>>>,
946    Extension(metrics): Extension<McpMetrics>,
947    client: AuthedClient,
948    body: Bytes,
949) -> axum::response::Response {
950    if let Some(resp) = validate_origin(&headers, &allowed_origins) {
951        return resp;
952    }
953    handle_mcp_request(
954        client,
955        parse_mcp_request(&headers, &body),
956        McpHeaders::from_map(&headers),
957        body,
958        McpEndpointType::Developer,
959        metrics,
960    )
961    .await
962    .into_response()
963}
964
965/// Unified endpoint at `/api/mcp`.
966pub async fn handle_mcp_unified(
967    headers: HeaderMap,
968    Extension(allowed_origins): Extension<Arc<Vec<HeaderValue>>>,
969    Extension(metrics): Extension<McpMetrics>,
970    client: AuthedClient,
971    body: Bytes,
972) -> axum::response::Response {
973    if let Some(resp) = validate_origin(&headers, &allowed_origins) {
974        return resp;
975    }
976    handle_mcp_request(
977        client,
978        parse_mcp_request(&headers, &body),
979        McpHeaders::from_map(&headers),
980        body,
981        McpEndpointType::Unified,
982        metrics,
983    )
984    .await
985    .into_response()
986}
987
988/// Parses a request body the way axum's `Json` extractor does, so every
989/// rejection keeps its status and text. The one exception: an unknown method
990/// that carries `params` becomes `McpMethod::Unknown` instead of a 422 (see
991/// [`as_unknown_method`]). The body arrives through `Bytes`, so the route's
992/// `DefaultBodyLimit` still applies.
993fn parse_mcp_request(headers: &HeaderMap, body: &[u8]) -> Result<McpRequest, JsonRejection> {
994    if !is_json_content_type(headers) {
995        return Err(MissingJsonContentType::default().into());
996    }
997    match Json::<McpRequest>::from_bytes(body) {
998        Ok(Json(request)) => Ok(request),
999        Err(JsonRejection::JsonDataError(rejection)) => {
1000            as_unknown_method(body).ok_or_else(|| rejection.into())
1001        }
1002        Err(rejection) => Err(rejection),
1003    }
1004}
1005
1006/// The `Content-Type` check axum's `Json` extractor runs before parsing.
1007fn is_json_content_type(headers: &HeaderMap) -> bool {
1008    let Some(mime) = headers
1009        .get(header::CONTENT_TYPE)
1010        .and_then(|value| value.to_str().ok())
1011        .and_then(|value| value.parse::<mime::Mime>().ok())
1012    else {
1013        return false;
1014    };
1015    mime.type_() == "application"
1016        && (mime.subtype() == "json" || mime.suffix().is_some_and(|name| name == "json"))
1017}
1018
1019/// The request `body` would produce if `McpMethod::Unknown` accepted `params`,
1020/// or `None` when its method is one we know, whose parse error must stand.
1021///
1022/// `#[serde(other)]` only matches a unit variant, so an unknown method with
1023/// `params` fails the whole body. Every 2026-07-28 client sends `params`.
1024fn as_unknown_method(body: &[u8]) -> Option<McpRequest> {
1025    #[derive(Deserialize)]
1026    struct Envelope {
1027        jsonrpc: String,
1028        #[serde(default, deserialize_with = "present_id")]
1029        id: Option<serde_json::Value>,
1030        method: String,
1031    }
1032    let envelope: Envelope = serde_json::from_slice(body).ok()?;
1033    // Without `params`, a known method either parses to its own variant or
1034    // fails on its missing params. Only an unknown one parses to `Unknown`.
1035    let method: McpMethod = serde_json::from_value(json!({ "method": envelope.method })).ok()?;
1036    matches!(method, McpMethod::Unknown).then(|| McpRequest {
1037        jsonrpc: envelope.jsonrpc,
1038        id: envelope.id,
1039        method,
1040    })
1041}
1042
1043/// Validates the Origin header against the CORS allowlist to prevent DNS
1044/// rebinding attacks (MCP spec 2025-11-25). Returns Some(403) if Origin is
1045/// present but not on the allowlist. Returns None if absent (non-browser
1046/// client) or allowed.
1047///
1048/// Note: this server-side check is required in addition to the CorsLayer.
1049/// CorsLayer only controls response headers and can be bypassed when the
1050/// attacker arranges same-origin DNS rebinding (no preflight fires).
1051fn validate_origin(
1052    headers: &HeaderMap,
1053    allowed: &[HeaderValue],
1054) -> Option<axum::response::Response> {
1055    let origin = headers.get(http::header::ORIGIN)?;
1056    if mz_http_util::origin_is_allowed(origin, allowed) {
1057        return None;
1058    }
1059    warn!(
1060        origin = ?origin,
1061        "MCP request rejected: origin not in allowlist",
1062    );
1063    Some(StatusCode::FORBIDDEN.into_response())
1064}
1065
1066async fn handle_mcp_request(
1067    mut client: AuthedClient,
1068    request: Result<McpRequest, JsonRejection>,
1069    mcp_headers: McpHeaders,
1070    body: Bytes,
1071    endpoint_type: McpEndpointType,
1072    metrics: McpMetrics,
1073) -> impl IntoResponse {
1074    let protocol = ProtocolVersion::select(&mcp_headers.protocol_version);
1075    // Only a 2026-07-28 request gets a JSON-RPC answer for a body that is not
1076    // JSON or not a request. Every other request gets axum's rejection.
1077    let request =
1078        match request {
1079            Err(
1080                rejection @ (JsonRejection::JsonDataError(_) | JsonRejection::JsonSyntaxError(_)),
1081            ) if protocol.is_modern() => Err(rejection),
1082            Err(rejection) => return rejection.into_response(),
1083            Ok(request) => Ok(request),
1084        };
1085    let endpoint_label = endpoint_type.as_label();
1086    let method_label = match &request {
1087        Ok(request) => request.method.to_string(),
1088        Err(_) => "invalid".to_string(),
1089    };
1090    let record_request =
1091        |status: McpCallStatus| metrics.record_request(endpoint_label, &method_label, status);
1092
1093    // Check the per-endpoint feature flag via a catalog snapshot, similar to peek_sequencing.rs.
1094    // The configured `MCP_REQUEST_TIMEOUT` lives in the snapshot we are about
1095    // to fetch, so bound this phase with the compiled-in default. Without it a
1096    // stalled snapshot would hang the request past any configured timeout.
1097    let catalog = match tokio::time::timeout(
1098        *MCP_REQUEST_TIMEOUT.default(),
1099        client.client.catalog_snapshot("mcp"),
1100    )
1101    .await
1102    {
1103        Ok(catalog) => catalog,
1104        Err(_elapsed) => {
1105            warn!(endpoint = %endpoint_type, "MCP catalog snapshot timed out");
1106            record_request(McpCallStatus::Timeout);
1107            return StatusCode::SERVICE_UNAVAILABLE.into_response();
1108        }
1109    };
1110    let dyncfgs = catalog.system_config().dyncfgs();
1111    let enabled = match endpoint_type {
1112        McpEndpointType::Agent => ENABLE_MCP_AGENT.get(dyncfgs),
1113        McpEndpointType::Developer => ENABLE_MCP_DEVELOPER.get(dyncfgs),
1114        McpEndpointType::Unified => ENABLE_MCP_UNIFIED.get(dyncfgs),
1115    };
1116    if !enabled {
1117        debug!(endpoint = %endpoint_type, "MCP endpoint disabled by feature flag");
1118        record_request(McpCallStatus::EndpointDisabled);
1119        return StatusCode::SERVICE_UNAVAILABLE.into_response();
1120    }
1121
1122    // Per-endpoint feature flag for the `query` tool. Agent and developer have
1123    // independent rollouts; collapsing to one bool keeps the downstream
1124    // signatures unchanged since each handler invocation is already bound to a
1125    // single endpoint.
1126    let query_tool_enabled = match endpoint_type {
1127        McpEndpointType::Agent => ENABLE_MCP_AGENT_QUERY_TOOL.get(dyncfgs),
1128        McpEndpointType::Developer => ENABLE_MCP_DEVELOPER_QUERY_TOOL.get(dyncfgs),
1129        // `query` is one of the route's three tools. `enable_mcp_unified`
1130        // gates the whole route.
1131        McpEndpointType::Unified => true,
1132    };
1133    // Only the agent route has `read_data_product`.
1134    let read_data_product_tool_enabled = match endpoint_type {
1135        McpEndpointType::Agent => ENABLE_MCP_AGENT_READ_DATA_PRODUCT_TOOL.get(dyncfgs),
1136        McpEndpointType::Developer | McpEndpointType::Unified => false,
1137    };
1138    let max_response_size = MCP_MAX_RESPONSE_SIZE.get(dyncfgs);
1139    let request_timeout = MCP_REQUEST_TIMEOUT.get(dyncfgs);
1140
1141    let request = match request {
1142        Ok(request) => request,
1143        Err(rejection) => {
1144            return answer_parse_failure(rejection, &body, &mcp_headers, &record_request);
1145        }
1146    };
1147
1148    // Tag MCP-originated sessions so they're distinguishable in
1149    // mz_session_history / mz_statement_execution_history. set_default lets a
1150    // caller still override via `?options={"application_name":"..."}`
1151    let app_name = match endpoint_type {
1152        McpEndpointType::Agent => "mz_mcp_agents",
1153        McpEndpointType::Developer => "mz_mcp_developer",
1154        McpEndpointType::Unified => "mz_mcp",
1155    };
1156    client
1157        .client
1158        .session()
1159        .vars_mut()
1160        .set_default(APPLICATION_NAME.name(), VarInput::Flat(app_name))
1161        .expect("application_name is a known session var");
1162
1163    let user = client.client.session().user().name.clone();
1164    let is_notification = request.id.is_none();
1165
1166    debug!(
1167        method = %request.method,
1168        endpoint = %endpoint_type,
1169        user = %user,
1170        is_notification = is_notification,
1171        ?protocol,
1172        "MCP request received"
1173    );
1174
1175    // No `id` means no reply, which the transport answers 202. SDK clients take
1176    // any other status as a response to parse and close on the empty body.
1177    if is_notification {
1178        // 2026-07-28 refuses a notification it cannot accept with a 400.
1179        if protocol.is_modern() && request.jsonrpc != JSONRPC_VERSION {
1180            let err = McpRequestError::InvalidRequest("not a JSON-RPC 2.0 request".into());
1181            record_request(McpCallStatus::Error(err.error_type()));
1182            let response = McpResponse::error(None, err.into());
1183            return (StatusCode::BAD_REQUEST, Json(response)).into_response();
1184        }
1185        debug!(method = %request.method, "Received notification (no response will be sent)");
1186        record_request(McpCallStatus::Ok);
1187        return StatusCode::ACCEPTED.into_response();
1188    }
1189
1190    if !request.id.as_ref().is_some_and(is_valid_request_id) {
1191        let err = invalid_id();
1192        record_request(McpCallStatus::Error(err.error_type()));
1193        let status = if protocol.is_modern() {
1194            StatusCode::BAD_REQUEST
1195        } else {
1196            StatusCode::OK
1197        };
1198        return (status, Json(McpResponse::error(None, err.into()))).into_response();
1199    }
1200
1201    let request_id = request.id.clone().unwrap_or(serde_json::Value::Null);
1202
1203    // The transport leaves header rules for notification POSTs undefined, so
1204    // only requests are checked. A failed check is transport validation, so it
1205    // gets a 400 even where its JSON-RPC code is -32602.
1206    if protocol.is_modern() {
1207        let raw = RawRequest::parse(&body).unwrap_or_default();
1208        if let Err(err) = check_modern_request(&mcp_headers, &raw) {
1209            record_request(McpCallStatus::Error(err.error_type()));
1210            let response = McpResponse::error(request_id, err.into());
1211            return (StatusCode::BAD_REQUEST, Json(response)).into_response();
1212        }
1213    }
1214
1215    // Spawn task for fault isolation, with a timeout safety net.
1216    // `abort_on_drop` propagates the timeout to the task itself; without
1217    // it the task orphans and the SQL query keeps running in the
1218    // background after the client gives up (see database-issues#9947).
1219    let metrics_inner = metrics.clone();
1220    let result = tokio::time::timeout(
1221        request_timeout,
1222        mz_ore::task::spawn(|| "mcp_request", async move {
1223            handle_mcp_request_inner(
1224                &mut client,
1225                request,
1226                protocol,
1227                endpoint_type,
1228                query_tool_enabled,
1229                read_data_product_tool_enabled,
1230                max_response_size,
1231                metrics_inner,
1232            )
1233            .await
1234        })
1235        .abort_on_drop(),
1236    )
1237    .await;
1238
1239    let (response, status_label): (McpResponse, McpCallStatus) = match result {
1240        Ok(inner) => inner,
1241        Err(_elapsed) => {
1242            warn!(
1243                endpoint = %endpoint_type,
1244                timeout = ?request_timeout,
1245                "MCP request timed out",
1246            );
1247            let response = McpResponse::error(
1248                request_id,
1249                McpRequestError::QueryExecutionFailed(format!(
1250                    "Request timed out after {} seconds.",
1251                    request_timeout.as_secs(),
1252                ))
1253                .into(),
1254            );
1255            (response, McpCallStatus::Timeout)
1256        }
1257    };
1258
1259    record_request(status_label);
1260    // 2026-07-28 answers a method it does not define with 404.
1261    let status = match &response.error {
1262        Some(error) if protocol.is_modern() && error.code == error_codes::METHOD_NOT_FOUND => {
1263            StatusCode::NOT_FOUND
1264        }
1265        _ => StatusCode::OK,
1266    };
1267    // Always a single JSON object. The transport lets the server answer with
1268    // JSON or an SSE stream, and we never stream, so `Accept` is not checked.
1269    (status, Json(response)).into_response()
1270}
1271
1272/// Answers a 2026-07-28 request whose body did not parse, in JSON-RPC. One that
1273/// passes [`check_modern_request`] gets 404 for a method 2026-07-28 does not
1274/// define, and `-32602` otherwise. Other rejections keep axum's response.
1275fn answer_parse_failure(
1276    rejection: JsonRejection,
1277    body: &[u8],
1278    headers: &McpHeaders,
1279    record_request: &dyn Fn(McpCallStatus),
1280) -> axum::response::Response {
1281    let raw = RawRequest::parse(body).unwrap_or_default();
1282    let (status, err) = match rejection {
1283        JsonRejection::JsonSyntaxError(rejection) => (
1284            StatusCode::BAD_REQUEST,
1285            McpRequestError::ParseError(rejection.body_text()),
1286        ),
1287        JsonRejection::JsonDataError(_)
1288            if raw.id.as_ref().is_some_and(|id| !is_valid_request_id(id)) =>
1289        {
1290            (StatusCode::BAD_REQUEST, invalid_id())
1291        }
1292        JsonRejection::JsonDataError(rejection) => {
1293            let message = rejection.body_text();
1294            match (raw.id.is_some(), check_modern_request(headers, &raw)) {
1295                (_, Err(err @ McpRequestError::InvalidRequest(_))) => {
1296                    (StatusCode::BAD_REQUEST, err)
1297                }
1298                // A notification has no reply, so one that cannot be accepted gets
1299                // a 400. Header rules do not apply to it.
1300                (false, _) => (
1301                    StatusCode::BAD_REQUEST,
1302                    McpRequestError::InvalidParams(message),
1303                ),
1304                (true, Err(err)) => (StatusCode::BAD_REQUEST, err),
1305                (true, Ok(())) if raw.method() == Some("initialize") => (
1306                    StatusCode::NOT_FOUND,
1307                    McpRequestError::MethodNotFound("unknown method".to_string()),
1308                ),
1309                (true, Ok(())) => (StatusCode::OK, McpRequestError::InvalidParams(message)),
1310            }
1311        }
1312        rejection => return rejection.into_response(),
1313    };
1314    record_request(McpCallStatus::Error(err.error_type()));
1315    let id = raw.id.filter(is_valid_request_id);
1316    (status, Json(McpResponse::error(id, err.into()))).into_response()
1317}
1318
1319async fn handle_mcp_request_inner(
1320    client: &mut AuthedClient,
1321    request: McpRequest,
1322    protocol: ProtocolVersion,
1323    endpoint_type: McpEndpointType,
1324    query_tool_enabled: bool,
1325    read_data_product_tool_enabled: bool,
1326    max_response_size: usize,
1327    metrics: McpMetrics,
1328) -> (McpResponse, McpCallStatus) {
1329    // Extract request ID (guaranteed to be Some since notifications are filtered earlier)
1330    let request_id = request.id.clone().unwrap_or(serde_json::Value::Null);
1331
1332    let result = handle_mcp_method(
1333        client,
1334        &request,
1335        protocol,
1336        endpoint_type,
1337        query_tool_enabled,
1338        read_data_product_tool_enabled,
1339        max_response_size,
1340        &metrics,
1341    )
1342    .await;
1343
1344    let status_label = call_status(&result);
1345
1346    let response = match result {
1347        Ok(result_value) => {
1348            McpResponse::success(request_id, result_value.into_body(protocol, endpoint_type))
1349        }
1350        Err(e) => {
1351            if !matches!(
1352                e,
1353                McpRequestError::MethodNotFound(_) | McpRequestError::InvalidJsonRpcVersion
1354            ) {
1355                warn!(error = %e, method = %request.method, "MCP method execution failed");
1356            }
1357            McpResponse::error(request_id, e.into())
1358        }
1359    };
1360
1361    (response, status_label)
1362}
1363
1364async fn handle_mcp_method(
1365    client: &mut AuthedClient,
1366    request: &McpRequest,
1367    protocol: ProtocolVersion,
1368    endpoint_type: McpEndpointType,
1369    query_tool_enabled: bool,
1370    read_data_product_tool_enabled: bool,
1371    max_response_size: usize,
1372    metrics: &McpMetrics,
1373) -> Result<McpResult, McpRequestError> {
1374    if request.jsonrpc != JSONRPC_VERSION {
1375        return Err(McpRequestError::InvalidJsonRpcVersion);
1376    }
1377
1378    match &request.method {
1379        // 2026-07-28 removed the handshake.
1380        McpMethod::Initialize(_) if !protocol.is_modern() => {
1381            debug!(endpoint = %endpoint_type, "Processing initialize");
1382            handle_initialize(
1383                endpoint_type,
1384                query_tool_enabled,
1385                read_data_product_tool_enabled,
1386            )
1387        }
1388        McpMethod::ToolsList(_) => {
1389            debug!(endpoint = %endpoint_type, "Processing tools/list");
1390            handle_tools_list(
1391                endpoint_type,
1392                query_tool_enabled,
1393                read_data_product_tool_enabled,
1394                max_response_size,
1395            )
1396        }
1397        McpMethod::ToolsCall(params) => {
1398            debug!(tool = params.route_name(endpoint_type), endpoint = %endpoint_type, "Processing tools/call");
1399            handle_tools_call(
1400                client,
1401                params,
1402                endpoint_type,
1403                query_tool_enabled,
1404                read_data_product_tool_enabled,
1405                max_response_size,
1406                metrics,
1407            )
1408            .await
1409        }
1410        // Dual-era clients probe with `server/discover` and fall back to
1411        // `initialize` when 2025-11-25 answers it with a not found error.
1412        McpMethod::ServerDiscover(_) if protocol.is_modern() => {
1413            debug!(endpoint = %endpoint_type, "Processing server/discover");
1414            handle_discover(
1415                endpoint_type,
1416                query_tool_enabled,
1417                read_data_product_tool_enabled,
1418            )
1419        }
1420        McpMethod::Initialize(_)
1421        | McpMethod::ServerDiscover(_)
1422        | McpMethod::Ping(_)
1423        | McpMethod::NotificationsInitialized(_)
1424        | McpMethod::Unknown => Err(McpRequestError::MethodNotFound(
1425            "unknown method".to_string(),
1426        )),
1427    }
1428}
1429
1430/// Instructions returned by `initialize` and `server/discover` for each
1431/// endpoint type.
1432/// These guide the AI agent on how to use the server correctly.
1433fn endpoint_instructions(
1434    endpoint_type: McpEndpointType,
1435    query_tool_enabled: bool,
1436    read_data_product_tool_enabled: bool,
1437) -> Option<String> {
1438    match endpoint_type {
1439        // `/api/mcp` serves its three tools whatever the agent and developer
1440        // tool flags say, so its text names all three.
1441        McpEndpointType::Unified => Some(UNIFIED_INSTRUCTIONS.to_string()),
1442        McpEndpointType::Agent => {
1443            // Only reference tools that are actually exposed by tools/list.
1444            // Both flags off is a valid config where the agent can only
1445            // discover products, not read them. Say so instead of pointing at
1446            // a hidden tool.
1447            let read_paragraph = match (read_data_product_tool_enabled, query_tool_enabled) {
1448                (true, _) => {
1449                    "`read_data_product` automatically routes the \
1450                     read to the cluster recorded in the data product catalog so indexes are used; \
1451                     you only need to set the `cluster` parameter if you intentionally want the \
1452                     read to run on a different cluster (e.g. one with larger or more replicas). \
1453                     A null `cluster` in discovery means your role lacks USAGE on the object's \
1454                     index/compute cluster; `read_data_product` without an override then reads on \
1455                     your session's default cluster (safe: only materialized views appear this way, \
1456                     and they serve from persist). "
1457                }
1458                (false, true) => {
1459                    "Use the `query` tool to read data products, passing the cluster from \
1460                     `get_data_product_details` so indexed reads hit the arrangement. If \
1461                     `get_data_product_details` returns a null `cluster`, your role lacks USAGE on \
1462                     the object's index/compute cluster; omit `cluster` from the `query` call so it \
1463                     runs on your session's default cluster, and if that fails, pass any cluster \
1464                     your role can use (the read works without the index arrangement). "
1465                }
1466                (false, false) => {
1467                    "This server is configured for discovery only: no read tool is exposed. \
1468                     Use `get_data_products` and `get_data_product_details` to inspect what \
1469                     is available. "
1470                }
1471            };
1472            Some(format!(
1473                "You have access to Materialize data products via MCP. \
1474                 Prefer indexed objects (served from memory) over unindexed materialized views \
1475                 (read from persistent storage). {read_paragraph}\
1476                 `get_data_product_details` returns a `hydration` object with `hydrated`, \
1477                 `replica_count`, and `hydrated_replica_count` fields. Reads never return \
1478                 partial data: a read against a not-yet-hydrated product blocks until the \
1479                 dataflow catches up, and may hit the request timeout. Check `hydrated` \
1480                 before reading: if it is false and `replica_count` is greater than 0, the \
1481                 dataflow is still warming up, so wait and retry; if `replica_count` is 0 the \
1482                 cluster has no replicas and the read cannot make progress until one is added.",
1483            ))
1484        }
1485        McpEndpointType::Developer => {
1486            // Only advertise the `query` tool when it is actually exposed:
1487            // otherwise the instructions would point agents at a tool that
1488            // tools/list does not list.
1489            let query_tool_line = if query_tool_enabled {
1490                "- query: read-only SELECT/SHOW/EXPLAIN that can also reach user objects on a named cluster. Use this for EXPLAIN ANALYZE and for inspecting user objects directly.\n"
1491            } else {
1492                ""
1493            };
1494            // Same reasoning for the introspection rule: only route to the
1495            // `query` tool when it is exposed, otherwise say that
1496            // cluster-targeted introspection is unavailable here.
1497            let introspection_rule = if query_tool_enabled {
1498                "- mz_introspection relations (for example mz_dataflow_arrangement_sizes) are cluster-scoped and query_system_catalog answers about the session's default cluster: read them only through the query tool with its cluster argument (and cluster_replica on a multi-replica cluster), never through query_system_catalog"
1499            } else {
1500                "- mz_introspection relations (for example mz_dataflow_arrangement_sizes) are cluster-scoped and query_system_catalog answers about the session's default cluster only; cluster-targeted introspection is unavailable on this server (the query tool is disabled), so say so rather than reporting another cluster's numbers"
1501            };
1502            Some(format!(
1503                "You are connected to the Materialize developer MCP server for troubleshooting and observability.\n\n\
1504                 Tools:\n\
1505                 - query_system_catalog: read-only SELECT/SHOW/EXPLAIN restricted to system catalog tables (mz_*, pg_catalog, information_schema). No cluster argument; prefer this for most catalog lookups.\n\
1506                 {query_tool_line}\n\
1507                 IMPORTANT: Before writing queries, discover table schemas using the mz_ontology tables:\n\
1508                 - mz_internal.mz_ontology_entity_types: what catalog entities exist and which tables they map to\n\
1509                 - mz_internal.mz_ontology_link_types: relationships between entities (foreign keys, metrics, etc.)\n\
1510                 - mz_internal.mz_ontology_properties: column names, types, and descriptions for each entity\n\
1511                 - mz_internal.mz_ontology_semantic_types: typed ID domains (CatalogItemId, ReplicaId, etc.)\n\n\
1512                 Use these to find the correct tables, join paths, and column names instead of guessing.\n\n\
1513                 Key rules:\n\
1514                 - mz_source_statuses and mz_sink_statuses use `last_status_change_at` (NOT `updated_at`)\n\
1515                 - mz_cluster_replica_utilization only has `replica_id` — JOIN with mz_cluster_replicas and mz_clusters to get names\n\
1516                 {introspection_rule}\n\
1517                 - mz_dataflow_arrangement_sizes.id and mz_dataflows.id are dataflow ids (uint8), not catalog ids: do not JOIN them to mz_catalog.mz_objects.id (text); join through mz_introspection.mz_compute_exports (dataflow_id to export_id) instead, or match the name column, which reads Dataflow: <database>.<schema>.<object>\n\
1518                 - Use SHOW COLUMNS FROM <table> to verify column names if unsure",
1519            ))
1520        }
1521    }
1522}
1523
1524const UNIFIED_INSTRUCTIONS: &str = "\
1525You are connected to the Materialize MCP server. It reads data products and the system catalog.
1526
1527Tools:
1528- list_data_products: the data products your role can read. Start here.
1529- get_data_product_details: one data product's columns, its cluster, and its `hydration`.
1530- query: read-only SELECT, SHOW, or EXPLAIN against anything your role can read, data products and system catalog alike.
1531
1532Reading data products:
1533- Pass the `cluster` from get_data_product_details to query, so indexed reads hit the arrangement. Prefer indexed objects (served from memory) over unindexed materialized views (read from persistent storage).
1534- A null `cluster` means your role lacks USAGE on that cluster. Omit `cluster`, and the query runs on your session's default cluster.
1535- Check `hydration` before reading. Reads never return partial data: a read of a product that is not hydrated blocks until the dataflow catches up, and may hit the request timeout. If `hydrated` is false and `replica_count` is greater than 0, wait and retry. If `replica_count` is 0, the cluster has no replicas and the read cannot make progress until one is added.
1536
1537System catalog:
1538- Write system object names with their schema, for example mz_internal.mz_source_statuses. query does not add the system schemas to the search path.
1539- Before writing catalog queries, find tables, columns, and join paths in mz_internal.mz_ontology_entity_types, mz_internal.mz_ontology_link_types, mz_internal.mz_ontology_properties, and mz_internal.mz_ontology_semantic_types.
1540- mz_introspection relations (for example mz_introspection.mz_dataflow_arrangement_sizes) are cluster-scoped: query them with `cluster` set, and `cluster_replica` on a cluster with more than one replica.
1541- mz_internal.mz_source_statuses and mz_internal.mz_sink_statuses use `last_status_change_at`, not `updated_at`.
1542- mz_internal.mz_cluster_replica_utilization only has `replica_id`: join mz_catalog.mz_cluster_replicas and mz_catalog.mz_clusters for names.
1543- mz_introspection.mz_dataflow_arrangement_sizes.id and mz_introspection.mz_dataflows.id are dataflow ids (uint8), not catalog ids: join through mz_introspection.mz_compute_exports (dataflow_id to export_id), or match the name column, which reads Dataflow: <database>.<schema>.<object>.";
1544
1545fn server_info(endpoint_type: McpEndpointType) -> ServerInfo {
1546    let name = match endpoint_type {
1547        McpEndpointType::Unified => "materialize-mcp".to_string(),
1548        other => format!("materialize-mcp-{other}"),
1549    };
1550    ServerInfo {
1551        name,
1552        version: env!("CARGO_PKG_VERSION").to_string(),
1553    }
1554}
1555
1556fn handle_initialize(
1557    endpoint_type: McpEndpointType,
1558    query_tool_enabled: bool,
1559    read_data_product_tool_enabled: bool,
1560) -> Result<McpResult, McpRequestError> {
1561    Ok(McpResult::Initialize(InitializeResult {
1562        protocol_version: MCP_PROTOCOL_VERSION.to_string(),
1563        capabilities: Capabilities { tools: json!({}) },
1564        server_info: server_info(endpoint_type),
1565        instructions: endpoint_instructions(
1566            endpoint_type,
1567            query_tool_enabled,
1568            read_data_product_tool_enabled,
1569        ),
1570    }))
1571}
1572
1573fn handle_discover(
1574    endpoint_type: McpEndpointType,
1575    query_tool_enabled: bool,
1576    read_data_product_tool_enabled: bool,
1577) -> Result<McpResult, McpRequestError> {
1578    Ok(McpResult::Discover(DiscoverResult {
1579        supported_versions: [
1580            ProtocolVersion::V2026_07_28.as_str(),
1581            ProtocolVersion::V2025_11_25.as_str(),
1582        ],
1583        capabilities: Capabilities { tools: json!({}) },
1584        instructions: endpoint_instructions(
1585            endpoint_type,
1586            query_tool_enabled,
1587            read_data_product_tool_enabled,
1588        ),
1589    }))
1590}
1591
1592const DATA_PRODUCTS_DESCRIPTION: &str = "Discover all available real-time data views (data products) that represent business entities like customers, orders, products, etc. Each data product provides fresh, queryable data with defined schemas. Use this first to see what data is available before querying specific information.";
1593
1594const DATA_PRODUCT_DETAILS_DESCRIPTION: &str = "Get the complete schema and structure of a specific data product, plus a `hydration` object reporting whether the dataflow is ready across the cluster's replicas (`{hydrated, replica_count, hydrated_replica_count}`). This shows you exactly what fields are available, their types, and what data you can query. Reads never return partial data, so check `hydration` before reading: if `hydrated` is false and `replica_count` is greater than 0 the dataflow is still warming up (a read would block until it catches up, possibly hitting the request timeout), so wait and retry; if `replica_count` is 0 the cluster has no replicas and the read cannot make progress until one is added.";
1595
1596fn handle_tools_list(
1597    endpoint_type: McpEndpointType,
1598    query_tool_enabled: bool,
1599    read_data_product_tool_enabled: bool,
1600    max_response_size: usize,
1601) -> Result<McpResult, McpRequestError> {
1602    let size_hint = format!(
1603        "Response limit: {:.1} MB.",
1604        f64::cast_lossy(max_response_size) / 1_000_000.0
1605    );
1606
1607    let tools = match endpoint_type {
1608        McpEndpointType::Agent => {
1609            let mut tools = vec![
1610                ToolDefinition {
1611                    name: "get_data_products".to_string(),
1612                    title: Some("List Data Products".to_string()),
1613                    description: DATA_PRODUCTS_DESCRIPTION.to_string(),
1614                    input_schema: json!({
1615                        "type": "object",
1616                        "properties": {},
1617                        "required": []
1618                    }),
1619                    annotations: Some(READ_ONLY_ANNOTATIONS),
1620                },
1621                ToolDefinition {
1622                    name: "get_data_product_details".to_string(),
1623                    title: Some("Get Data Product Details".to_string()),
1624                    description: DATA_PRODUCT_DETAILS_DESCRIPTION.to_string(),
1625                    input_schema: json!({
1626                        "type": "object",
1627                        "properties": {
1628                            "name": {
1629                                "type": "string",
1630                                "description": "Exact name of the data product from get_data_products() list"
1631                            }
1632                        },
1633                        "required": ["name"]
1634                    }),
1635                    annotations: Some(READ_ONLY_ANNOTATIONS),
1636                },
1637            ];
1638            if read_data_product_tool_enabled {
1639                tools.push(ToolDefinition {
1640                    name: "read_data_product".to_string(),
1641                    title: Some("Read Data Product".to_string()),
1642                    description: format!("Read rows from a specific data product. Returns up to `limit` rows (default {DEFAULT_READ_LIMIT}). The data product must exist in the catalog (use get_data_products() to discover available products). Use this to retrieve actual data from a known data product. {size_hint}"),
1643                    input_schema: json!({
1644                        "type": "object",
1645                        "properties": {
1646                            "name": {
1647                                "type": "string",
1648                                "description": "Exact fully-qualified name of the data product (e.g. '\"materialize\".\"schema\".\"view_name\"')"
1649                            },
1650                            "limit": {
1651                                "type": "integer",
1652                                "description": format!("Maximum number of rows to return (default {DEFAULT_READ_LIMIT})"),
1653                                "default": DEFAULT_READ_LIMIT
1654                            },
1655                            "cluster": {
1656                                "type": "string",
1657                                "description": "Optional override. By default, the read runs on the cluster recorded in the data product catalog (where the index or materialized view dataflow lives), so indexed reads actually hit their arrangement. A null `cluster` in discovery means your role lacks USAGE on the object's index/compute cluster; without an override, the read then runs on your session's default cluster (safe: only materialized views appear this way, and they serve from persist). Set this only to intentionally run the same read on a different cluster — e.g. one with more or larger replicas, or to compare cost/latency."
1658                            }
1659                        },
1660                        "required": ["name"]
1661                    }),
1662                    annotations: Some(READ_ONLY_ANNOTATIONS),
1663                });
1664            }
1665            if query_tool_enabled {
1666                tools.push(ToolDefinition {
1667                    name: "query".to_string(),
1668                    title: Some("Query Data Products".to_string()),
1669                    description: format!("Execute SQL queries against real-time data products to retrieve current business information. Use standard PostgreSQL syntax. You can JOIN multiple data products together, but ONLY if they are all hosted on the same cluster. Pass the cluster from the data product details so indexed reads hit the arrangement. If the data product's cluster is null, omit it. This provides fresh, up-to-date results from materialized views. {size_hint}"),
1670                    input_schema: json!({
1671                        "type": "object",
1672                        "properties": {
1673                            "cluster": {
1674                                "type": "string",
1675                                "description": "Exact cluster name from the data product details. Omit it when the data product's cluster is null, which means your role lacks USAGE on that cluster: the query then runs on your session's default cluster, without the index arrangement. If that fails, pass any cluster your role can use."
1676                            },
1677                            "sql_query": {
1678                                "type": "string",
1679                                "description": "PostgreSQL-compatible SELECT statement to retrieve data. Use the fully qualified data product name exactly as provided (with double quotes). You can JOIN multiple data products, but only those on the same cluster."
1680                            }
1681                        },
1682                        "required": ["sql_query"]
1683                    }),
1684                    annotations: Some(READ_ONLY_ANNOTATIONS),
1685                });
1686            }
1687            tools
1688        }
1689        McpEndpointType::Unified => vec![
1690            ToolDefinition {
1691                name: LIST_DATA_PRODUCTS.to_string(),
1692                title: Some("List Data Products".to_string()),
1693                description: DATA_PRODUCTS_DESCRIPTION.to_string(),
1694                input_schema: json!({
1695                    "type": "object",
1696                    "properties": {},
1697                    "required": []
1698                }),
1699                annotations: Some(READ_ONLY_ANNOTATIONS),
1700            },
1701            ToolDefinition {
1702                name: "get_data_product_details".to_string(),
1703                title: Some("Get Data Product Details".to_string()),
1704                description: DATA_PRODUCT_DETAILS_DESCRIPTION.to_string(),
1705                input_schema: json!({
1706                    "type": "object",
1707                    "properties": {
1708                        "name": {
1709                            "type": "string",
1710                            "description": "Exact name of the data product from list_data_products() list"
1711                        }
1712                    },
1713                    "required": ["name"]
1714                }),
1715                annotations: Some(READ_ONLY_ANNOTATIONS),
1716            },
1717            ToolDefinition {
1718                name: "query".to_string(),
1719                title: Some("Query".to_string()),
1720                description: format!(
1721                    "Execute a read-only SQL query (SELECT, SHOW, or EXPLAIN) against any object the role can access, including data products and the system catalog. Pass the cluster from the data product details so indexed reads hit the arrangement. Omit `cluster` to run on your session's default cluster, for example when the data product's cluster is null. Write system object names in full, such as `mz_catalog.mz_clusters`. {size_hint}",
1722                ),
1723                input_schema: json!({
1724                    "type": "object",
1725                    "properties": {
1726                        "cluster": {
1727                            "type": "string",
1728                            "description": "Exact cluster name the query should run on, such as the cluster from the data product details. Omit it to run on your session's default cluster. EXPLAIN ANALYZE needs a cluster."
1729                        },
1730                        "cluster_replica": {
1731                            "type": "string",
1732                            "description": "Optional replica name (e.g. 'r1') to target one replica of `cluster`. Requires `cluster`. Required for EXPLAIN ANALYZE on clusters with more than one replica. Find replica names in mz_catalog.mz_cluster_replicas."
1733                        },
1734                        "sql_query": {
1735                            "type": "string",
1736                            "description": "PostgreSQL-compatible SELECT, SHOW, or EXPLAIN statement. Use the fully qualified data product name exactly as provided (with double quotes). Multi-statement queries are rejected."
1737                        }
1738                    },
1739                    "required": ["sql_query"]
1740                }),
1741                annotations: Some(READ_ONLY_ANNOTATIONS),
1742            },
1743        ],
1744        McpEndpointType::Developer => {
1745            let mut tools = vec![ToolDefinition {
1746                name: "query_system_catalog".to_string(),
1747                title: Some("Query System Catalog".to_string()),
1748                description: concat!(
1749                    "Query Materialize system catalog tables for troubleshooting and observability. ",
1750                    "Only mz_*, pg_catalog, and information_schema tables are accessible. ",
1751                    "Use the mz_internal.mz_ontology_* tables to discover tables, columns, and join paths before writing queries.",
1752                ).to_owned() + &format!(" {size_hint}"),
1753                input_schema: json!({
1754                    "type": "object",
1755                    "properties": {
1756                        "sql_query": {
1757                            "type": "string",
1758                            "description": "PostgreSQL-compatible SELECT, SHOW, or EXPLAIN query referencing mz_*, pg_catalog, or information_schema tables"
1759                        }
1760                    },
1761                    "required": ["sql_query"]
1762                }),
1763                annotations: Some(READ_ONLY_ANNOTATIONS),
1764            }];
1765            if query_tool_enabled {
1766                tools.push(ToolDefinition {
1767                    name: "query".to_string(),
1768                    title: Some("Query".to_string()),
1769                    description: format!(
1770                        "Execute a read-only SQL query (SELECT, SHOW, or EXPLAIN) against any object the role can access, including system catalog and user objects. Requires a cluster, which is what enables EXPLAIN ANALYZE and queries against indexed user objects. For pure system catalog lookups that do not need a cluster, prefer `query_system_catalog`. {size_hint}",
1771                    ),
1772                    input_schema: json!({
1773                        "type": "object",
1774                        "properties": {
1775                            "cluster": {
1776                                "type": "string",
1777                                "description": "Exact cluster name the query should run on. Required: EXPLAIN ANALYZE and queries against indexed user objects need a specific cluster to execute on."
1778                            },
1779                            "cluster_replica": {
1780                                "type": "string",
1781                                "description": "Optional replica name (e.g. 'r1') to target one replica of the cluster. Required for EXPLAIN ANALYZE on clusters with more than one replica. Find replica names in mz_catalog.mz_cluster_replicas."
1782                            },
1783                            "sql_query": {
1784                                "type": "string",
1785                                "description": "PostgreSQL-compatible SELECT, SHOW, or EXPLAIN statement. Multi-statement queries are rejected."
1786                            }
1787                        },
1788                        "required": ["cluster", "sql_query"]
1789                    }),
1790                    annotations: Some(READ_ONLY_ANNOTATIONS),
1791                });
1792            }
1793            tools
1794        }
1795    };
1796
1797    Ok(McpResult::ToolsList(ToolsListResult { tools }))
1798}
1799
1800async fn handle_tools_call(
1801    client: &mut AuthedClient,
1802    params: &ToolsCallParams,
1803    endpoint_type: McpEndpointType,
1804    query_tool_enabled: bool,
1805    read_data_product_tool_enabled: bool,
1806    max_response_size: usize,
1807    metrics: &McpMetrics,
1808) -> Result<McpResult, McpRequestError> {
1809    // Drop-recording so metrics survive task cancellation.
1810    let tool_name = params.route_name(endpoint_type);
1811    let mut guard = ToolCallGuard::new(metrics, endpoint_type.as_label(), tool_name.to_string());
1812
1813    let result = match (endpoint_type, params) {
1814        (
1815            McpEndpointType::Agent | McpEndpointType::Unified,
1816            ToolsCallParams::GetDataProducts(_),
1817        ) => get_data_products(client, max_response_size).await,
1818        (
1819            McpEndpointType::Agent | McpEndpointType::Unified,
1820            ToolsCallParams::GetDataProductDetails(p),
1821        ) => get_data_product_details(client, &p.name, max_response_size).await,
1822        (McpEndpointType::Agent, ToolsCallParams::ReadDataProduct(_))
1823            if !read_data_product_tool_enabled =>
1824        {
1825            Err(McpRequestError::ToolNotFound(
1826                "read_data_product tool is not available. Use the query tool to read data products."
1827                    .to_string(),
1828            ))
1829        }
1830        (McpEndpointType::Agent, ToolsCallParams::ReadDataProduct(p)) => {
1831            read_data_product(
1832                client,
1833                &p.name,
1834                p.limit,
1835                p.cluster.as_deref(),
1836                max_response_size,
1837            )
1838            .await
1839        }
1840        (McpEndpointType::Agent, ToolsCallParams::Query(_)) if !query_tool_enabled => {
1841            Err(McpRequestError::ToolNotFound(
1842                "query tool is not available. Use get_data_products, get_data_product_details, and read_data_product instead.".to_string(),
1843            ))
1844        }
1845        (McpEndpointType::Agent, ToolsCallParams::Query(p)) => {
1846            execute_query(
1847                client,
1848                Placement::cluster_or_default(p.cluster.as_deref()),
1849                &p.sql_query,
1850                max_response_size,
1851            )
1852            .await
1853        }
1854        (McpEndpointType::Developer, ToolsCallParams::QuerySystemCatalog(p)) => {
1855            query_system_catalog(client, &p.sql_query, max_response_size).await
1856        }
1857        (McpEndpointType::Developer, ToolsCallParams::Query(_)) if !query_tool_enabled => {
1858            Err(McpRequestError::ToolNotFound(
1859                "query tool is not available. Use query_system_catalog instead.".to_string(),
1860            ))
1861        }
1862        // NOTE: a `?` here would skip `guard.set_status` below and record the
1863        // call as cancelled.
1864        (McpEndpointType::Developer, ToolsCallParams::Query(p)) => match p.developer_placement() {
1865            Ok(placement) => {
1866                execute_query(client, placement, &p.sql_query, max_response_size).await
1867            }
1868            Err(e) => Err(e),
1869        },
1870        (McpEndpointType::Unified, ToolsCallParams::Query(p)) => match p.unified_placement() {
1871            Ok(placement) => {
1872                execute_query(client, placement, &p.sql_query, max_response_size).await
1873            }
1874            Err(e) => Err(e),
1875        },
1876        // Tool called on wrong endpoint
1877        (_, _) => Err(McpRequestError::ToolNotFound(format!(
1878            "{tool_name} is not available on {endpoint_type} endpoint"
1879        ))),
1880    };
1881
1882    guard.set_status(call_status(&result));
1883
1884    result
1885}
1886
1887/// Maps a handler result to its metric [`McpCallStatus`]. Errors carry the
1888/// closed `error_type()` label; anything else is `Ok`.
1889fn call_status<T>(result: &Result<T, McpRequestError>) -> McpCallStatus {
1890    match result {
1891        Ok(_) => McpCallStatus::Ok,
1892        Err(e) => McpCallStatus::Error(e.error_type()),
1893    }
1894}
1895
1896/// Execute SQL via `execute_request` from sql.rs.
1897async fn execute_sql(
1898    client: &mut AuthedClient,
1899    query: &str,
1900) -> Result<Vec<Box<serde_json::value::RawValue>>, McpRequestError> {
1901    let mut response = SqlResponse::new();
1902
1903    execute_request(
1904        client,
1905        SqlRequest::Simple {
1906            query: mz_ore::sql::Sql::trusted_external_request(query.to_string()),
1907        },
1908        &mut response,
1909    )
1910    .await
1911    .map_err(|e| McpRequestError::QueryExecutionFailed(e.to_string()))?;
1912
1913    select_single_rows(response.results)
1914}
1915
1916/// Returns the rows of the single row-returning statement in a response.
1917///
1918/// A read's framing statements (`BEGIN`, `SET`, `COMMIT`) report `Ok`, so only
1919/// the user's statement returns rows. Surfaces the first error, and a second
1920/// row-returning statement is an error rather than a dropped result.
1921fn select_single_rows(
1922    results: Vec<SqlResult>,
1923) -> Result<Vec<Box<serde_json::value::RawValue>>, McpRequestError> {
1924    let mut rows = None;
1925    for result in results {
1926        match result {
1927            SqlResult::Rows { rows: r, .. } => {
1928                if rows.is_some() {
1929                    return Err(McpRequestError::Internal(anyhow!(
1930                        "MCP query returned multiple row-producing statements"
1931                    )));
1932                }
1933                rows = Some(r);
1934            }
1935            SqlResult::Err { error, .. } => {
1936                return Err(McpRequestError::QueryExecutionFailed(error.message));
1937            }
1938            SqlResult::Ok { .. } => continue,
1939        }
1940    }
1941
1942    rows.ok_or_else(|| {
1943        McpRequestError::QueryExecutionFailed("Query did not return any results".to_string())
1944    })
1945}
1946
1947/// Serialize rows to JSON and enforce the response size cap.
1948///
1949/// If the serialized response exceeds `max_size` bytes, returns an error
1950/// telling the agent to narrow its query, rather than truncating. The HTTP
1951/// SQL endpoint handles `max_result_size` the same way in sql.rs.
1952fn format_rows_response(
1953    rows: Vec<Box<serde_json::value::RawValue>>,
1954    max_size: usize,
1955) -> Result<McpResult, McpRequestError> {
1956    // Each row is already-serialized compact JSON. `RawValue` re-serializes
1957    // verbatim, so the outer array is pretty-printed while rows stay compact.
1958    let text =
1959        serde_json::to_string_pretty(&rows).map_err(|e| McpRequestError::Internal(anyhow!(e)))?;
1960
1961    if text.len() > max_size {
1962        return Err(McpRequestError::QueryExecutionFailed(format!(
1963            "Response size ({} bytes) exceeds the {} byte limit. \
1964             Use LIMIT or WHERE to narrow your query.",
1965            text.len(),
1966            max_size,
1967        )));
1968    }
1969
1970    Ok(McpResult::ToolContent(ToolContentResult {
1971        content: vec![ContentBlock {
1972            content_type: "text".to_string(),
1973            text,
1974        }],
1975        is_error: false,
1976    }))
1977}
1978
1979async fn get_data_products(
1980    client: &mut AuthedClient,
1981    max_response_size: usize,
1982) -> Result<McpResult, McpRequestError> {
1983    debug!("Executing get_data_products");
1984    let rows = execute_sql(client, DISCOVERY_QUERY).await?;
1985    debug!("get_data_products returned {} rows", rows.len());
1986
1987    format_rows_response(rows, max_response_size)
1988}
1989
1990async fn get_data_product_details(
1991    client: &mut AuthedClient,
1992    name: &str,
1993    max_response_size: usize,
1994) -> Result<McpResult, McpRequestError> {
1995    debug!(name = %name, "Executing get_data_product_details");
1996
1997    let query = format!("{}{}", DETAILS_QUERY_PREFIX, escaped_string_literal(name));
1998
1999    let rows = execute_sql(client, &query).await?;
2000
2001    if rows.is_empty() {
2002        return Err(McpRequestError::DataProductNotFound(name.to_string()));
2003    }
2004
2005    format_rows_response(rows, max_response_size)
2006}
2007
2008/// Parses a data product name and returns it safely quoted for SQL interpolation.
2009///
2010/// Uses the SQL parser to validate the name as an `UnresolvedItemName`, then
2011/// formats it with `FormatMode::Stable` so every identifier part is
2012/// double-quoted with proper escaping. This prevents SQL injection regardless
2013/// of the input.
2014fn safe_data_product_name(name: &str) -> Result<String, McpRequestError> {
2015    let name = name.trim();
2016    if name.is_empty() {
2017        return Err(McpRequestError::QueryValidationFailed(
2018            "Data product name cannot be empty".to_string(),
2019        ));
2020    }
2021
2022    // `parse_item_name_with_limit` enforces the 1 MB guard on the raw input
2023    // (DEX-64) before lexing.
2024    let parsed = parse_item_name_with_limit(name)
2025        .map_err(McpRequestError::QueryValidationFailed)?
2026        .map_err(|_| {
2027            McpRequestError::QueryValidationFailed(format!(
2028                "Invalid data product name: {}. Expected a valid object name, \
2029                 e.g. '\"database\".\"schema\".\"name\"' or 'my_view'",
2030                name
2031            ))
2032        })?;
2033
2034    // Stable formatting forces all identifiers to be double-quoted,
2035    // so SQL keywords and special characters cannot escape.
2036    Ok(parsed.to_ast_string_stable())
2037}
2038
2039/// Read rows from a data product. Issues a single read-only query.
2040///
2041/// The read routes to the cluster recorded in `mz_mcp_data_products.cluster`
2042/// when the role has USAGE on it, so reads of indexed objects hit the index's
2043/// in-memory arrangement. That column is null when the role lacks USAGE on the
2044/// object's cluster (DEX-66); in that case, and absent an override, the read
2045/// runs on the session's default (serving) cluster instead. Only materialized
2046/// views can appear this way, since plain views without at least one usable
2047/// index cluster are excluded from `mz_mcp_data_products` entirely; the
2048/// fallback is therefore safe (materialized views serve from persist without
2049/// recompute).
2050///
2051/// `cluster_override` forces the read onto a named cluster instead, for example
2052/// one with more or larger replicas.
2053///
2054/// The name is expected to come from `get_data_products()` /
2055/// `get_data_product_details()`. The query runs inside a READ ONLY
2056/// transaction, preventing mutations.
2057async fn read_data_product(
2058    client: &mut AuthedClient,
2059    name: &str,
2060    limit: u32,
2061    cluster_override: Option<&str>,
2062    max_response_size: usize,
2063) -> Result<McpResult, McpRequestError> {
2064    debug!(name = %name, limit = limit, cluster_override = ?cluster_override, "Executing read_data_product");
2065
2066    // Parse and safely quote the name for SQL interpolation.
2067    let safe_name = safe_data_product_name(name)?;
2068
2069    // Existence check and cluster routing. `mz_mcp_data_products.cluster` is
2070    // non-null only when the role has USAGE on that cluster, so any value here
2071    // is safe to route to. `NULLS LAST` prefers such a usable cluster when an
2072    // object appears both with a usable cluster and as null (an object indexed
2073    // on several clusters, some of which the role cannot use).
2074    let lookup_query = format!(
2075        "SELECT dp.cluster FROM mz_internal.mz_mcp_data_products dp \
2076         WHERE dp.object_name = {} \
2077         ORDER BY dp.cluster NULLS LAST \
2078         LIMIT 1",
2079        escaped_string_literal(name)
2080    );
2081    let lookup_rows = execute_sql(client, &lookup_query).await?;
2082    if lookup_rows.is_empty() {
2083        return Err(McpRequestError::DataProductNotFound(name.to_string()));
2084    }
2085    // Rows are stored as pre-serialized JSON arrays, so parse the single-cell
2086    // lookup row to read `dp.cluster`.
2087    let catalog_cluster: Option<String> = lookup_rows
2088        .first()
2089        .and_then(|row| serde_json::from_str::<Vec<serde_json::Value>>(row.get()).ok())
2090        .and_then(|row| row.into_iter().next())
2091        .and_then(|v| v.as_str().map(|s| s.to_string()));
2092
2093    // An override wins. Otherwise use the catalog cluster when the role can use
2094    // it (non-null), else the session's default cluster. The doc comment says
2095    // why that fallback is safe.
2096    let target_cluster: Option<&str> = cluster_override.or(catalog_cluster.as_deref());
2097
2098    // The caller's `limit` is not clamped. The response is bounded by the size
2099    // cap in format_rows_response (MCP_MAX_RESPONSE_SIZE), and by
2100    // max_result_size at the adapter layer.
2101    let read_query = build_read_query(
2102        &safe_name,
2103        limit,
2104        Placement::cluster_or_default(target_cluster),
2105    );
2106
2107    let rows = execute_sql(client, &read_query).await?;
2108
2109    format_rows_response(rows, max_response_size)
2110}
2111
2112/// Builds the SQL the agent runs for `read_data_product`.
2113///
2114/// `safe_name` must already be the validated, quoted form produced by
2115/// [`safe_data_product_name`].
2116fn build_read_query(safe_name: &str, limit: u32, placement: Placement<'_>) -> String {
2117    let body = format!("SELECT * FROM {safe_name} LIMIT {limit}");
2118    read_only_txn(placement.set_clause().as_deref(), &body)
2119}
2120
2121/// Wraps `body` in a `BEGIN READ ONLY; <set_clause>; <body>; COMMIT;` frame so
2122/// `set_clause` is scoped to this read and does not leak into the session.
2123/// Without a `set_clause` the read runs on the session's default cluster.
2124///
2125/// NOTE: the newline before `; COMMIT;` stops a trailing `--` comment in `body`
2126/// from swallowing the `COMMIT`.
2127fn read_only_txn(set_clause: Option<&str>, body: &str) -> String {
2128    match set_clause {
2129        Some(set_clause) => format!("BEGIN READ ONLY; {set_clause}; {body}\n; COMMIT;"),
2130        None => format!("BEGIN READ ONLY; {body}\n; COMMIT;"),
2131    }
2132}
2133
2134/// Validates query is a single SELECT, SHOW, or EXPLAIN statement.
2135fn validate_readonly_query(sql: &str) -> Result<(), McpRequestError> {
2136    let sql = sql.trim();
2137    if sql.is_empty() {
2138        return Err(McpRequestError::QueryValidationFailed(
2139            "Empty query".to_string(),
2140        ));
2141    }
2142
2143    // Parse the SQL to get AST. `parse_with_limit` rejects inputs larger
2144    // than `MAX_STATEMENT_BATCH_SIZE` before lexing so the MCP endpoint
2145    // enforces the same 1 MB guard as the SQL HTTP path (DEX-64).
2146    let stmts = parse_with_limit(sql)
2147        .map_err(McpRequestError::QueryValidationFailed)?
2148        .map_err(|e| {
2149            McpRequestError::QueryValidationFailed(format!("Failed to parse SQL: {}", e))
2150        })?;
2151
2152    if stmts.len() != 1 {
2153        return Err(McpRequestError::QueryValidationFailed(format!(
2154            "Only one query allowed at a time. Found {} statements.",
2155            stmts.len()
2156        )));
2157    }
2158
2159    // Allowlist: SELECT, SHOW, and every read-only EXPLAIN variant. EXPLAIN
2160    // expands to six distinct Statement variants in the parser (ExplainPlan
2161    // covers only the most common one). Listing them out exhaustively beats
2162    // matching by string prefix, so a new write-capable EXPLAIN variant would
2163    // have to be considered here.
2164    let stmt = &stmts[0];
2165    use mz_sql_parser::ast::Statement;
2166
2167    match &stmt.ast {
2168        Statement::Select(_)
2169        | Statement::Show(_)
2170        | Statement::ExplainPlan(_)
2171        | Statement::ExplainPushdown(_)
2172        | Statement::ExplainTimestamp(_)
2173        | Statement::ExplainSinkSchema(_)
2174        | Statement::ExplainAnalyzeObject(_)
2175        | Statement::ExplainAnalyzeCluster(_) => {}
2176        _ => {
2177            return Err(McpRequestError::QueryValidationFailed(
2178                "Only SELECT, SHOW, and EXPLAIN statements are allowed".to_string(),
2179            ));
2180        }
2181    }
2182
2183    // A SELECT of a side-effecting function such as `pg_cancel_backend` plans
2184    // to `Plan::SideEffectingFunc`, which `BEGIN READ ONLY` does not block.
2185    let mut finder = SideEffectingCallFinder::default();
2186    finder.visit_statement(&stmt.ast);
2187    if !finder.rejected.is_empty() {
2188        return Err(McpRequestError::QueryValidationFailed(format!(
2189            "Query calls functions with side effects or by ID: {}. Only read-only queries are allowed.",
2190            finder.rejected.join(", ")
2191        )));
2192    }
2193    Ok(())
2194}
2195
2196/// Collects calls to side-effecting functions, and calls that name a function
2197/// by ID.
2198///
2199/// NOTE: Materialize has no user-defined functions, so a function name always
2200/// refers to a builtin and its last part identifies it. Revisit this check if
2201/// `CREATE FUNCTION` is ever added.
2202#[derive(Default)]
2203struct SideEffectingCallFinder {
2204    rejected: Vec<String>,
2205}
2206
2207impl<'ast> Visit<'ast, Raw> for SideEffectingCallFinder {
2208    fn visit_function(&mut self, function: &'ast Function<Raw>) {
2209        let rejected = match &function.name {
2210            // The name in `[<id> AS <name>]` need not be the function's name.
2211            RawItemName::Id(..) => true,
2212            RawItemName::Name(name) => name
2213                .0
2214                .last()
2215                .is_some_and(|ident| is_side_effecting_func_name(ident.as_str())),
2216        };
2217        if rejected {
2218            self.rejected.push(function.name.to_ast_string_simple());
2219        }
2220        visit::visit_function(self, function);
2221    }
2222}
2223
2224async fn execute_query(
2225    client: &mut AuthedClient,
2226    placement: Placement<'_>,
2227    sql_query: &str,
2228    max_response_size: usize,
2229) -> Result<McpResult, McpRequestError> {
2230    debug!(?placement, "Executing user query");
2231
2232    validate_readonly_query(sql_query)?;
2233    placement.validate()?;
2234
2235    // READ ONLY prevents mutations, and the SET clause scopes any placement to
2236    // this read.
2237    let combined_query = read_only_txn(placement.set_clause().as_deref(), sql_query);
2238
2239    let rows = execute_sql(client, &combined_query).await?;
2240
2241    format_rows_response(rows, max_response_size)
2242}
2243
2244/// The `search_path` of `query_system_catalog`, and the schemas an unqualified
2245/// name binds to, in order. No database-local schema can take these names,
2246/// since user schema names cannot start with `mz_` or `pg_`
2247/// (`is_reserved_name`).
2248const SYSTEM_CATALOG_SEARCH_PATH: [&str; 3] = [
2249    namespaces::MZ_CATALOG_SCHEMA,
2250    namespaces::MZ_INTERNAL_SCHEMA,
2251    namespaces::PG_CATALOG_SCHEMA,
2252];
2253
2254async fn query_system_catalog(
2255    client: &mut AuthedClient,
2256    sql_query: &str,
2257    max_response_size: usize,
2258) -> Result<McpResult, McpRequestError> {
2259    debug!("Executing query_system_catalog");
2260
2261    validate_readonly_query(sql_query)?;
2262
2263    let catalog = client
2264        .client
2265        .catalog_snapshot("mcp_query_system_catalog")
2266        .await;
2267    let conn_id = client.client.session().conn_id().clone();
2268    let bound_query = bind_system_catalog_query(sql_query, |schema, item| {
2269        catalog
2270            .resolve_schema_in_database(&ResolvedDatabaseSpecifier::Ambient, schema, &conn_id)
2271            .ok()?
2272            .items
2273            .get(item)
2274            .filter(|id| id.is_system())
2275            .map(|id| id.to_string())
2276    })?;
2277
2278    // An unqualified name matching a CTE stays unbound and resolves at
2279    // execution: first in the session's temporary schema, which is empty
2280    // because each request opens a new session, then through this search_path.
2281    let set_search_path = format!(
2282        "SET search_path = {}",
2283        SYSTEM_CATALOG_SEARCH_PATH.join(", ")
2284    );
2285    let combined_query = read_only_txn(Some(&set_search_path), &bound_query);
2286
2287    let rows = execute_sql(client, &combined_query).await?;
2288
2289    format_rows_response(rows, max_response_size)
2290}
2291
2292/// Rewrites each object name in the query to its system catalog ID, as
2293/// `[<id> AS <name>]`, and rejects the query if one is not a system object,
2294/// if a schema name is not a system schema, or if a SELECT reads no relation.
2295/// This covers the names SHOW and EXPLAIN take, not only the relations a
2296/// query reads. Function, type and cluster names stay as written.
2297///
2298/// Names match by exact spelling, in the system schemas (`SYSTEM_SCHEMAS`
2299/// without `mz_unsafe`). An unqualified name binds through
2300/// [`SYSTEM_CATALOG_SEARCH_PATH`], except one matching a CTE, which stays
2301/// unbound.
2302///
2303/// `sql` must hold exactly one statement, which `validate_readonly_query`
2304/// checks. `resolve(schema, item)` returns the ID of the system object `item`
2305/// in `schema`.
2306fn bind_system_catalog_query(
2307    sql: &str,
2308    resolve: impl Fn(&str, &str) -> Option<String>,
2309) -> Result<String, McpRequestError> {
2310    // `parse_with_limit` enforces the 1 MB guard shared with the SQL HTTP path
2311    // (DEX-64).
2312    let mut stmts = parse_with_limit(sql)
2313        .map_err(McpRequestError::QueryValidationFailed)?
2314        .map_err(|e| {
2315            McpRequestError::QueryValidationFailed(format!("Failed to parse SQL: {}", e))
2316        })?;
2317    let stmt = &mut stmts[0].ast;
2318
2319    // The binder does not visit type names, so a user type would pass. The
2320    // planner refuses this statement for system types.
2321    if matches!(stmt, Statement::Show(ShowStatement::ShowCreateType(_))) {
2322        return Err(McpRequestError::QueryValidationFailed(
2323            "SHOW CREATE TYPE is not supported: system types have no definition to show."
2324                .to_string(),
2325        ));
2326    }
2327
2328    let mut binder = SystemRelationBinder {
2329        resolve: &resolve,
2330        cte_names: BTreeSet::new(),
2331        id_references: Vec::new(),
2332        rejected: Vec::new(),
2333        unknown: Vec::new(),
2334        bound: 0,
2335    };
2336    binder.visit_statement_mut(stmt);
2337
2338    if !binder.id_references.is_empty() {
2339        return Err(McpRequestError::QueryValidationFailed(format!(
2340            "Query references objects by ID: {}. Reference system catalog objects by name.",
2341            binder.id_references.join(", ")
2342        )));
2343    }
2344    if !binder.rejected.is_empty() {
2345        return Err(McpRequestError::QueryValidationFailed(format!(
2346            "Query references non-system objects: {}. Only system catalog objects (mz_*, pg_catalog, information_schema) are allowed.",
2347            binder.rejected.join(", ")
2348        )));
2349    }
2350    if !binder.unknown.is_empty() {
2351        return Err(McpRequestError::QueryValidationFailed(format!(
2352            "Query references unknown system catalog objects: {}. Check the name and its schema.",
2353            binder.unknown.join(", ")
2354        )));
2355    }
2356    if matches!(stmt, Statement::Select(_)) && binder.bound == 0 {
2357        return Err(McpRequestError::QueryValidationFailed(
2358            "Query must reference at least one system catalog table".to_string(),
2359        ));
2360    }
2361
2362    Ok(stmt.to_ast_string_stable())
2363}
2364
2365struct SystemRelationBinder<'a, F> {
2366    resolve: &'a F,
2367    cte_names: BTreeSet<String>,
2368    /// Names the caller wrote as `[<id> AS <name>]`, which resolve by ID.
2369    id_references: Vec<String>,
2370    /// Names outside the system schemas.
2371    rejected: Vec<String>,
2372    /// Names in a system schema, or with its `mz_`/`pg_` prefix, that match no
2373    /// system relation.
2374    unknown: Vec<String>,
2375    bound: usize,
2376}
2377
2378impl<F: Fn(&str, &str) -> Option<String>> SystemRelationBinder<'_, F> {
2379    fn bind(&mut self, name: &mut RawItemName) {
2380        let RawItemName::Name(unresolved) = name else {
2381            return;
2382        };
2383        let parts: Vec<&str> = unresolved.0.iter().map(|ident| ident.as_str()).collect();
2384        let (item, schemas): (&str, &[&str]) = match parts.as_slice() {
2385            [item] if self.cte_names.contains(*item) => return,
2386            [item] => (item, &SYSTEM_CATALOG_SEARCH_PATH),
2387            // System schemas are in no database, so a database part does not
2388            // change what the name refers to.
2389            [schema, item] | [_, schema, item] if is_system_schema(schema) => {
2390                (item, std::slice::from_ref(schema))
2391            }
2392            _ => {
2393                self.rejected.push(unresolved.to_ast_string_simple());
2394                return;
2395            }
2396        };
2397        let Some((schema, id)) = schemas
2398            .iter()
2399            .find_map(|schema| Some((*schema, (self.resolve)(schema, item)?)))
2400        else {
2401            if parts.len() > 1 || item.starts_with("mz_") || item.starts_with("pg_") {
2402                self.unknown.push(unresolved.to_ast_string_simple());
2403            } else {
2404                self.rejected.push(unresolved.to_ast_string_simple());
2405            }
2406            return;
2407        };
2408        // The parser requires the name in `[<id> AS <name>]` to be qualified.
2409        let qualified = UnresolvedItemName::qualified(&[
2410            Ident::new_unchecked(schema),
2411            Ident::new_unchecked(item),
2412        ]);
2413        *name = RawItemName::Id(id, qualified, None);
2414        self.bound += 1;
2415    }
2416}
2417
2418impl<'ast, F: Fn(&str, &str) -> Option<String>> VisitMut<'ast, Raw>
2419    for SystemRelationBinder<'_, F>
2420{
2421    fn visit_cte_block_mut(&mut self, block: &'ast mut CteBlock<Raw>) {
2422        // Bindings are registered before any body is visited, because a
2423        // WITH MUTUALLY RECURSIVE body can reference any binding in its block.
2424        self.cte_names.extend(
2425            block
2426                .bound_identifiers()
2427                .map(|ident| ident.as_str().to_owned()),
2428        );
2429        visit_mut::visit_cte_block_mut(self, block);
2430    }
2431
2432    fn visit_item_name_mut(&mut self, name: &'ast mut RawItemName) {
2433        match name {
2434            RawItemName::Id(..) => self.id_references.push(name.to_ast_string_simple()),
2435            RawItemName::Name(_) => self.bind(name),
2436        }
2437    }
2438
2439    // Function names resolve among functions, not relations, so they stay
2440    // unbound. The exhaustive pattern makes a new `Function` field a compile error.
2441    fn visit_function_mut(&mut self, function: &'ast mut Function<Raw>) {
2442        let Function {
2443            name,
2444            args,
2445            filter,
2446            over,
2447            distinct: _,
2448        } = function;
2449        if let RawItemName::Id(..) = name {
2450            self.id_references.push(name.to_ast_string_simple());
2451        }
2452        self.visit_function_args_mut(args);
2453        if let Some(filter) = filter {
2454            self.visit_expr_mut(filter);
2455        }
2456        if let Some(over) = over {
2457            self.visit_window_spec_mut(over);
2458        }
2459    }
2460
2461    // A user can create a schema named `information_schema`, which has no
2462    // reserved prefix, and it wins over the system one in name resolution
2463    // (`CatalogState::resolve_schema`). Item names in it bind by ID, but a
2464    // schema name has no ID form, so it is rejected here.
2465    fn visit_schema_name_mut(&mut self, name: &'ast mut UnresolvedSchemaName) {
2466        let parts: Vec<&str> = name.0.iter().map(|ident| ident.as_str()).collect();
2467        let allowed = matches!(
2468            parts.as_slice(),
2469            [schema] | [_, schema]
2470                if is_system_schema(schema) && *schema != namespaces::INFORMATION_SCHEMA
2471        );
2472        if !allowed {
2473            self.rejected.push(name.to_ast_string_simple());
2474        }
2475    }
2476}
2477
2478fn is_system_schema(schema: &str) -> bool {
2479    SYSTEM_SCHEMAS.contains(&schema) && schema != namespaces::MZ_UNSAFE_SCHEMA
2480}
2481
2482#[cfg(test)]
2483mod tests {
2484    use super::*;
2485    use crate::http::sql::{Description, SqlError};
2486
2487    /// Binds against a stand-in catalog where every system relation has ID
2488    /// `s1`: `mz_`-prefixed names other than `mz_missing` in the `mz_` schemas,
2489    /// `pg_`-prefixed names in `pg_catalog`, and `tables` and `columns` in
2490    /// `information_schema`.
2491    fn bind_with_stub_catalog(sql: &str) -> Result<String, McpRequestError> {
2492        bind_system_catalog_query(sql, |schema, item| {
2493            let exists = match schema {
2494                namespaces::PG_CATALOG_SCHEMA => item.starts_with("pg_"),
2495                namespaces::INFORMATION_SCHEMA => matches!(item, "tables" | "columns"),
2496                _ => schema.starts_with("mz_") && item.starts_with("mz_") && item != "mz_missing",
2497            };
2498            exists.then(|| "s1".to_string())
2499        })
2500    }
2501
2502    /// Serializes each row to a compact JSON array, matching how the HTTP SQL
2503    /// layer stores rows.
2504    fn raw_rows(rows: Vec<Vec<serde_json::Value>>) -> Vec<Box<serde_json::value::RawValue>> {
2505        rows.iter()
2506            .map(|r| serde_json::value::to_raw_value(r).unwrap())
2507            .collect()
2508    }
2509
2510    fn rows_result(rows: Vec<Vec<serde_json::Value>>) -> SqlResult {
2511        SqlResult::Rows {
2512            tag: String::new(),
2513            rows: raw_rows(rows),
2514            desc: Description { columns: vec![] },
2515            notices: vec![],
2516        }
2517    }
2518
2519    fn ok_result() -> SqlResult {
2520        SqlResult::Ok {
2521            ok: String::new(),
2522            notices: vec![],
2523            parameters: vec![],
2524            execution_time: None,
2525        }
2526    }
2527
2528    fn err_result(message: &str) -> SqlResult {
2529        SqlResult::Err {
2530            error: SqlError {
2531                message: message.to_string(),
2532                code: String::new(),
2533                detail: None,
2534                hint: None,
2535                position: None,
2536            },
2537            notices: vec![],
2538        }
2539    }
2540
2541    /// The row-returning statement's rows are returned, ignoring the `Ok`
2542    /// framing statements around it.
2543    #[mz_ore::test]
2544    fn test_select_single_rows_extracts_rows() {
2545        let rows = vec![vec![serde_json::json!(1)]];
2546        let results = vec![
2547            ok_result(),
2548            ok_result(),
2549            rows_result(rows.clone()),
2550            ok_result(),
2551        ];
2552        let got = select_single_rows(results).unwrap();
2553        let got: Vec<&str> = got.iter().map(|r| r.get()).collect();
2554        assert_eq!(got, vec!["[1]"]);
2555    }
2556
2557    /// A response with no row-returning statement is an error.
2558    #[mz_ore::test]
2559    fn test_select_single_rows_requires_rows() {
2560        let err = select_single_rows(vec![ok_result(), ok_result()]).unwrap_err();
2561        assert!(
2562            matches!(err, McpRequestError::QueryExecutionFailed(_)),
2563            "{err:?}"
2564        );
2565    }
2566
2567    /// The invariant is enforced: a second row-returning statement is an
2568    /// internal error rather than a silently dropped result.
2569    #[mz_ore::test]
2570    fn test_select_single_rows_rejects_multiple() {
2571        let results = vec![rows_result(vec![]), rows_result(vec![])];
2572        let err = select_single_rows(results).unwrap_err();
2573        assert!(matches!(err, McpRequestError::Internal(_)), "{err:?}");
2574    }
2575
2576    /// A statement error is surfaced.
2577    #[mz_ore::test]
2578    fn test_select_single_rows_surfaces_error() {
2579        let err = select_single_rows(vec![ok_result(), err_result("boom")]).unwrap_err();
2580        match err {
2581            McpRequestError::QueryExecutionFailed(msg) => assert_eq!(msg, "boom"),
2582            other => panic!("unexpected error: {other:?}"),
2583        }
2584    }
2585
2586    /// The DNS-rebinding defense: a disallowed `Origin` is rejected with 403,
2587    /// an allowed one passes, and a missing one passes (non-browser clients).
2588    #[mz_ore::test]
2589    fn test_validate_origin() {
2590        let allowed = [HeaderValue::from_static("https://good.example")];
2591
2592        assert!(validate_origin(&HeaderMap::new(), &allowed).is_none());
2593
2594        let mut ok = HeaderMap::new();
2595        ok.insert(http::header::ORIGIN, allowed[0].clone());
2596        assert!(validate_origin(&ok, &allowed).is_none());
2597
2598        let mut bad = HeaderMap::new();
2599        bad.insert(
2600            http::header::ORIGIN,
2601            HeaderValue::from_static("https://evil.example"),
2602        );
2603        let rejected = validate_origin(&bad, &allowed);
2604        assert_eq!(
2605            rejected
2606                .expect("disallowed origin must be rejected")
2607                .status(),
2608            StatusCode::FORBIDDEN,
2609        );
2610    }
2611
2612    /// The two constructors set the JSON-RPC version and put the payload in
2613    /// the right one of the mutually-exclusive `result` / `error` fields.
2614    #[mz_ore::test]
2615    fn test_mcp_response_constructors() {
2616        let id = serde_json::json!(1);
2617
2618        let ok = McpResponse::success(
2619            id.clone(),
2620            McpResult::ToolContent(ToolContentResult {
2621                content: vec![],
2622                is_error: false,
2623            })
2624            .into_body(ProtocolVersion::V2025_11_25, McpEndpointType::Developer),
2625        );
2626        assert_eq!(ok.jsonrpc, JSONRPC_VERSION);
2627        assert!(ok.result.is_some());
2628        assert!(ok.error.is_none());
2629
2630        let err = McpResponse::error(id, McpRequestError::ToolNotFound("t".to_string()).into());
2631        assert_eq!(err.jsonrpc, JSONRPC_VERSION);
2632        assert!(err.result.is_none());
2633        assert!(err.error.is_some());
2634    }
2635
2636    #[mz_ore::test]
2637    fn test_validate_readonly_query_select() {
2638        assert!(validate_readonly_query("SELECT * FROM mz_tables").is_ok());
2639        assert!(validate_readonly_query("SELECT 1 + 2").is_ok());
2640        assert!(validate_readonly_query("  SELECT 1  ").is_ok());
2641    }
2642
2643    #[mz_ore::test]
2644    fn test_validate_readonly_query_subqueries() {
2645        // Simple subquery in WHERE clause
2646        assert!(
2647            validate_readonly_query(
2648                "SELECT * FROM mz_tables WHERE id IN (SELECT id FROM mz_columns)"
2649            )
2650            .is_ok()
2651        );
2652
2653        // Subquery in FROM clause
2654        assert!(
2655            validate_readonly_query(
2656                "SELECT * FROM (SELECT * FROM mz_tables WHERE name LIKE 'test%') AS t"
2657            )
2658            .is_ok()
2659        );
2660
2661        // Correlated subquery
2662        assert!(validate_readonly_query(
2663            "SELECT * FROM mz_tables t WHERE EXISTS (SELECT 1 FROM mz_columns c WHERE c.id = t.id)"
2664        )
2665        .is_ok());
2666
2667        // Nested subqueries
2668        assert!(validate_readonly_query(
2669            "SELECT * FROM mz_tables WHERE id IN (SELECT id FROM mz_columns WHERE type IN (SELECT name FROM mz_types))"
2670        )
2671        .is_ok());
2672
2673        // Subquery with aggregation
2674        assert!(
2675            validate_readonly_query(
2676                "SELECT * FROM mz_tables WHERE id = (SELECT MAX(id) FROM mz_columns)"
2677            )
2678            .is_ok()
2679        );
2680    }
2681
2682    #[mz_ore::test]
2683    fn test_validate_readonly_query_show() {
2684        assert!(validate_readonly_query("SHOW CLUSTERS").is_ok());
2685        assert!(validate_readonly_query("SHOW TABLES").is_ok());
2686    }
2687
2688    #[mz_ore::test]
2689    fn test_validate_readonly_query_explain() {
2690        // Every read-only EXPLAIN variant must be accepted. Each line
2691        // corresponds to a distinct Statement::Explain* arm of the parser; if
2692        // one of them is dropped from the validator the test that lost its
2693        // arm will fail, naming the variant.
2694        assert!(validate_readonly_query("EXPLAIN SELECT 1").is_ok());
2695        assert!(
2696            validate_readonly_query("EXPLAIN FILTER PUSHDOWN FOR SELECT * FROM mz_tables").is_ok()
2697        );
2698        assert!(validate_readonly_query("EXPLAIN TIMESTAMP FOR SELECT 1").is_ok());
2699        assert!(validate_readonly_query("EXPLAIN ANALYZE MEMORY FOR INDEX foo").is_ok());
2700        assert!(validate_readonly_query("EXPLAIN ANALYZE MEMORY FOR MATERIALIZED VIEW mv").is_ok());
2701        assert!(validate_readonly_query("EXPLAIN ANALYZE CLUSTER MEMORY").is_ok());
2702        assert!(
2703            validate_readonly_query(
2704                "EXPLAIN VALUE SCHEMA FOR CREATE SINK FROM t INTO KAFKA CONNECTION k \
2705                 (TOPIC 't') FORMAT AVRO USING CONFLUENT SCHEMA REGISTRY CONNECTION c"
2706            )
2707            .is_ok()
2708        );
2709    }
2710
2711    #[mz_ore::test]
2712    fn test_validate_readonly_query_rejects_writes() {
2713        assert!(validate_readonly_query("INSERT INTO t VALUES (1)").is_err());
2714        assert!(validate_readonly_query("UPDATE t SET a = 1").is_err());
2715        assert!(validate_readonly_query("DELETE FROM t").is_err());
2716        assert!(validate_readonly_query("CREATE TABLE t (a INT)").is_err());
2717        assert!(validate_readonly_query("DROP TABLE t").is_err());
2718    }
2719
2720    #[mz_ore::test]
2721    fn test_validate_readonly_query_rejects_side_effecting_functions() {
2722        for sql in [
2723            "SELECT pg_cancel_backend(1)",
2724            "SELECT pg_catalog.pg_cancel_backend(1)",
2725            "SELECT materialize.pg_catalog.pg_cancel_backend(1)",
2726            r#"SELECT "pg_cancel_backend"(1)"#,
2727            "SELECT [s1 AS pg_catalog.abs](1)",
2728            "SELECT * FROM mz_tables WHERE pg_cancel_backend(1)",
2729            "SELECT (SELECT pg_cancel_backend(1))",
2730            "EXPLAIN SELECT pg_cancel_backend(1)",
2731        ] {
2732            let err = validate_readonly_query(sql).expect_err(sql).to_string();
2733            assert!(err.contains("side effects"), "{sql}: {err}");
2734        }
2735        assert!(validate_readonly_query("SELECT abs(-1), pg_backend_pid()").is_ok());
2736    }
2737
2738    #[mz_ore::test]
2739    fn test_validate_readonly_query_rejects_multiple() {
2740        assert!(validate_readonly_query("SELECT 1; SELECT 2").is_err());
2741    }
2742
2743    #[mz_ore::test]
2744    fn test_validate_readonly_query_rejects_empty() {
2745        assert!(validate_readonly_query("").is_err());
2746        assert!(validate_readonly_query("   ").is_err());
2747    }
2748
2749    /// Regression test for DEX-64: without the 1 MB parser guard, the MCP
2750    /// validators would lex and parse multi-megabyte input. Both
2751    /// `validate_readonly_query` and `bind_system_catalog_query` go through
2752    /// `parse_with_limit`, so an oversized batch is rejected with the same
2753    /// "statement batch size cannot exceed" message the SQL HTTP path emits.
2754    #[mz_ore::test]
2755    fn test_validate_readonly_query_enforces_size_limit() {
2756        use mz_sql_parser::parser::MAX_STATEMENT_BATCH_SIZE;
2757        // Just over the limit so the guard is the *only* thing that rejects.
2758        let oversized: String =
2759            "SELECT 1;".repeat((MAX_STATEMENT_BATCH_SIZE / "SELECT 1;".len()) + 1);
2760        let err = validate_readonly_query(&oversized).expect_err("should be rejected");
2761        let msg = err.to_string();
2762        assert!(
2763            msg.contains("statement batch size cannot exceed"),
2764            "expected size-guard error, got: {msg}"
2765        );
2766    }
2767
2768    #[mz_ore::test]
2769    fn test_validate_system_catalog_query_enforces_size_limit() {
2770        use mz_sql_parser::parser::MAX_STATEMENT_BATCH_SIZE;
2771        let stmt = "SELECT * FROM mz_tables;";
2772        let oversized: String = stmt.repeat((MAX_STATEMENT_BATCH_SIZE / stmt.len()) + 1);
2773        let err = bind_with_stub_catalog(&oversized).expect_err("should be rejected");
2774        let msg = err.to_string();
2775        assert!(
2776            msg.contains("statement batch size cannot exceed"),
2777            "expected size-guard error, got: {msg}"
2778        );
2779    }
2780
2781    #[mz_ore::test]
2782    fn test_validate_system_catalog_query_accepts_mz_tables() {
2783        assert!(bind_with_stub_catalog("SELECT * FROM mz_tables").is_ok());
2784        assert!(bind_with_stub_catalog("SELECT * FROM mz_internal.mz_comments").is_ok());
2785        assert!(
2786            bind_with_stub_catalog("SELECT * FROM mz_tables t JOIN mz_columns c ON t.id = c.id")
2787                .is_ok()
2788        );
2789    }
2790
2791    #[mz_ore::test]
2792    fn test_validate_system_catalog_query_subqueries() {
2793        // Subquery with mz_* tables
2794        assert!(
2795            bind_with_stub_catalog(
2796                "SELECT * FROM mz_tables WHERE id IN (SELECT id FROM mz_columns)"
2797            )
2798            .is_ok()
2799        );
2800
2801        // Nested subqueries with mz_* tables
2802        assert!(bind_with_stub_catalog(
2803            "SELECT * FROM mz_tables WHERE id IN (SELECT table_id FROM mz_columns WHERE type IN (SELECT id FROM mz_types))"
2804        )
2805        .is_ok());
2806
2807        // Subquery in FROM clause
2808        assert!(
2809            bind_with_stub_catalog(
2810                "SELECT * FROM (SELECT * FROM mz_tables WHERE name LIKE 'test%') AS t"
2811            )
2812            .is_ok()
2813        );
2814
2815        // Reject subqueries that reference non-mz_* tables
2816        assert!(
2817            bind_with_stub_catalog(
2818                "SELECT * FROM mz_tables WHERE id IN (SELECT table_id FROM user_data)"
2819            )
2820            .is_err()
2821        );
2822
2823        // Reject mixed references in nested subqueries
2824        assert!(bind_with_stub_catalog(
2825            "SELECT * FROM mz_tables WHERE id IN (SELECT id FROM (SELECT id FROM user_table) AS t)"
2826        )
2827        .is_err());
2828    }
2829
2830    #[mz_ore::test]
2831    fn test_validate_system_catalog_query_rejects_user_tables() {
2832        assert!(bind_with_stub_catalog("SELECT * FROM user_data").is_err());
2833        assert!(bind_with_stub_catalog("SELECT * FROM my_table").is_err());
2834        // Security: reject queries that mention mz_ in a non-table context
2835        assert!(bind_with_stub_catalog("SELECT * FROM user_data WHERE 'mz_' IS NOT NULL").is_err());
2836    }
2837
2838    #[mz_ore::test]
2839    fn test_validate_system_catalog_query_allows_functions() {
2840        // Function names should not be treated as table references
2841        assert!(
2842            bind_with_stub_catalog(
2843                "SELECT date_part('year', now())::int4 AS y FROM mz_tables LIMIT 1"
2844            )
2845            .is_ok()
2846        );
2847        assert!(bind_with_stub_catalog("SELECT length(name) FROM mz_tables").is_ok());
2848        assert!(
2849            bind_with_stub_catalog("SELECT count(*) FROM mz_sources WHERE now() > created_at")
2850                .is_ok()
2851        );
2852    }
2853
2854    #[mz_ore::test]
2855    fn test_validate_system_catalog_query_unqualified_pg_catalog() {
2856        // Unqualified `pg_`-prefixed names are as unambiguously system as `mz_`
2857        // ones, and resolve safely under the pinned search_path.
2858        assert!(bind_with_stub_catalog("SELECT * FROM pg_class").is_ok());
2859        assert!(bind_with_stub_catalog("SELECT nspname FROM pg_namespace").is_ok());
2860    }
2861
2862    #[mz_ore::test]
2863    fn test_validate_system_catalog_query_schema_qualified() {
2864        // Qualified with allowed schemas should work
2865        assert!(bind_with_stub_catalog("SELECT * FROM mz_catalog.mz_tables").is_ok());
2866        assert!(bind_with_stub_catalog("SELECT * FROM mz_internal.mz_sessions").is_ok());
2867        assert!(bind_with_stub_catalog("SELECT * FROM pg_catalog.pg_type").is_ok());
2868        assert!(bind_with_stub_catalog("SELECT * FROM information_schema.tables").is_ok());
2869
2870        // Qualified with disallowed schema should fail
2871        assert!(bind_with_stub_catalog("SELECT * FROM public.user_table").is_err());
2872        assert!(bind_with_stub_catalog("SELECT * FROM myschema.mytable").is_err());
2873
2874        // mz_unsafe is a system schema but explicitly blocked for MCP
2875        assert!(
2876            bind_with_stub_catalog("SELECT * FROM mz_unsafe.mz_some_table").is_err(),
2877            "mz_unsafe schema should be blocked even though it is a system schema"
2878        );
2879
2880        // Mixed: system and user schemas should fail
2881        assert!(
2882            bind_with_stub_catalog(
2883                "SELECT * FROM mz_catalog.mz_tables JOIN public.user_data ON true"
2884            )
2885            .is_err()
2886        );
2887    }
2888
2889    #[mz_ore::test]
2890    fn test_validate_system_catalog_query_rejects_hidden_user_references() {
2891        for sql in [
2892            "SELECT * FROM mz_catalog.mz_tables UNION ALL TABLE public.user_data",
2893            "WITH user_data AS (SELECT 1) \
2894             SELECT * FROM public.user_data, mz_catalog.mz_tables",
2895            "SELECT * FROM [u1 AS mz_catalog.mz_tables]",
2896        ] {
2897            assert!(bind_with_stub_catalog(sql).is_err(), "should reject {sql}");
2898        }
2899    }
2900
2901    #[mz_ore::test]
2902    fn test_validate_system_catalog_query_accepts_table_and_mutual_recursion() {
2903        for sql in [
2904            "TABLE mz_catalog.mz_tables",
2905            "WITH MUTUALLY RECURSIVE \
2906               t (id text) AS (TABLE u), \
2907               u (id text) AS (SELECT id FROM mz_catalog.mz_tables) \
2908             SELECT * FROM t",
2909        ] {
2910            assert!(bind_with_stub_catalog(sql).is_ok(), "should accept {sql}");
2911        }
2912    }
2913
2914    #[mz_ore::test]
2915    fn test_validate_system_catalog_query_adversarial_cases() {
2916        // Try to sneak in user table via CTE
2917        assert!(
2918            bind_with_stub_catalog(
2919                "WITH user_cte AS (SELECT * FROM user_data) \
2920                 SELECT * FROM mz_tables, user_cte"
2921            )
2922            .is_err(),
2923            "Should reject CTE referencing user table"
2924        );
2925
2926        // Complex multi-level CTE with user table buried deep
2927        assert!(
2928            bind_with_stub_catalog(
2929                "WITH \
2930                   cte1 AS (SELECT * FROM mz_tables), \
2931                   cte2 AS (SELECT * FROM cte1), \
2932                   cte3 AS (SELECT * FROM user_data) \
2933                 SELECT * FROM cte2"
2934            )
2935            .is_err(),
2936            "Should reject CTE chain with user table"
2937        );
2938
2939        // Multiple joins - user table in the middle
2940        assert!(
2941            bind_with_stub_catalog(
2942                "SELECT * FROM mz_tables t1 \
2943                 JOIN user_data u ON t1.id = u.id \
2944                 JOIN mz_sources s ON t1.id = s.id"
2945            )
2946            .is_err(),
2947            "Should reject multi-join with user table"
2948        );
2949
2950        // LEFT JOIN trying to hide user table
2951        assert!(
2952            bind_with_stub_catalog(
2953                "SELECT * FROM mz_tables t \
2954                 LEFT JOIN user_data u ON t.id = u.table_id \
2955                 WHERE u.id IS NULL"
2956            )
2957            .is_err(),
2958            "Should reject LEFT JOIN with user table"
2959        );
2960
2961        // Nested subquery with user table in FROM
2962        assert!(
2963            bind_with_stub_catalog(
2964                "SELECT * FROM mz_tables WHERE id IN \
2965                 (SELECT table_id FROM (SELECT * FROM user_data) AS u)"
2966            )
2967            .is_err(),
2968            "Should reject nested subquery with user table"
2969        );
2970
2971        // UNION trying to mix system and user data
2972        assert!(
2973            bind_with_stub_catalog(
2974                "SELECT name FROM mz_tables \
2975                 UNION \
2976                 SELECT name FROM user_data"
2977            )
2978            .is_err(),
2979            "Should reject UNION with user table"
2980        );
2981
2982        // UNION ALL variation
2983        assert!(
2984            bind_with_stub_catalog(
2985                "SELECT id FROM mz_sources \
2986                 UNION ALL \
2987                 SELECT id FROM products"
2988            )
2989            .is_err(),
2990            "Should reject UNION ALL with user table"
2991        );
2992
2993        // Cross join with user table
2994        assert!(
2995            bind_with_stub_catalog("SELECT * FROM mz_tables CROSS JOIN user_data").is_err(),
2996            "Should reject CROSS JOIN with user table"
2997        );
2998
2999        // Subquery in SELECT clause referencing user table
3000        assert!(
3001            bind_with_stub_catalog(
3002                "SELECT t.*, (SELECT COUNT(*) FROM user_data) AS cnt FROM mz_tables t"
3003            )
3004            .is_err(),
3005            "Should reject subquery in SELECT with user table"
3006        );
3007
3008        // Try to use a schema name that looks similar to allowed ones
3009        assert!(
3010            bind_with_stub_catalog("SELECT * FROM mz_catalogg.fake_table").is_err(),
3011            "Should reject typo-squatting schema name"
3012        );
3013        assert!(
3014            bind_with_stub_catalog("SELECT * FROM mz_catalog_hack.fake_table").is_err(),
3015            "Should reject fake schema with mz_catalog prefix"
3016        );
3017
3018        // Lateral join with user table
3019        assert!(
3020            bind_with_stub_catalog(
3021                "SELECT * FROM mz_tables t, LATERAL (SELECT * FROM user_data WHERE id = t.id) u"
3022            )
3023            .is_err(),
3024            "Should reject LATERAL join with user table"
3025        );
3026
3027        // Valid complex query - all system tables
3028        assert!(
3029            bind_with_stub_catalog(
3030                "WITH \
3031                   tables AS (SELECT * FROM mz_tables), \
3032                   sources AS (SELECT * FROM mz_sources) \
3033                 SELECT t.name, s.name \
3034                 FROM tables t \
3035                 JOIN sources s ON t.id = s.id \
3036                 WHERE t.id IN (SELECT id FROM mz_columns)"
3037            )
3038            .is_ok(),
3039            "Should allow complex query with only system tables"
3040        );
3041
3042        // Valid UNION of system tables
3043        assert!(
3044            bind_with_stub_catalog(
3045                "SELECT name FROM mz_tables \
3046                 UNION \
3047                 SELECT name FROM mz_sources"
3048            )
3049            .is_ok(),
3050            "Should allow UNION of system tables"
3051        );
3052    }
3053
3054    #[mz_ore::test]
3055    fn test_validate_system_catalog_query_rejects_constant_queries() {
3056        // SELECT without any table reference is rejected. The developer
3057        // endpoint is for system catalog queries, not arbitrary computation.
3058        assert!(
3059            bind_with_stub_catalog("SELECT 1").is_err(),
3060            "Should reject constant SELECT with no table references"
3061        );
3062        assert!(
3063            bind_with_stub_catalog("SELECT 1 + 2, 'hello'").is_err(),
3064            "Should reject constant expression SELECT"
3065        );
3066        assert!(
3067            bind_with_stub_catalog("SELECT now()").is_err(),
3068            "Should reject function-only SELECT with no table references"
3069        );
3070    }
3071
3072    #[mz_ore::test]
3073    fn test_validate_system_catalog_query_rejects_mixed_tables() {
3074        assert!(
3075            bind_with_stub_catalog(
3076                "SELECT * FROM mz_tables t JOIN user_data u ON t.id = u.table_id"
3077            )
3078            .is_err()
3079        );
3080    }
3081
3082    #[mz_ore::test]
3083    fn test_validate_system_catalog_query_allows_show() {
3084        assert!(
3085            bind_with_stub_catalog("SHOW TABLES FROM mz_internal").is_ok(),
3086            "SHOW TABLES FROM mz_internal should be allowed"
3087        );
3088        assert!(
3089            bind_with_stub_catalog("SHOW TABLES FROM mz_catalog").is_ok(),
3090            "SHOW TABLES FROM mz_catalog should be allowed"
3091        );
3092        assert!(
3093            bind_with_stub_catalog("SHOW CLUSTERS").is_ok(),
3094            "SHOW CLUSTERS should be allowed"
3095        );
3096        assert!(
3097            bind_with_stub_catalog("SHOW SOURCES").is_ok(),
3098            "SHOW SOURCES should be allowed"
3099        );
3100        assert!(
3101            bind_with_stub_catalog("SHOW TABLES").is_ok(),
3102            "SHOW TABLES should be allowed"
3103        );
3104    }
3105
3106    #[mz_ore::test]
3107    fn test_validate_system_catalog_query_allows_explain() {
3108        assert!(
3109            bind_with_stub_catalog("EXPLAIN SELECT * FROM mz_tables").is_ok(),
3110            "EXPLAIN of system table query should be allowed"
3111        );
3112        assert!(
3113            bind_with_stub_catalog("EXPLAIN SELECT 1").is_ok(),
3114            "EXPLAIN SELECT 1 should be allowed"
3115        );
3116    }
3117
3118    #[mz_ore::test]
3119    fn test_bind_system_catalog_query_binds_show_and_explain_names() {
3120        for (sql, bound) in [
3121            (
3122                "SHOW CREATE VIEW mz_catalog.mz_tables",
3123                r#"SHOW CREATE VIEW [s1 AS "mz_catalog"."mz_tables"]"#,
3124            ),
3125            (
3126                "SHOW COLUMNS FROM mz_tables",
3127                r#"SHOW COLUMNS FROM [s1 AS "mz_catalog"."mz_tables"]"#,
3128            ),
3129            (
3130                "SHOW INDEXES ON mz_internal.mz_comments",
3131                r#"SHOW INDEXES ON [s1 AS "mz_internal"."mz_comments"]"#,
3132            ),
3133            (
3134                "EXPLAIN OPTIMIZED PLAN FOR INDEX mz_internal.mz_show_databases_ind",
3135                r#"EXPLAIN OPTIMIZED PLAN FOR INDEX [s1 AS "mz_internal"."mz_show_databases_ind"]"#,
3136            ),
3137            (
3138                "SELECT count(*), now() FROM mz_tables",
3139                r#"SELECT "count"(*), "now"() FROM [s1 AS "mz_catalog"."mz_tables"]"#,
3140            ),
3141        ] {
3142            assert_eq!(bind_with_stub_catalog(sql).unwrap(), bound, "{sql}");
3143        }
3144
3145        for sql in [
3146            "SHOW CREATE TABLE materialize.public.t",
3147            r#"SHOW CREATE VIEW "MZ_CATALOG".leak"#,
3148            "SHOW CREATE MATERIALIZED VIEW mv",
3149            "SHOW COLUMNS FROM public.t",
3150            "SHOW INDEXES ON t",
3151            "SHOW TABLES FROM public",
3152            r#"SHOW TABLES FROM "MZ_CATALOG""#,
3153            "SHOW TABLES FROM mz_unsafe",
3154            "EXPLAIN OPTIMIZED PLAN FOR VIEW public.v",
3155            "EXPLAIN OPTIMIZED PLAN FOR MATERIALIZED VIEW mv",
3156            "EXPLAIN OPTIMIZED PLAN FOR INDEX public.i",
3157            "EXPLAIN FILTER PUSHDOWN FOR MATERIALIZED VIEW mv",
3158            "EXPLAIN OPTIMIZED PLAN FOR CREATE INDEX ON public.t (a)",
3159            "EXPLAIN OPTIMIZED PLAN FOR SUBSCRIBE TO public.t",
3160            "EXPLAIN SELECT * FROM public.t",
3161            "EXPLAIN TIMESTAMP FOR SELECT * FROM public.t",
3162        ] {
3163            assert!(
3164                bind_with_stub_catalog(sql).is_err(),
3165                "{sql} must be rejected"
3166            );
3167        }
3168    }
3169
3170    #[mz_ore::test]
3171    fn test_bind_system_catalog_query_binds_relations_by_id() {
3172        for (sql, bound) in [
3173            (
3174                "SELECT name FROM mz_catalog.mz_tables",
3175                r#"SELECT "name" FROM [s1 AS "mz_catalog"."mz_tables"]"#,
3176            ),
3177            (
3178                "SELECT * FROM mz_tables",
3179                r#"SELECT * FROM [s1 AS "mz_catalog"."mz_tables"]"#,
3180            ),
3181            (
3182                "SELECT * FROM information_schema.tables t",
3183                r#"SELECT * FROM [s1 AS "information_schema"."tables"] AS "t""#,
3184            ),
3185            (
3186                "WITH mz_x AS (SELECT 1) SELECT * FROM mz_x, mz_tables",
3187                r#"WITH "mz_x" AS (SELECT 1) SELECT * FROM "mz_x", [s1 AS "mz_catalog"."mz_tables"]"#,
3188            ),
3189            (
3190                "EXPLAIN SELECT * FROM mz_tables",
3191                r#"EXPLAIN SELECT * FROM [s1 AS "mz_catalog"."mz_tables"]"#,
3192            ),
3193            (
3194                "SELECT * FROM materialize.mz_catalog.mz_tables",
3195                r#"SELECT * FROM [s1 AS "mz_catalog"."mz_tables"]"#,
3196            ),
3197            (
3198                "TABLE mz_tables",
3199                r#"TABLE [s1 AS "mz_catalog"."mz_tables"]"#,
3200            ),
3201            (
3202                "SELECT * FROM mz_introspection.mz_dataflows",
3203                r#"SELECT * FROM [s1 AS "mz_introspection"."mz_dataflows"]"#,
3204            ),
3205        ] {
3206            let bound_sql = bind_with_stub_catalog(sql).expect(sql);
3207            assert_eq!(bound_sql, bound, "binding {sql}");
3208            assert!(
3209                matches!(parse_with_limit(&bound_sql), Ok(Ok(_))),
3210                "{bound_sql} should parse"
3211            );
3212        }
3213    }
3214
3215    #[mz_ore::test]
3216    fn test_bind_system_catalog_query_matches_exact_spelling() {
3217        // Quoted names keep their case, and user schemas such as "MZ_CATALOG"
3218        // or "INFORMATION_SCHEMA" may exist.
3219        for sql in [
3220            r#"SELECT * FROM "MZ_CATALOG".mz_tables"#,
3221            r#"SELECT * FROM "INFORMATION_SCHEMA".tables"#,
3222            r#"SELECT * FROM "MZ_TABLES""#,
3223            "SHOW TABLES WHERE name IN (SELECT name FROM public.t)",
3224            "SELECT * FROM [u1 AS mz_catalog.mz_tables]",
3225            // A user schema can take this name.
3226            "SHOW VIEWS FROM information_schema",
3227            "SHOW OBJECTS FROM materialize.information_schema",
3228        ] {
3229            assert!(
3230                bind_with_stub_catalog(sql).is_err(),
3231                "{sql} should be rejected"
3232            );
3233        }
3234    }
3235
3236    #[mz_ore::test]
3237    fn test_bind_system_catalog_query_reports_unknown_names() {
3238        for (sql, message) in [
3239            (
3240                "SELECT * FROM mz_catalog.mz_missing",
3241                "unknown system catalog objects",
3242            ),
3243            ("SELECT * FROM mz_missing", "unknown system catalog objects"),
3244            ("SELECT * FROM user_table", "non-system objects"),
3245        ] {
3246            let err = bind_with_stub_catalog(sql).expect_err(sql).to_string();
3247            assert!(err.contains(message), "{sql}: {err}");
3248        }
3249    }
3250
3251    #[mz_ore::test]
3252    fn test_bind_system_catalog_query_checks_function_fields() {
3253        for sql in [
3254            "SELECT max((SELECT a FROM materialize.public.t)) FROM mz_tables",
3255            "SELECT count(*) FILTER (WHERE EXISTS (SELECT 1 FROM materialize.public.t)) \
3256             FROM mz_tables",
3257            "SELECT count(*) OVER (ORDER BY (SELECT a FROM materialize.public.t)) FROM mz_tables",
3258        ] {
3259            let err = bind_with_stub_catalog(sql).expect_err(sql).to_string();
3260            assert!(err.contains("materialize.public.t"), "{sql}: {err}");
3261        }
3262    }
3263
3264    #[mz_ore::test]
3265    fn test_bind_system_catalog_query_rejects_show_create_type() {
3266        for sql in [
3267            "SHOW CREATE TYPE public.mytype",
3268            "SHOW CREATE TYPE [u6 AS materialize.public.mytype]",
3269        ] {
3270            assert!(
3271                bind_with_stub_catalog(sql).is_err(),
3272                "{sql} should be rejected"
3273            );
3274        }
3275    }
3276
3277    #[mz_ore::test(tokio::test)]
3278    async fn test_tools_list_agent_query_tool_disabled() {
3279        let result = handle_tools_list(McpEndpointType::Agent, false, true, 1_000_000).unwrap();
3280        let McpResult::ToolsList(list) = result else {
3281            panic!("Expected ToolsList result");
3282        };
3283        let tool_names: Vec<&str> = list.tools.iter().map(|t| t.name.as_str()).collect();
3284        assert!(
3285            tool_names.contains(&"get_data_products"),
3286            "get_data_products should always be present"
3287        );
3288        assert!(
3289            tool_names.contains(&"get_data_product_details"),
3290            "get_data_product_details should always be present"
3291        );
3292        assert!(
3293            tool_names.contains(&"read_data_product"),
3294            "read_data_product should be present when its flag is on"
3295        );
3296        assert!(
3297            !tool_names.contains(&"query"),
3298            "query tool should be hidden when disabled"
3299        );
3300    }
3301
3302    #[mz_ore::test(tokio::test)]
3303    async fn test_tools_list_agent_query_tool_enabled() {
3304        let result = handle_tools_list(McpEndpointType::Agent, true, true, 1_000_000).unwrap();
3305        let McpResult::ToolsList(list) = result else {
3306            panic!("Expected ToolsList result");
3307        };
3308        let tool_names: Vec<&str> = list.tools.iter().map(|t| t.name.as_str()).collect();
3309        assert!(
3310            tool_names.contains(&"get_data_products"),
3311            "get_data_products should always be present"
3312        );
3313        assert!(
3314            tool_names.contains(&"get_data_product_details"),
3315            "get_data_product_details should always be present"
3316        );
3317        assert!(
3318            tool_names.contains(&"read_data_product"),
3319            "read_data_product should be present when its flag is on"
3320        );
3321        assert!(
3322            tool_names.contains(&"query"),
3323            "query tool should be present when enabled"
3324        );
3325    }
3326
3327    #[mz_ore::test(tokio::test)]
3328    async fn test_tools_list_agent_read_data_product_tool_disabled() {
3329        let result = handle_tools_list(McpEndpointType::Agent, true, false, 1_000_000).unwrap();
3330        let McpResult::ToolsList(list) = result else {
3331            panic!("Expected ToolsList result");
3332        };
3333        let tool_names: Vec<&str> = list.tools.iter().map(|t| t.name.as_str()).collect();
3334        assert!(
3335            tool_names.contains(&"get_data_products"),
3336            "get_data_products should always be present"
3337        );
3338        assert!(
3339            tool_names.contains(&"get_data_product_details"),
3340            "get_data_product_details should always be present"
3341        );
3342        assert!(
3343            !tool_names.contains(&"read_data_product"),
3344            "read_data_product should be hidden when disabled"
3345        );
3346        assert!(
3347            tool_names.contains(&"query"),
3348            "query tool should remain present when enabled"
3349        );
3350    }
3351
3352    /// Both read tools off is a valid (if unusual) config where the agent
3353    /// is discovery-only. Pin the behavior: only get_data_products and
3354    /// get_data_product_details are advertised, and the initialize
3355    /// instructions do not tell the agent to use a tool that isn't listed.
3356    #[mz_ore::test(tokio::test)]
3357    async fn test_tools_list_agent_both_read_tools_disabled() {
3358        let result = handle_tools_list(McpEndpointType::Agent, false, false, 1_000_000).unwrap();
3359        let McpResult::ToolsList(list) = result else {
3360            panic!("Expected ToolsList result");
3361        };
3362        let tool_names: Vec<&str> = list.tools.iter().map(|t| t.name.as_str()).collect();
3363        assert_eq!(
3364            tool_names
3365                .iter()
3366                .copied()
3367                .collect::<std::collections::BTreeSet<_>>(),
3368            ["get_data_product_details", "get_data_products"]
3369                .into_iter()
3370                .collect(),
3371            "only discovery tools should be advertised when both read flags are off",
3372        );
3373
3374        let instructions = endpoint_instructions(McpEndpointType::Agent, false, false)
3375            .expect("agent instructions must be present");
3376        assert!(
3377            !instructions.contains("Use the `query` tool"),
3378            "instructions must not point at query when it is hidden: {instructions}",
3379        );
3380        assert!(
3381            !instructions.contains("`read_data_product` automatically"),
3382            "instructions must not point at read_data_product when it is hidden: {instructions}",
3383        );
3384        assert!(
3385            instructions.contains("discovery only"),
3386            "instructions must tell the agent it is discovery-only: {instructions}",
3387        );
3388    }
3389
3390    #[mz_ore::test(tokio::test)]
3391    async fn test_tools_list_developer_query_tool_disabled() {
3392        // Developer endpoint doesn't expose read_data_product; the flag is
3393        // orthogonal, so pass whichever value.
3394        let result = handle_tools_list(McpEndpointType::Developer, false, true, 1_000_000).unwrap();
3395        let McpResult::ToolsList(list) = result else {
3396            panic!("Expected ToolsList result");
3397        };
3398        let tool_names: Vec<&str> = list.tools.iter().map(|t| t.name.as_str()).collect();
3399        assert!(
3400            tool_names.contains(&"query_system_catalog"),
3401            "query_system_catalog should always be present on developer"
3402        );
3403        assert!(
3404            !tool_names.contains(&"query"),
3405            "query tool should be hidden when disabled"
3406        );
3407    }
3408
3409    #[mz_ore::test(tokio::test)]
3410    async fn test_tools_list_developer_query_tool_enabled() {
3411        let result = handle_tools_list(McpEndpointType::Developer, true, true, 1_000_000).unwrap();
3412        let McpResult::ToolsList(list) = result else {
3413            panic!("Expected ToolsList result");
3414        };
3415        let tool_names: Vec<&str> = list.tools.iter().map(|t| t.name.as_str()).collect();
3416        assert!(
3417            tool_names.contains(&"query_system_catalog"),
3418            "query_system_catalog should always be present on developer"
3419        );
3420        assert!(
3421            tool_names.contains(&"query"),
3422            "query tool should be present on developer when enabled"
3423        );
3424
3425        let instructions = endpoint_instructions(McpEndpointType::Developer, true, true)
3426            .expect("developer instructions must be present");
3427        assert!(
3428            instructions.contains("through the query tool with its cluster argument"),
3429            "instructions must route mz_introspection through query: {instructions}",
3430        );
3431    }
3432
3433    #[mz_ore::test]
3434    fn test_developer_instructions_query_tool_disabled() {
3435        let instructions = endpoint_instructions(McpEndpointType::Developer, false, true)
3436            .expect("developer instructions must be present");
3437        assert!(
3438            instructions.contains("cluster-targeted introspection is unavailable")
3439                && !instructions.contains("through the query tool"),
3440            "instructions must not route to the hidden query tool: {instructions}",
3441        );
3442    }
3443
3444    /// Clients attach `_meta` to `tools/list`. Rejecting it fails the whole
3445    /// request with a 422, which the client reads as the server being down.
3446    #[mz_ore::test]
3447    fn test_tools_list_accepts_optional_params() {
3448        for body in [
3449            r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#,
3450            r#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":null}"#,
3451            r#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}"#,
3452            r#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{"_meta":{"progressToken":0}}}"#,
3453        ] {
3454            let req: McpRequest = serde_json::from_str(body)
3455                .unwrap_or_else(|e| panic!("tools/list must deserialize: {body}: {e}"));
3456            assert!(
3457                matches!(req.method, McpMethod::ToolsList(_)),
3458                "expected ToolsList for {body}"
3459            );
3460        }
3461    }
3462
3463    #[mz_ore::test]
3464    fn test_protocol_version_select() {
3465        use ProtocolVersion::*;
3466        for (header, want) in [
3467            (&[][..], V2025_11_25),
3468            (&["2025-11-25"], V2025_11_25),
3469            (&["2025-06-18"], V2025_11_25),
3470            (&["2026-07-28"], V2026_07_28),
3471            (&["not-a-version"], V2025_11_25),
3472            (&["2026-07-28X"], V2025_11_25),
3473            (&["2025-11-25", "2026-07-28"], V2026_07_28),
3474            (&["2025-11-25, 2026-07-28"], V2026_07_28),
3475        ] {
3476            let values: Vec<_> = header.iter().map(|v| HeaderValue::from_static(v)).collect();
3477            assert_eq!(ProtocolVersion::select(&values), want, "for {header:?}");
3478        }
3479        let non_ascii = HeaderValue::from_bytes(b"2026-07-28\xff").expect("valid header bytes");
3480        assert_eq!(ProtocolVersion::select(&[non_ascii]), V2025_11_25);
3481        let non_ascii_list =
3482            HeaderValue::from_bytes(b"\xff, 2026-07-28").expect("valid header bytes");
3483        assert_eq!(ProtocolVersion::select(&[non_ascii_list]), V2026_07_28);
3484    }
3485
3486    fn json_headers() -> HeaderMap {
3487        HeaderMap::from_iter([(
3488            header::CONTENT_TYPE,
3489            HeaderValue::from_static("application/json"),
3490        )])
3491    }
3492
3493    #[mz_ore::test]
3494    fn test_parse_mcp_request_unknown_method_with_params() {
3495        let req = parse_mcp_request(
3496            &json_headers(),
3497            br#"{"jsonrpc":"2.0","id":7,"method":"server/other","params":{"_meta":{}}}"#,
3498        )
3499        .expect("unknown method with params must parse");
3500        assert!(matches!(req.method, McpMethod::Unknown));
3501        assert_eq!(req.id, Some(json!(7)));
3502
3503        let req = parse_mcp_request(
3504            &json_headers(),
3505            br#"{"jsonrpc":"2.0","method":"notifications/other","params":{}}"#,
3506        )
3507        .expect("unknown notification with params must parse");
3508        assert!(matches!(req.method, McpMethod::Unknown));
3509        assert_eq!(req.id, None);
3510    }
3511
3512    #[mz_ore::test]
3513    fn test_parse_mcp_request_keeps_other_rejections() {
3514        for (headers, body, want) in [
3515            (
3516                json_headers(),
3517                &br#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"nonexistent_tool","arguments":{}}}"#[..],
3518                StatusCode::UNPROCESSABLE_ENTITY,
3519            ),
3520            (
3521                json_headers(),
3522                br#"{"id":1,"method":"server/other","params":{}}"#,
3523                StatusCode::UNPROCESSABLE_ENTITY,
3524            ),
3525            (json_headers(), b"{not json", StatusCode::BAD_REQUEST),
3526            (
3527                HeaderMap::new(),
3528                br#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#,
3529                StatusCode::UNSUPPORTED_MEDIA_TYPE,
3530            ),
3531        ] {
3532            let rejection = parse_mcp_request(&headers, body).expect_err("must be rejected");
3533            let body = String::from_utf8_lossy(body);
3534            assert_eq!(rejection.status(), want, "for {body}");
3535        }
3536    }
3537
3538    fn headers(method: &'static str, name: Option<&'static str>) -> McpHeaders {
3539        McpHeaders {
3540            protocol_version: vec![HeaderValue::from_static(
3541                ProtocolVersion::V2026_07_28.as_str(),
3542            )],
3543            method: vec![HeaderValue::from_static(method)],
3544            name: name.into_iter().map(HeaderValue::from_static).collect(),
3545        }
3546    }
3547
3548    #[mz_ore::test]
3549    fn test_header_check_tool_names() {
3550        let call = headers("tools/call", Some("query"));
3551        assert!(call.check("tools/call", ToolName::Name("query")).is_ok());
3552        assert!(call.check("tools/call", ToolName::Missing).is_err());
3553        assert!(call.check("tools/list", ToolName::NotToolsCall).is_err());
3554        assert!(
3555            headers("server/other", None)
3556                .check("server/other", ToolName::NotToolsCall)
3557                .is_ok()
3558        );
3559    }
3560
3561    /// Bodies the datadriven harness cannot send: not a JSON object, not JSON,
3562    /// or an object without a `method`.
3563    #[mz_ore::test(tokio::test)]
3564    async fn test_answer_parse_failure() {
3565        let no_method = r#"{"jsonrpc":"2.0","id":4,"params":{}}"#;
3566        for (body, want_code, want_id) in [
3567            ("[]", error_codes::INVALID_REQUEST, None),
3568            ("null", error_codes::INVALID_REQUEST, None),
3569            ("{not json", error_codes::PARSE_ERROR, None),
3570            (no_method, error_codes::INVALID_REQUEST, Some(json!(4))),
3571        ] {
3572            let failure = parse_mcp_request(&json_headers(), body.as_bytes())
3573                .expect_err("not a request we parse");
3574            let headers = headers("tools/list", None);
3575            let resp = answer_parse_failure(failure, body.as_bytes(), &headers, &|_| {});
3576            assert_eq!(resp.status(), StatusCode::BAD_REQUEST, "status for {body}");
3577            let resp: serde_json::Value = serde_json::from_slice(
3578                &axum::body::to_bytes(resp.into_body(), usize::MAX)
3579                    .await
3580                    .expect("body"),
3581            )
3582            .expect("JSON body");
3583            assert_eq!(resp["error"]["code"], json!(want_code), "code for {body}");
3584            assert_eq!(resp.get("id").cloned(), want_id, "id for {body}");
3585        }
3586    }
3587
3588    /// `ping` and `notifications/initialized` are named variants so their
3589    /// `params` deserialize. A `_meta` on the acknowledgement would otherwise
3590    /// fail the body with a 422 in the middle of the handshake.
3591    #[mz_ore::test]
3592    fn test_named_methods_accept_optional_params() {
3593        for (body, want_ping) in [
3594            (r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#, true),
3595            (
3596                r#"{"jsonrpc":"2.0","id":1,"method":"ping","params":{}}"#,
3597                true,
3598            ),
3599            (
3600                r#"{"jsonrpc":"2.0","id":1,"method":"ping","params":{"_meta":{"progressToken":0}}}"#,
3601                true,
3602            ),
3603            (
3604                r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
3605                false,
3606            ),
3607            (
3608                r#"{"jsonrpc":"2.0","method":"notifications/initialized","params":{"_meta":{"x":1}}}"#,
3609                false,
3610            ),
3611        ] {
3612            let req: McpRequest = serde_json::from_str(body)
3613                .unwrap_or_else(|e| panic!("must deserialize: {body}: {e}"));
3614            if want_ping {
3615                assert!(matches!(req.method, McpMethod::Ping(_)), "for {body}");
3616            } else {
3617                assert!(
3618                    matches!(req.method, McpMethod::NotificationsInitialized(_)),
3619                    "for {body}"
3620                );
3621            }
3622        }
3623    }
3624
3625    #[mz_ore::test]
3626    fn test_tools_call_arguments_optional() {
3627        for body in [
3628            r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_data_products"}}"#,
3629            r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_data_products","arguments":{}}}"#,
3630            r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"get_data_products","arguments":null}}"#,
3631        ] {
3632            let req: McpRequest = serde_json::from_str(body)
3633                .unwrap_or_else(|e| panic!("must deserialize: {body}: {e}"));
3634            assert!(
3635                matches!(
3636                    req.method,
3637                    McpMethod::ToolsCall(ToolsCallParams::GetDataProducts(NoArguments {}))
3638                ),
3639                "for {body}"
3640            );
3641        }
3642
3643        // A tool that needs arguments still fails, on the missing field itself.
3644        let err = serde_json::from_str::<McpRequest>(
3645            r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"query_system_catalog"}}"#,
3646        )
3647        .expect_err("query_system_catalog requires sql_query");
3648        assert!(err.to_string().contains("sql_query"), "{err}");
3649    }
3650
3651    #[mz_ore::test]
3652    fn test_format_rows_response_within_limit() {
3653        let rows = vec![vec![json!("a"), json!(1)], vec![json!("b"), json!(2)]];
3654        let result = format_rows_response(raw_rows(rows), 1_000_000).unwrap();
3655        let McpResult::ToolContent(content) = result else {
3656            panic!("Expected ToolContent");
3657        };
3658        assert_eq!(content.content.len(), 1);
3659        assert!(content.content[0].text.contains("\"a\""));
3660        assert!(content.content[0].text.contains("\"b\""));
3661    }
3662
3663    #[mz_ore::test]
3664    fn test_format_rows_response_errors_when_over_limit() {
3665        let rows: Vec<Vec<serde_json::Value>> = (0..100)
3666            .map(|i| vec![json!(format!("row_{}", i)), json!(i)])
3667            .collect();
3668        let err = format_rows_response(raw_rows(rows), 500).unwrap_err();
3669        let msg = err.to_string();
3670        assert!(
3671            msg.contains("exceeds the 500 byte limit"),
3672            "Error should mention the size limit, got: {msg}"
3673        );
3674        assert!(
3675            msg.contains("Use LIMIT or WHERE"),
3676            "Error should suggest narrowing the query, got: {msg}"
3677        );
3678    }
3679
3680    #[mz_ore::test]
3681    fn test_format_rows_response_empty_rows() {
3682        let rows: Vec<Vec<serde_json::Value>> = vec![];
3683        let result = format_rows_response(raw_rows(rows), 1000).unwrap();
3684        let McpResult::ToolContent(content) = result else {
3685            panic!("Expected ToolContent");
3686        };
3687        assert_eq!(content.content.len(), 1);
3688        assert_eq!(content.content[0].text, "[]");
3689    }
3690
3691    #[mz_ore::test]
3692    fn test_safe_data_product_name_valid() {
3693        // Fully qualified quoted identifiers
3694        assert_eq!(
3695            safe_data_product_name(r#""materialize"."public"."my_view""#).unwrap(),
3696            r#""materialize"."public"."my_view""#
3697        );
3698        // Two-part name
3699        assert_eq!(
3700            safe_data_product_name(r#""public"."my_view""#).unwrap(),
3701            r#""public"."my_view""#
3702        );
3703        // Unquoted name gets quoted in stable mode
3704        assert_eq!(safe_data_product_name("my_view").unwrap(), r#""my_view""#);
3705    }
3706
3707    #[mz_ore::test]
3708    fn test_safe_data_product_name_rejects_empty() {
3709        assert!(safe_data_product_name("").is_err());
3710        assert!(safe_data_product_name("   ").is_err());
3711    }
3712
3713    /// DEX-64: `parse_item_name` is unbounded on its own; the MCP path
3714    /// switches to `parse_item_name_with_limit` so a pathological name (e.g.
3715    /// millions of `(` characters) is rejected before lexing.
3716    #[mz_ore::test]
3717    fn test_safe_data_product_name_enforces_size_limit() {
3718        use mz_sql_parser::parser::MAX_STATEMENT_BATCH_SIZE;
3719        let oversized: String = "(".repeat(MAX_STATEMENT_BATCH_SIZE + 1);
3720        let err = safe_data_product_name(&oversized).expect_err("should be rejected");
3721        let msg = err.to_string();
3722        assert!(
3723            msg.contains("statement batch size cannot exceed"),
3724            "expected size-guard error, got: {msg}"
3725        );
3726    }
3727
3728    #[mz_ore::test]
3729    fn test_safe_data_product_name_rejects_sql_injection() {
3730        // Attempted injection via semicolon
3731        assert!(safe_data_product_name("my_view; DROP TABLE users").is_err());
3732        // Attempted injection via subquery
3733        assert!(safe_data_product_name("my_view UNION SELECT * FROM secrets").is_err());
3734        // Multiple table references via comma
3735        assert!(safe_data_product_name("my_view, secrets").is_err());
3736        // SQL keywords after name are rejected by the parser
3737        assert!(safe_data_product_name("my_view WHERE 1=1 --").is_err());
3738    }
3739
3740    /// A trailing `--` comment in the body must not swallow the `; COMMIT;`.
3741    #[mz_ore::test]
3742    fn test_read_only_txn_comment_cannot_swallow_commit() {
3743        let sql = read_only_txn(Some("SET CLUSTER = 'c'"), "SELECT 1 --");
3744        assert!(
3745            sql.contains("\n; COMMIT;"),
3746            "COMMIT must sit on its own line: {sql}",
3747        );
3748    }
3749
3750    #[mz_ore::test]
3751    fn test_placement_set_clause() {
3752        assert_eq!(Placement::SessionDefault.set_clause(), None);
3753        assert_eq!(
3754            Placement::Cluster("prod_cluster").set_clause().as_deref(),
3755            Some("SET CLUSTER = 'prod_cluster'")
3756        );
3757        assert_eq!(
3758            Placement::Replica {
3759                cluster: "prod_cluster",
3760                replica: "r1"
3761            }
3762            .set_clause()
3763            .as_deref(),
3764            Some("SET CLUSTER = 'prod_cluster'; SET CLUSTER_REPLICA = 'r1'")
3765        );
3766    }
3767
3768    #[mz_ore::test]
3769    fn test_placement_set_clause_escapes_replica_name() {
3770        let clause = Placement::Replica {
3771            cluster: "c",
3772            replica: "evil'; DROP TABLE secrets; --",
3773        }
3774        .set_clause();
3775        assert_eq!(
3776            clause.as_deref(),
3777            Some("SET CLUSTER = 'c'; SET CLUSTER_REPLICA = 'evil''; DROP TABLE secrets; --'")
3778        );
3779    }
3780
3781    #[mz_ore::test]
3782    fn test_placement_validate() {
3783        assert!(Placement::SessionDefault.validate().is_ok());
3784        assert!(Placement::Cluster("c").validate().is_ok());
3785        let replica = |cluster, replica| Placement::Replica { cluster, replica };
3786        assert!(replica("c", "r1").validate().is_ok());
3787        for bad in [
3788            Placement::Cluster(""),
3789            Placement::Cluster("   "),
3790            replica("", "r1"),
3791            replica("c", ""),
3792            replica("c", "\t\n"),
3793        ] {
3794            assert!(
3795                matches!(
3796                    bad.validate(),
3797                    Err(McpRequestError::QueryValidationFailed(_))
3798                ),
3799                "expected validation error for {bad:?}",
3800            );
3801        }
3802    }
3803
3804    #[mz_ore::test]
3805    fn test_unified_placement() {
3806        let params = |cluster: Option<&str>, replica: Option<&str>| QueryParams {
3807            cluster: cluster.map(str::to_string),
3808            cluster_replica: replica.map(str::to_string),
3809            sql_query: "SELECT 1".to_string(),
3810        };
3811        assert_eq!(
3812            params(None, None).unified_placement().unwrap(),
3813            Placement::SessionDefault
3814        );
3815        assert!(matches!(
3816            params(None, Some("r1")).unified_placement(),
3817            Err(McpRequestError::QueryValidationFailed(_))
3818        ));
3819        assert_eq!(
3820            params(Some("c"), Some("r1")).unified_placement().unwrap(),
3821            Placement::Replica {
3822                cluster: "c",
3823                replica: "r1"
3824            }
3825        );
3826    }
3827
3828    #[mz_ore::test]
3829    fn test_list_data_products_is_get_data_products() {
3830        for name in ["list_data_products", "get_data_products"] {
3831            let req: McpRequest = serde_json::from_value(json!({
3832                "jsonrpc": "2.0",
3833                "id": 1,
3834                "method": "tools/call",
3835                "params": {"name": name},
3836            }))
3837            .unwrap();
3838            let McpMethod::ToolsCall(params) = req.method else {
3839                panic!("expected tools/call for {name}");
3840            };
3841            assert_eq!(
3842                params.route_name(McpEndpointType::Agent),
3843                "get_data_products",
3844                "agent metric label for {name}"
3845            );
3846            assert_eq!(
3847                params.route_name(McpEndpointType::Unified),
3848                "list_data_products",
3849                "unified metric label for {name}"
3850            );
3851        }
3852    }
3853
3854    #[mz_ore::test]
3855    fn test_developer_placement() {
3856        let params = |cluster: Option<&str>, replica: Option<&str>| QueryParams {
3857            cluster: cluster.map(str::to_string),
3858            cluster_replica: replica.map(str::to_string),
3859            sql_query: "SELECT 1".to_string(),
3860        };
3861        assert!(matches!(
3862            params(None, Some("r1")).developer_placement(),
3863            Err(McpRequestError::QueryValidationFailed(_))
3864        ));
3865        assert_eq!(
3866            params(Some("c"), None).developer_placement().unwrap(),
3867            Placement::Cluster("c")
3868        );
3869        assert_eq!(
3870            params(Some("c"), Some("r1")).developer_placement().unwrap(),
3871            Placement::Replica {
3872                cluster: "c",
3873                replica: "r1"
3874            }
3875        );
3876    }
3877
3878    /// The read is wrapped in a `BEGIN READ ONLY` transaction so the
3879    /// `SET CLUSTER` scope is bounded to this read and does not leak
3880    /// into the rest of the session.
3881    #[mz_ore::test]
3882    fn test_build_read_query_with_cluster() {
3883        let sql = build_read_query(
3884            "\"db\".\"sch\".\"v\"",
3885            50,
3886            Placement::Cluster("prod_cluster"),
3887        );
3888        assert!(sql.contains("BEGIN READ ONLY"), "{sql}");
3889        assert!(sql.contains("SET CLUSTER = 'prod_cluster'"), "{sql}");
3890        assert!(
3891            sql.contains("SELECT * FROM \"db\".\"sch\".\"v\" LIMIT 50"),
3892            "{sql}",
3893        );
3894        assert!(sql.contains("COMMIT"), "{sql}");
3895    }
3896
3897    /// With no cluster (the role lacks USAGE on the object's cluster, DEX-66),
3898    /// the read omits `SET CLUSTER` and runs on the session's serving cluster.
3899    #[mz_ore::test]
3900    fn test_build_read_query_without_cluster() {
3901        let sql = build_read_query("\"db\".\"sch\".\"v\"", 50, Placement::SessionDefault);
3902        assert!(sql.contains("BEGIN READ ONLY"), "{sql}");
3903        assert!(!sql.contains("SET CLUSTER"), "{sql}");
3904        assert!(
3905            sql.contains("SELECT * FROM \"db\".\"sch\".\"v\" LIMIT 50"),
3906            "{sql}",
3907        );
3908        assert!(sql.contains("COMMIT"), "{sql}");
3909    }
3910
3911    /// Cluster names with single quotes and backslashes must be escaped
3912    /// the same way as the `name` argument, since they end up interpolated
3913    /// into a SQL string literal. Defends against catalog-injection or
3914    /// adversarial cluster names.
3915    #[mz_ore::test]
3916    fn test_build_read_query_escapes_cluster_name() {
3917        let sql = build_read_query(
3918            "\"db\".\"sch\".\"v\"",
3919            10,
3920            Placement::Cluster("evil'; DROP TABLE secrets; --"),
3921        );
3922        // The single quote in `evil'` must be doubled inside the literal.
3923        assert!(
3924            sql.contains("SET CLUSTER = 'evil''; DROP TABLE secrets; --'"),
3925            "single quote should be doubled inside the literal: {sql}",
3926        );
3927        // The injected `DROP TABLE` must remain inside the literal, so there is
3928        // no second statement that escapes the SET CLUSTER call.
3929        assert_eq!(
3930            sql.matches("SET CLUSTER").count(),
3931            1,
3932            "exactly one SET CLUSTER statement: {sql}",
3933        );
3934        assert_eq!(
3935            sql.matches("DROP TABLE").count(),
3936            1,
3937            "DROP TABLE should appear once, inside the quoted literal: {sql}",
3938        );
3939    }
3940
3941    #[mz_ore::test]
3942    fn test_mcp_error_codes() {
3943        assert_eq!(
3944            McpRequestError::InvalidJsonRpcVersion.error_code(),
3945            error_codes::INVALID_REQUEST
3946        );
3947        assert_eq!(
3948            McpRequestError::MethodNotFound("test".to_string()).error_code(),
3949            error_codes::METHOD_NOT_FOUND
3950        );
3951        assert_eq!(
3952            McpRequestError::QueryExecutionFailed("test".to_string()).error_code(),
3953            error_codes::INTERNAL_ERROR
3954        );
3955        assert_eq!(
3956            McpRequestError::HeaderMismatch("test".to_string()).error_code(),
3957            error_codes::HEADER_MISMATCH
3958        );
3959    }
3960
3961    #[mz_ore::test]
3962    fn test_request_meta_check() {
3963        let params = |body: &str| {
3964            RawRequest::parse(body.as_bytes())
3965                .expect("an object")
3966                .params
3967        };
3968        let check =
3969            |body: &str| check_request_meta(params(body).as_ref()).map_err(|e| e.error_code());
3970        let with_meta = |meta: &str| {
3971            format!(
3972                r#"{{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{{"_meta":{meta}}}}}"#
3973            )
3974        };
3975        assert_eq!(
3976            check(&with_meta(
3977                r#"{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}"#
3978            )),
3979            Ok(())
3980        );
3981        for (meta, want) in [
3982            (
3983                r#"{"io.modelcontextprotocol/clientCapabilities":{}}"#,
3984                error_codes::INVALID_PARAMS,
3985            ),
3986            (
3987                r#"{"io.modelcontextprotocol/protocolVersion":7,"io.modelcontextprotocol/clientCapabilities":{}}"#,
3988                error_codes::INVALID_PARAMS,
3989            ),
3990            (
3991                r#"{"io.modelcontextprotocol/protocolVersion":"2025-11-25","io.modelcontextprotocol/clientCapabilities":{}}"#,
3992                error_codes::HEADER_MISMATCH,
3993            ),
3994            (
3995                r#"{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}"#,
3996                error_codes::INVALID_PARAMS,
3997            ),
3998            (
3999                r#"{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":[]}"#,
4000                error_codes::INVALID_PARAMS,
4001            ),
4002        ] {
4003            assert_eq!(check(&with_meta(meta)), Err(want), "for {meta}");
4004        }
4005        let message = |body: &str| {
4006            check_request_meta(params(body).as_ref())
4007                .expect_err("must be rejected")
4008                .to_string()
4009        };
4010        assert!(
4011            message(&with_meta(
4012                r#"{"io.modelcontextprotocol/protocolVersion":7}"#
4013            ))
4014            .ends_with("must be a string")
4015        );
4016        assert!(message(&with_meta("[]")).ends_with("params._meta must be an object"));
4017        assert_eq!(
4018            check(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#),
4019            Err(error_codes::INVALID_PARAMS)
4020        );
4021    }
4022
4023    #[mz_ore::test]
4024    fn test_header_check_rejects_non_ascii() {
4025        let headers = McpHeaders {
4026            protocol_version: vec![HeaderValue::from_static(
4027                ProtocolVersion::V2026_07_28.as_str(),
4028            )],
4029            method: vec![HeaderValue::from_bytes(b"tools/list\xff").expect("valid header bytes")],
4030            name: vec![],
4031        };
4032        let err = headers
4033            .check("tools/list", ToolName::NotToolsCall)
4034            .expect_err("non-ASCII Mcp-Method");
4035        assert_eq!(err.error_code(), error_codes::HEADER_MISMATCH);
4036    }
4037}