mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-16 23:42:27 +00:00
Support configurable legacy MCP sessions and envelopes
This commit is contained in:
1 parent
811b386e89
commit
2c9903ca1d
2 files changed
+129
-3
No files matched your search
@@ -195,3 +195,61 @@ where
|
||||
let responses: Vec<_> = batch.iter().filter_map(|v| one(v, limits, &mut on_request, &mut on_notification)).collect();
|
||||
Ok((!responses.is_empty()).then_some(Value::Array(responses)))
|
||||
}
|
||||
/// Process a permissive legacy JSON-RPC envelope. This mode accepts arbitrary IDs and
|
||||
/// parameter shapes, ignores response envelopes, and retains legacy diagnostic messages.
|
||||
/// The caller supplies dispatch and notification callbacks, and should bound transport input.
|
||||
pub fn process_legacy<F, N>(value: &Value, mut on_request: F, mut on_notification: N) -> Option<Value>
|
||||
where
|
||||
F: FnMut(Request<'_>) -> Result<Value, RpcError>,
|
||||
N: FnMut(Request<'_>),
|
||||
{
|
||||
fn one<F, N>(value: &Value, on_request: &mut F, on_notification: &mut N) -> Option<Value>
|
||||
where
|
||||
F: FnMut(Request<'_>) -> Result<Value, RpcError>,
|
||||
N: FnMut(Request<'_>),
|
||||
{
|
||||
let Some(object) = value.as_object() else { return Some(error_response(Value::Null, RpcError::new(-32600, "message must be an object"))) };
|
||||
let id = object.get("id");
|
||||
let Some(method) = object.get("method").and_then(Value::as_str) else {
|
||||
if object.contains_key("result") || object.contains_key("error") {
|
||||
return None;
|
||||
}
|
||||
return Some(error_response(id.cloned().unwrap_or(Value::Null), RpcError::new(-32600, "missing `method`")));
|
||||
};
|
||||
let request = Request { id, method, params: object.get("params") };
|
||||
let Some(id) = id else {
|
||||
on_notification(request);
|
||||
return None;
|
||||
};
|
||||
Some(match on_request(request) {
|
||||
Ok(result) => json!({"jsonrpc": "2.0", "id": id, "result": result}),
|
||||
Err(error) => error_response(id.clone(), error),
|
||||
})
|
||||
}
|
||||
if let Some(batch) = value.as_array() {
|
||||
if batch.is_empty() {
|
||||
return Some(error_response(Value::Null, RpcError::new(-32600, "empty batch")));
|
||||
}
|
||||
let replies: Vec<_> = batch.iter().filter_map(|v| one(v, &mut on_request, &mut on_notification)).collect();
|
||||
(!replies.is_empty()).then_some(Value::Array(replies))
|
||||
} else {
|
||||
one(value, &mut on_request, &mut on_notification)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod legacy_tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn preserves_legacy_batch_routing_and_errors() {
|
||||
let input = json!([{"id": [1], "method":"echo", "params":5}, {"method":"notice"}, {"result":1}, {}, 7]);
|
||||
let seen = std::cell::Cell::new(false);
|
||||
let result = process_legacy(&input, |r| Ok(r.params.cloned().unwrap_or(Value::Null)), |_| seen.set(true)).unwrap();
|
||||
assert!(seen.get());
|
||||
assert_eq!(
|
||||
result,
|
||||
json!([{"jsonrpc":"2.0","id":[1],"result":5}, {"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"missing `method`"}}, {"jsonrpc":"2.0","id":null,"error":{"code":-32600,"message":"message must be an object"}}])
|
||||
);
|
||||
assert_eq!(process_legacy(&json!([]), |_| Ok(Value::Null), |_| {}).unwrap()["error"]["message"], "empty batch");
|
||||
}
|
||||
}
|
||||
+71
-3
@@ -34,11 +34,27 @@ pub struct Session {
|
||||
policy: Policy,
|
||||
state: State,
|
||||
capabilities: Value,
|
||||
versions: Vec<String>,
|
||||
permissive_initialize: bool,
|
||||
server_info: Option<Value>,
|
||||
instructions: Option<String>,
|
||||
initialized: bool,
|
||||
}
|
||||
|
||||
impl Session {
|
||||
pub fn new(name: impl Into<String>, version: impl Into<String>, policy: Policy) -> Self {
|
||||
Self { name: name.into(), version: version.into(), policy, state: State::New, capabilities: json!({"tools": {}}) }
|
||||
Self {
|
||||
name: name.into(),
|
||||
version: version.into(),
|
||||
policy,
|
||||
state: State::New,
|
||||
capabilities: json!({"tools": {}}),
|
||||
versions: vec![PROTOCOL_VERSION.into()],
|
||||
permissive_initialize: false,
|
||||
server_info: None,
|
||||
instructions: None,
|
||||
initialized: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Set the server capabilities returned at initialization. The value must be an object.
|
||||
@@ -50,6 +66,27 @@ impl Session {
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Configure a permissive legacy server: absent or malformed initialize parameters are
|
||||
/// accepted, supported client versions are echoed, and unknown versions use the first entry.
|
||||
pub fn with_legacy_initialize(mut self, versions: &[&str], server_info: Value) -> Self {
|
||||
if !versions.is_empty() {
|
||||
self.versions = versions.iter().map(|v| (*v).to_owned()).collect();
|
||||
}
|
||||
self.permissive_initialize = true;
|
||||
self.server_info = Some(server_info);
|
||||
self
|
||||
}
|
||||
|
||||
/// Update connection-specific instructions returned by subsequent initialize requests.
|
||||
pub fn set_instructions(&mut self, instructions: String) {
|
||||
self.instructions = Some(instructions);
|
||||
}
|
||||
|
||||
/// Whether an initialized notification has been observed, including before initialize.
|
||||
pub fn is_initialized(&self) -> bool {
|
||||
self.initialized
|
||||
}
|
||||
|
||||
pub fn state(&self) -> State {
|
||||
self.state
|
||||
}
|
||||
@@ -64,6 +101,18 @@ impl Session {
|
||||
if self.policy == Policy::Strict && (in_batch || self.state != State::New) {
|
||||
return Some(Err(RpcError::new(-32600, "Invalid Request")));
|
||||
}
|
||||
if self.permissive_initialize {
|
||||
let asked = request.params.and_then(|p| p.get("protocolVersion")).and_then(Value::as_str);
|
||||
let version = asked
|
||||
.filter(|v| self.versions.iter().any(|supported| supported == v))
|
||||
.unwrap_or_else(|| self.versions.first().map(String::as_str).unwrap_or(PROTOCOL_VERSION));
|
||||
let mut result = json!({"protocolVersion": version, "capabilities": self.capabilities, "serverInfo": self.server_info});
|
||||
if let Some(instructions) = &self.instructions {
|
||||
result["instructions"] = json!(instructions);
|
||||
}
|
||||
self.state = State::AwaitingInitialized;
|
||||
return Some(Ok(result));
|
||||
}
|
||||
let Some(params) = request.params.and_then(Value::as_object) else {
|
||||
return Some(Err(invalid_initialize()));
|
||||
};
|
||||
@@ -89,8 +138,11 @@ impl Session {
|
||||
|
||||
/// Observe a JSON-RPC notification; notifications never receive replies.
|
||||
pub fn notification(&mut self, request: Request<'_>) {
|
||||
if request.method == "notifications/initialized" && self.state == State::AwaitingInitialized {
|
||||
self.state = State::Ready;
|
||||
if request.method == "notifications/initialized" {
|
||||
self.initialized = true;
|
||||
if self.state == State::AwaitingInitialized {
|
||||
self.state = State::Ready;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -127,6 +179,22 @@ mod tests {
|
||||
Request { id: None, method, params }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn legacy_initialization_negotiates_and_accepts_missing_parameters() {
|
||||
let mut s = Session::new("test", "1", Policy::Compatible).with_legacy_initialize(&["new", "old"], json!({"name":"custom", "title":"Title"}));
|
||||
s.notification(call("notifications/initialized", None));
|
||||
assert!(s.is_initialized());
|
||||
s.set_instructions("help".into());
|
||||
for (params, expected) in
|
||||
[(None, "new"), (Some(json!({"protocolVersion":"old"})), "old"), (Some(json!({"protocolVersion":"unknown"})), "new")]
|
||||
{
|
||||
let result = s.request(call("initialize", params.as_ref()), false).unwrap().unwrap();
|
||||
assert_eq!(result["protocolVersion"], expected);
|
||||
assert_eq!(result["serverInfo"]["title"], "Title");
|
||||
assert_eq!(result["instructions"], "help");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn compatible_negotiation_preserves_existing_clients() {
|
||||
let mut s = Session::new("test", "1", Policy::Compatible);
|
||||
|
||||
Reference in new issue
Block a user