Skip to content

Commit 0ac67f2

Browse files
committed
mcp: check params._meta on 2026-07-28 requests (DEX-81, DEX-80)
1 parent 8ce3ed7 commit 0ac67f2

2 files changed

Lines changed: 203 additions & 18 deletions

File tree

‎src/environmentd/src/http/mcp.rs‎

Lines changed: 154 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ const JSONRPC_VERSION: &str = "2.0";
6767

6868
/// MCP protocol version returned in the `initialize` response.
6969
/// Spec: <https://modelcontextprotocol.io/specification/2025-11-25>
70-
const MCP_PROTOCOL_VERSION: &str = "2025-11-25";
70+
const MCP_PROTOCOL_VERSION: &str = ProtocolVersion::V2025_11_25.as_str();
7171

7272
/// The protocol revision a request is served on.
7373
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -95,20 +95,84 @@ impl ProtocolVersion {
9595
let names_2026_07_28 = values
9696
.iter()
9797
.flat_map(|value| value.as_bytes().split(|byte| *byte == b','))
98-
.any(|version| version.trim_ascii() == b"2026-07-28");
98+
.any(|version| version.trim_ascii() == Self::V2026_07_28.as_str().as_bytes());
9999
if names_2026_07_28 && modern_enabled {
100100
Self::V2026_07_28
101101
} else {
102102
Self::V2025_11_25
103103
}
104104
}
105105

106-
/// Whether clients mirror body fields into `Mcp-Method` and `Mcp-Name`.
107-
fn mirrors_body_in_headers(self) -> bool {
106+
const fn as_str(self) -> &'static str {
107+
match self {
108+
Self::V2025_11_25 => "2025-11-25",
109+
Self::V2026_07_28 => "2026-07-28",
110+
}
111+
}
112+
113+
/// Whether this is a modern revision, the spec's term for 2026-07-28 and
114+
/// later: no handshake, and each request carries its version and client
115+
/// capabilities in `params._meta`, with the method and tool name mirrored in
116+
/// headers.
117+
fn is_modern(self) -> bool {
108118
matches!(self, Self::V2026_07_28)
109119
}
110120
}
111121

