Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions crates/openshell-supervisor-network/src/l7/mcp.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,67 @@ impl std::fmt::Display for McpProtocolVersionError {

impl std::error::Error for McpProtocolVersionError {}

/// JSON-RPC error code for a request the endpoint refuses by revision.
pub(super) const JSONRPC_INVALID_REQUEST: i64 = -32600;
/// JSON-RPC error code for a request the endpoint refuses by method.
pub(super) const JSONRPC_METHOD_NOT_FOUND: i64 = -32601;

/// How a policy refusal of an MCP JSON-RPC message is answered on the wire.
///
/// An HTTP 401 or 403 reads as an authorization challenge to MCP clients, so
/// a refusal travels as a JSON-RPC error (HTTP 200) for requests and as an
/// HTTP 202 acknowledgement for notifications, which have no response.
#[derive(Debug, Clone, PartialEq)]
pub(super) enum McpRefusalAnswer {
/// JSON-RPC error response (one object, or an array for a batch).
Error(serde_json::Value),
/// The message carried only notifications: acknowledge without a body.
Accepted,
}

/// Build the answer for a refused MCP message, or `None` when the body is not
/// a JSON-RPC message (the caller keeps its HTTP answer).
pub(super) fn refusal_answer(
request: &L7Request,
code: i64,
message: &str,
data: Option<&serde_json::Value>,
) -> Option<McpRefusalAnswer> {
// Only a POST carries an MCP message; any other method keeps its HTTP answer.
if request.action != "POST" {
return None;
}
let header_end = request
.raw_header
.windows(4)
.position(|window| window == b"\r\n\r\n")?
+ 4;
let body: serde_json::Value = serde_json::from_slice(&request.raw_header[header_end..]).ok()?;
let error_for = |message_value: &serde_json::Value| -> Option<serde_json::Value> {
message_value.get("method")?;
let id = message_value.get("id")?;
let mut error = serde_json::json!({ "code": code, "message": message });
if let Some(data) = data {
error["data"] = data.clone();
}
Some(serde_json::json!({ "jsonrpc": "2.0", "id": id, "error": error }))
};
match &body {
serde_json::Value::Object(_) => {
Some(error_for(&body).map_or(McpRefusalAnswer::Accepted, McpRefusalAnswer::Error))
}
serde_json::Value::Array(items) if !items.is_empty() => {
let errors: Vec<_> = items.iter().filter_map(error_for).collect();
Some(if errors.is_empty() {
McpRefusalAnswer::Accepted
} else {
McpRefusalAnswer::Error(serde_json::Value::Array(errors))
})
}
_ => None,
}
}

/// Describe how the request selected its MCP revision.
///
/// Initial and post-middleware inspection supply their current request so the
Expand Down
Loading
Loading