122+
/// The body read as untyped JSON, for the 2026-07-28 checks on fields the typed
123+
/// parse drops. Only 2026-07-28 requests pay for the second read.
124+
#[derive(Debug, Default, Deserialize)]
125+
struct RawRequest {
126+
params: Option<serde_json::Value>,
127+
}
128+
129+
impl RawRequest {
130+
/// `None` when the body is not a JSON object.
131+
fn parse(body: &[u8]) -> Option<Self> {
132+
serde_json::from_slice(body).ok()
133+
}
134+
}
135+
136+
/// Checks the `params._meta` fields every 2026-07-28 request must carry: the
137+
/// protocol version, matching its header, and the client capabilities.
138+
fn check_request_meta(params: Option<&serde_json::Value>) -> Result<(), McpRequestError> {
139+
let invalid = |message: String| McpRequestError::InvalidParams(message);
140+
let meta = match params.and_then(|params| params.get("_meta")) {
141+
None => return Err(invalid("missing params._meta".into())),
142+
Some(serde_json::Value::Object(meta)) => meta,
143+
Some(_) => return Err(invalid("params._meta must be an object".into())),
144+
};
145+
146+
let version_key = "io.modelcontextprotocol/protocolVersion";
147+
let body_version = match meta.get(version_key) {
148+
None => return Err(invalid(format!("missing {version_key} in params._meta"))),
149+
Some(serde_json::Value::String(version)) => version,
150+
Some(_) => {
151+
return Err(invalid(format!(
152+
"{version_key} in params._meta must be a string"
153+
)));
154+
}
155+
};
156+
// The header check already pinned the header to this version.
157+
let header_version = ProtocolVersion::V2026_07_28.as_str();
158+
if body_version != header_version {
159+
return Err(McpRequestError::HeaderMismatch(format!(
160+
"MCP-Protocol-Version header value '{header_version}' does not match body value '{body_version}'"
161+
)));
162+
}
163+
164+
let capabilities_key = "io.modelcontextprotocol/clientCapabilities";
165+
match meta.get(capabilities_key) {
166+
None => Err(invalid(format!(
167+
"missing {capabilities_key} in params._meta"
168+
))),
169+
Some(serde_json::Value::Object(_)) => Ok(()),
170+
Some(_) => Err(invalid(format!(
171+
"{capabilities_key} in params._meta must be an object"
172+
))),
173+
}
174+
}
175+
112176
/// The request headers the Streamable HTTP transport defines, with every
113177
/// occurrence kept: a repeated header is rejected rather than reduced to one.
114178
struct McpHeaders {
@@ -131,9 +195,10 @@ impl McpHeaders {
131195
/// the body, so a proxy routing on the headers sees what we execute.
132196
fn check_against(&self, method: &McpMethod) -> Result<(), McpRequestError> {
133197
let version = header_text(&self.protocol_version, "MCP-Protocol-Version")?;
134-
if version != "2026-07-28" {
198+
let modern = ProtocolVersion::V2026_07_28.as_str();
199+
if version != modern {
135200
return Err(McpRequestError::HeaderMismatch(format!(
136-
"MCP-Protocol-Version header value '{version}' is not '2026-07-28'"
201+
"MCP-Protocol-Version header value '{version}' is not '{modern}'"
137202
)));
138203
}
139204
let header_method = header_text(&self.method, "Mcp-Method")?;
@@ -215,6 +280,8 @@ enum McpRequestError {
215280
Internal(#[from] anyhow::Error),
216281
#[error("Header mismatch: {0}")]
217282
HeaderMismatch(String),
283+
#[error("Invalid params: {0}")]
284+
InvalidParams(String),
218285
}
219286

220287
impl McpRequestError {
@@ -227,6 +294,7 @@ impl McpRequestError {
227294
Self::QueryValidationFailed(_) => error_codes::INVALID_PARAMS,
228295
Self::QueryExecutionFailed(_) | Self::Internal(_) => error_codes::INTERNAL_ERROR,
229296
Self::HeaderMismatch(_) => error_codes::HEADER_MISMATCH,
297+
Self::InvalidParams(_) => error_codes::INVALID_PARAMS,
230298
}
231299
}
232300

@@ -240,6 +308,7 @@ impl McpRequestError {
240308
Self::QueryExecutionFailed(_) => "ExecutionError",
241309
Self::Internal(_) => "InternalError",
242310
Self::HeaderMismatch(_) => "HeaderMismatch",
311+
Self::InvalidParams(_) => "InvalidParams",
243312
}
244313
}
245314
}
@@ -594,6 +663,7 @@ pub async fn handle_mcp_agent(
594663
client,
595664
request,
596665
McpHeaders::from_map(&headers),
666+
body,
597667
McpEndpointType::Agent,
598668
metrics,
599669
)
@@ -620,6 +690,7 @@ pub async fn handle_mcp_developer(
620690
client,
621691
request,
622692
McpHeaders::from_map(&headers),
693+
body,
623694
McpEndpointType::Developer,
624695
metrics,
625696
)
@@ -711,6 +782,7 @@ async fn handle_mcp_request(
711782
mut client: AuthedClient,
712783
request: McpRequest,
713784
mcp_headers: McpHeaders,
785+
body: Bytes,
714786
endpoint_type: McpEndpointType,
715787
metrics: McpMetrics,
716788
) -> impl IntoResponse {
@@ -800,19 +872,23 @@ async fn handle_mcp_request(
800872
return StatusCode::ACCEPTED.into_response();
801873
}
802874

875+
let request_id = request.id.clone().unwrap_or(serde_json::Value::Null);
876+
803877
// The transport leaves header rules for notification POSTs undefined, so
804-
// only requests are checked.
805-
if protocol.mirrors_body_in_headers() {
806-
if let Err(err) = mcp_headers.check_against(&request.method) {
878+
// only requests are checked. A failed header or `_meta` check is transport
879+
// validation, so it gets a 400 even where its JSON-RPC code is -32602.
880+
if protocol.is_modern() {
881+
let raw = RawRequest::parse(&body).unwrap_or_default();
882+
let checked = mcp_headers
883+
.check_against(&request.method)
884+
.and_then(|()| check_request_meta(raw.params.as_ref()));
885+
if let Err(err) = checked {
807886
record_request(McpCallStatus::Error(err.error_type()));
808-
let id = request.id.clone().unwrap_or(serde_json::Value::Null);
809-
let response = McpResponse::error(id, err.into());
887+
let response = McpResponse::error(request_id, err.into());
810888
return (StatusCode::BAD_REQUEST, Json(response)).into_response();
811889
}
812890
}
813891

814-
let request_id = request.id.clone().unwrap_or(serde_json::Value::Null);
815-
816892
// Spawn task for fault isolation, with a timeout safety net.
817893
// `abort_on_drop` propagates the timeout to the task itself; without
818894
// it the task orphans and the SQL query keeps running in the
@@ -2953,10 +3029,74 @@ mod tests {
29533029
);
29543030
}
29553031

3032+
#[mz_ore::test]
3033+
fn test_request_meta_check() {
3034+
let params = |body: &str| {
3035+
RawRequest::parse(body.as_bytes())
3036+
.expect("an object")
3037+
.params
3038+
};
3039+
let check =
3040+
|body: &str| check_request_meta(params(body).as_ref()).map_err(|e| e.error_code());
3041+
let with_meta = |meta: &str| {
3042+
format!(
3043+
r#"{{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{{"_meta":{meta}}}}}"#
3044+
)
3045+
};
3046+
assert_eq!(
3047+
check(&with_meta(
3048+
r#"{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}"#
3049+
)),
3050+
Ok(())
3051+
);
3052+
for (meta, want) in [
3053+
(
3054+
r#"{"io.modelcontextprotocol/clientCapabilities":{}}"#,
3055+
error_codes::INVALID_PARAMS,
3056+
),
3057+
(
3058+
r#"{"io.modelcontextprotocol/protocolVersion":7,"io.modelcontextprotocol/clientCapabilities":{}}"#,
3059+
error_codes::INVALID_PARAMS,
3060+
),
3061+
(
3062+
r#"{"io.modelcontextprotocol/protocolVersion":"2025-11-25","io.modelcontextprotocol/clientCapabilities":{}}"#,
3063+
error_codes::HEADER_MISMATCH,
3064+
),
3065+
(
3066+
r#"{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}"#,
3067+
error_codes::INVALID_PARAMS,
3068+
),
3069+
(
3070+
r#"{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":[]}"#,
3071+
error_codes::INVALID_PARAMS,
3072+
),
3073+
] {
3074+
assert_eq!(check(&with_meta(meta)), Err(want), "for {meta}");
3075+
}
3076+
let message = |body: &str| {
3077+
check_request_meta(params(body).as_ref())
3078+
.expect_err("must be rejected")
3079+
.to_string()
3080+
};
3081+
assert!(
3082+
message(&with_meta(
3083+
r#"{"io.modelcontextprotocol/protocolVersion":7}"#
3084+
))
3085+
.ends_with("must be a string")
3086+
);
3087+
assert!(message(&with_meta("[]")).ends_with("params._meta must be an object"));
3088+
assert_eq!(
3089+
check(r#"{"jsonrpc":"2.0","id":1,"method":"tools/list"}"#),
3090+
Err(error_codes::INVALID_PARAMS)
3091+
);
3092+
}
3093+
29563094
#[mz_ore::test]
29573095
fn test_header_check_rejects_non_ascii() {
29583096
let headers = McpHeaders {
2959-
protocol_version: vec![HeaderValue::from_static("2026-07-28")],
3097+
protocol_version: vec![HeaderValue::from_static(
3098+
ProtocolVersion::V2026_07_28.as_str(),
3099+
)],
29603100
method: vec![HeaderValue::from_bytes(b"tools/list\xff").expect("valid header bytes")],
29613101
name: vec![],
29623102
};

‎src/environmentd/tests/testdata/mcp/developer_2026_07_28‎

Lines changed: 49 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ mcp-developer
1818
MCP-Protocol-Version: 2026-07-28
1919
Mcp-Method: tools/call
2020
Mcp-Name: query_system_catalog
21-
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"query_system_catalog","arguments":{"sql_query":"SELECT name FROM mz_databases WHERE name = 'materialize'"}}}
21+
{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"query_system_catalog","arguments":{"sql_query":"SELECT name FROM mz_databases WHERE name = 'materialize'"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
2222
----
2323
200 OK
2424
{"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"[\n [\"materialize\"]\n]"}],"isError":false}}
@@ -29,7 +29,7 @@ mcp-developer
2929
MCP-Protocol-Version: 2026-07-28
3030
Mcp-Method: tools/call
3131
Mcp-Name: =?base64?cXVlcnlfc3lzdGVtX2NhdGFsb2c=?=
32-
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"query_system_catalog","arguments":{"sql_query":"SELECT name FROM mz_databases WHERE name = 'materialize'"}}}
32+
{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"query_system_catalog","arguments":{"sql_query":"SELECT name FROM mz_databases WHERE name = 'materialize'"},"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
3333
----
3434
200 OK
3535
{"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"[\n [\"materialize\"]\n]"}],"isError":false}}
@@ -38,7 +38,7 @@ Mcp-Name: =?base64?cXVlcnlfc3lzdGVtX2NhdGFsb2c=?=
3838
mcp-developer
3939
MCP-Protocol-Version: 2026-07-28
4040
Mcp-Method: tools/list
41-
{"jsonrpc":"2.0","id":27,"method":"tools/list"}
41+
{"jsonrpc":"2.0","id":27,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
4242
----
4343
200 OK
4444
{"jsonrpc":"2.0","id":27,"result":{"tools":[{"name":"query_system_catalog","title":"Query System Catalog","description":"Query Materialize system catalog tables for troubleshooting and observability. Only mz_*, pg_catalog, and information_schema tables are accessible. Use the mz_internal.mz_ontology_* tables to discover tables, columns, and join paths before writing queries. Response limit: 1.0 MB.","inputSchema":{"type":"object","properties":{"sql_query":{"type":"string","description":"PostgreSQL-compatible SELECT, SHOW, or EXPLAIN query referencing mz_*, pg_catalog, or information_schema tables"}},"required":["sql_query"]},"annotations":{"readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}},{"name":"query","title":"Query","description":"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`. Response limit: 1.0 MB.","inputSchema":{"type":"object","properties":{"cluster":{"type":"string","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."},"cluster_replica":{"type":"string","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."},"sql_query":{"type":"string","description":"PostgreSQL-compatible SELECT, SHOW, or EXPLAIN statement. Multi-statement queries are rejected."}},"required":["cluster","sql_query"]},"annotations":{"readOnlyHint":true,"destructiveHint":false,"idempotentHint":true,"openWorldHint":false}}]}}
@@ -150,7 +150,7 @@ Mcp-Method: tools/list
150150
mcp-developer
151151
MCP-Protocol-Version: 2026-07-28
152152
Mcp-Method: server/other
153-
{"jsonrpc":"2.0","id":9,"method":"server/other","params":{}}
153+
{"jsonrpc":"2.0","id":9,"method":"server/other","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}}}}
154154
----
155155
200 OK
156156
{"jsonrpc":"2.0","id":9,"error":{"code":-32601,"message":"Method not found: unknown method","data":{"error_type":"MethodNotFound"}}}
@@ -162,6 +162,51 @@ MCP-Protocol-Version: 2026-07-28
162162
400 Bad Request
163163
{"jsonrpc":"2.0","id":10,"error":{"code":-32020,"message":"Header mismatch: missing Mcp-Method header","data":{"error_type":"HeaderMismatch"}}}
164164

165+
# =============================================================================
166+
# params._meta must carry the protocol version and client capabilities
167+
# =============================================================================
168+
169+
mcp-developer
170+
MCP-Protocol-Version: 2026-07-28
171+
Mcp-Method: tools/list
172+
{"jsonrpc":"2.0","id":11,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/clientCapabilities":{}}}}
173+
----
174+
400 Bad Request
175+
{"jsonrpc":"2.0","id":11,"error":{"code":-32602,"message":"Invalid params: missing io.modelcontextprotocol/protocolVersion in params._meta","data":{"error_type":"InvalidParams"}}}
176+
177+
mcp-developer
178+
MCP-Protocol-Version: 2026-07-28
179+
Mcp-Method: tools/list
180+
{"jsonrpc":"2.0","id":12,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2025-11-25","io.modelcontextprotocol/clientCapabilities":{}}}}
181+
----
182+
400 Bad Request
183+
{"jsonrpc":"2.0","id":12,"error":{"code":-32020,"message":"Header mismatch: MCP-Protocol-Version header value '2026-07-28' does not match body value '2025-11-25'","data":{"error_type":"HeaderMismatch"}}}
184+
185+
mcp-developer
186+
MCP-Protocol-Version: 2026-07-28
187+
Mcp-Method: tools/list
188+
{"jsonrpc":"2.0","id":13,"method":"tools/list","params":{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28"}}}
189+
----
190+
400 Bad Request
191+
{"jsonrpc":"2.0","id":13,"error":{"code":-32602,"message":"Invalid params: missing io.modelcontextprotocol/clientCapabilities in params._meta","data":{"error_type":"InvalidParams"}}}
192+
193+
# A request with no params at all has no _meta.
194+
mcp-developer
195+
MCP-Protocol-Version: 2026-07-28
196+
Mcp-Method: tools/list
197+
{"jsonrpc":"2.0","id":14,"method":"tools/list"}
198+
----
199+
400 Bad Request
200+
{"jsonrpc":"2.0","id":14,"error":{"code":-32602,"message":"Invalid params: missing params._meta","data":{"error_type":"InvalidParams"}}}
201+
202+
# Notifications are not requests, so they carry no required _meta.
203+
mcp-developer
204+
MCP-Protocol-Version: 2026-07-28
205+
Mcp-Method: notifications/initialized
206+
{"jsonrpc":"2.0","method":"notifications/initialized"}
207+
----
208+
202 Accepted
209+
165210
# =============================================================================
166211
# Earlier revisions are never checked
167212
# =============================================================================

0 commit comments

Comments
 (0)