Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
feat(mcp): serve protocol revision 2026-07-28 without initialize
Kam65deac529041
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex eb044d51..11ce9759 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -85,6 +85,13 @@run talks to it; the two answers then differed everywhere and the case was saved as `[..]`,which accepts any one-line body. A body that is random by design records with`--normalize name=regex` for the part that changes (#1268, reported by @AyhamJo7).+- The MCP server (`rust-anything mcp`) speaks protocol revision 2026-07-28 alongside the+ `initialize` handshake. It answers `server/discover` with the versions it supports, and a+ request that carries `io.modelcontextprotocol/protocolVersion` in `_meta` is served without+ `initialize`: its result has `resultType`, the server's name in `_meta`, and `ttlMs` and+ `cacheScope` on lists. A version it does not speak gets error `-32022` with the supported+ versions, and a missing `_meta` field gets `-32602`. Clients that send `initialize` still+ negotiate 2025-06-18, 2025-03-26 or 2024-11-05 as before (#1247, reported by @bbudiono).- Ruby: a crate bridged without `--batch` passes `gate`'s clippy check. The generated `src/lib.rs`imported magnus's `Object` and `method`, which only the batch classes use, so clippy with`-D warnings` failed on `unused imports: Object and method` in generated code the port's authordiff --git a/src/mcp.rs b/src/mcp.rsindex bd8ef715..2e3a5d54 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -1,8 +1,10 @@//! MCP server over stdio: every step as a tool, for any agent.//!//! Newline-delimited JSON-RPC 2.0, as the MCP stdio transport specifies. The protocol surface-//! is small (initialize, tools/list, tools/call, prompts/list, prompts/get, ping, progress and-//! cancellation), so it is implemented directly on serde_json instead of pulling in an SDK.+//! is small (initialize, server/discover, tools/list, tools/call, prompts/list, prompts/get, ping,+//! progress and cancellation), so it is implemented directly on serde_json instead of pulling in+//! an SDK. Clients of 2026-07-28 send no `initialize`: each request carries its version in+//! `_meta`, and its result says `resultType` and names the server.//!//! Each tools/call runs on its own thread, so ping and notifications/cancelled are answered//! while a long call runs; one writer thread owns stdout and writes whole lines. A cancelled@@ -25,6 +27,16 @@ use crate::{analyze, app, bridge, front_door, gate, harness, lift, obligations,const PROTOCOL_VERSION: &str = "2025-06-18";const SUPPORTED_PROTOCOL_VERSIONS: &[&str] = &[PROTOCOL_VERSION, "2025-03-26", "2024-11-05"];+/// The revision without `initialize`, whose requests carry the version in `_meta`.+const STATELESS_PROTOCOL_VERSION: &str = "2026-07-28";+const VERSION_KEY: &str = "io.modelcontextprotocol/protocolVersion";+const CAPABILITIES_KEY: &str = "io.modelcontextprotocol/clientCapabilities";+const SERVER_INFO_KEY: &str = "io.modelcontextprotocol/serverInfo";+const INSTRUCTIONS: &str = "Rewrite TypeScript/JavaScript, Python, C, Go, Ruby, Java, Kotlin, PHP, C#, \+ PowerShell or Swift apps in Rust, one verified piece at a time. Loop per unit: analyze -> bridge -> \+ record -> (port src/port.rs) -> build -> diff -> shadow (skip for PHP, C#, PowerShell, \+ and Swift) -> gate. Never mark a port done before gate passes. Read rust/RULES.md (`rules`) \+ before porting; when the user corrects behavior, add it with `rules`.";pub fn serve() -> Result<()> {serve_io(std::io::stdin().lock(), std::io::stdout())@@ -341,25 +353,27 @@ pub fn handle(request: &Value) -> Option<Value> {let id = request.get("id").cloned();let method = request["method"].as_str().unwrap_or_default();let id = id?;+ let meta = &request["params"]["_meta"];+ let stateless =+ method != "initialize" && (method == "server/discover" || meta.get(VERSION_KEY).is_some());+ if stateless && let Some(refusal) = stateless_refusal(&id, meta) {+ return Some(refusal);+ }let result = match method {"initialize" => json!({"protocolVersion": request["params"]["protocolVersion"].as_str().filter(|v| SUPPORTED_PROTOCOL_VERSIONS.contains(v)).unwrap_or(PROTOCOL_VERSION),- "capabilities": {- "tools": {},- "prompts": {},- "resources": {},- "extensions": { "io.modelcontextprotocol/skills": {} },- },- "serverInfo": { "name": "rust-anything", "version": env!("CARGO_PKG_VERSION") },- "instructions": "Rewrite TypeScript/JavaScript, Python, C, Go, Ruby, Java, Kotlin, PHP, C#, \- PowerShell or Swift apps in Rust, one verified piece at a time. Loop per unit: analyze -> bridge -> \- record -> (port src/port.rs) -> build -> diff -> shadow (skip for PHP, C#, PowerShell, \- and Swift) -> gate. Never mark a port done before gate passes. Read rust/RULES.md (`rules`) \- before porting; when the user corrects behavior, add it with `rules`.",+ "capabilities": capabilities(),+ "serverInfo": server_info(),+ "instructions": INSTRUCTIONS,}),+ "server/discover" => fresh(json!({+ "supportedVersions": supported_versions(),+ "capabilities": capabilities(),+ "instructions": INSTRUCTIONS,+ })),"ping" => json!({}),"tools/list" => json!({ "tools": tools() }),"tools/call" => {@@ -409,7 +423,8 @@ pub fn handle(request: &Value) -> Option<Value> {.strip_prefix(SKILL_ROOT).and_then(|file| crate::setup::SKILL_FILES.iter().find(|(f, _)| *f == file))else {- return Some(error(id, -32002, &format!("resource not found: `{uri}`")));+ let code = if stateless { -32602 } else { -32002 };+ return Some(error(id, code, &format!("resource not found: `{uri}`")));};fresh(json!({ "contents": [{ "uri": uri, "mimeType": "text/markdown", "text": text }] }),@@ -417,13 +432,84 @@ pub fn handle(request: &Value) -> Option<Value> {}_ => return Some(error(id, -32601, &format!("unknown method `{method}`"))),};+ let result = if stateless {+ stateless_result(method, result)+ } else {+ result+ };Some(json!({ "jsonrpc": "2.0", "id": id, "result": result }))}+fn capabilities() -> Value {+ json!({+ "tools": {},+ "prompts": {},+ "resources": {},+ "extensions": { "io.modelcontextprotocol/skills": {} },+ })+}++fn server_info() -> Value {+ json!({ "name": "rust-anything", "version": env!("CARGO_PKG_VERSION") })+}++/// Every version this server speaks, the stateless one first.+fn supported_versions() -> Vec<&'static str> {+ std::iter::once(STATELESS_PROTOCOL_VERSION)+ .chain(SUPPORTED_PROTOCOL_VERSIONS.iter().copied())+ .collect()+}++/// The error for a stateless request whose `_meta` lacks a field 2026-07-28 requires (`-32602`)+/// or names a version this server does not speak (`-32022`, with the versions it does).+fn stateless_refusal(id: &Value, meta: &Value) -> Option<Value> {+ let Some(version) = meta[VERSION_KEY].as_str() else {+ return Some(error(+ id.clone(),+ -32602,+ &format!("`params._meta` has no `{VERSION_KEY}` string"),+ ));+ };+ if !meta[CAPABILITIES_KEY].is_object() {+ return Some(error(+ id.clone(),+ -32602,+ &format!("`params._meta` has no `{CAPABILITIES_KEY}` object"),+ ));+ }+ let supported = supported_versions();+ if supported.contains(&version) {+ return None;+ }+ Some(json!({+ "jsonrpc": "2.0",+ "id": id,+ "error": {+ "code": -32022,+ "message": "Unsupported protocol version",+ "data": { "supported": supported, "requested": version },+ },+ }))+}++/// A stateless request's result: `resultType`, the server's name in `_meta`, and the cache+/// fields on the results 2026-07-28 lets a client cache.+fn stateless_result(method: &str, mut result: Value) -> Value {+ if matches!(+ method,+ "tools/list" | "prompts/list" | "resources/list" | "resources/read"+ ) {+ result = fresh(result);+ }+ result["resultType"] = json!("complete");+ result["_meta"][SERVER_INFO_KEY] = server_info();+ result+}+/// Where the workflow skill's files live for the MCP skills extension.const SKILL_ROOT: &str = "skill://rust-anything/";-/// A skills-extension result with the cache fields it requires.+/// A result with the cache fields the skills extension and 2026-07-28 require.fn fresh(mut result: Value) -> Value {result["resultType"] = json!("complete");result["ttlMs"] = json!(300_000);@@ -2521,6 +2607,100 @@ mod tests {assert_eq!(init(json!({ "protocolVersion": 42 })), PROTOCOL_VERSION);}+ fn stateless_meta() -> Value {+ json!({+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",+ "io.modelcontextprotocol/clientInfo": { "name": "test", "version": "0" },+ "io.modelcontextprotocol/clientCapabilities": {},+ })+ }++ #[test]+ fn stateless_clients_list_and_call_tools_without_initialize() {+ let input = [+ json!({ "jsonrpc": "2.0", "id": 1, "method": "server/discover",+ "params": { "_meta": stateless_meta() } }),+ json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/list",+ "params": { "_meta": stateless_meta() } }),+ json!({ "jsonrpc": "2.0", "id": 3, "method": "tools/call",+ "params": { "name": "gate", "arguments": {}, "_meta": stateless_meta() } }),+ ]+ .iter()+ .map(|m| format!("{m}\n"))+ .collect::<String>();+ let out = Shared::default();+ serve_io(std::io::Cursor::new(input), out.clone()).unwrap();+ let text = String::from_utf8(lock(&out.0).clone()).unwrap();+ let messages: Vec<Value> = text+ .lines()+ .map(|l| serde_json::from_str(l).unwrap())+ .collect();+ let result = |id: i64| {+ messages+ .iter()+ .find(|m| m["id"] == id)+ .unwrap_or_else(|| panic!("no answer to {id}: {text}"))["result"]+ .clone()+ };+ let discover = result(1);+ assert_eq!(+ discover["supportedVersions"],+ json!(["2026-07-28", "2025-06-18", "2025-03-26", "2024-11-05"])+ );+ assert_eq!(discover["capabilities"]["tools"], json!({}));+ assert!(discover["instructions"].is_string(), "{discover}");+ let list = result(2);+ assert_eq!(+ list["tools"].as_array().map(Vec::len),+ Some(TOOL_META.len())+ );+ let call = result(3);+ assert_eq!(call["isError"], true, "{call}");+ assert_eq!(call["structuredContent"]["code"], "invalid_arguments");+ for (id, cached) in [(1, true), (2, true), (3, false)] {+ let r = result(id);+ assert_eq!(r["resultType"], "complete", "{r}");+ assert_eq!(+ r["_meta"]["io.modelcontextprotocol/serverInfo"]["name"],+ "rust-anything"+ );+ assert_eq!(r["ttlMs"].is_u64(), cached, "{r}");+ assert_eq!(r["cacheScope"].is_string(), cached, "{r}");+ }+ }++ #[test]+ fn stateless_requests_with_a_bad_meta_are_refused_and_initialize_stays_legacy() {+ let ask = |method: &str, meta: Value| {+ handle(&json!({ "jsonrpc": "2.0", "id": 7, "method": method,+ "params": { "uri": "skill://rust-anything/nope.md", "_meta": meta } }))+ .unwrap()+ };+ let mut old = stateless_meta();+ old["io.modelcontextprotocol/protocolVersion"] = json!("1900-01-01");+ let refused = ask("tools/list", old);+ assert_eq!(refused["error"]["code"], -32022, "{refused}");+ assert_eq!(refused["error"]["data"]["requested"], "1900-01-01");+ assert_eq!(refused["error"]["data"]["supported"][0], "2026-07-28");+ let mut bare = stateless_meta();+ bare.as_object_mut()+ .unwrap()+ .remove("io.modelcontextprotocol/clientCapabilities");+ assert_eq!(ask("tools/list", bare)["error"]["code"], -32602);+ assert_eq!(ask("server/discover", json!({}))["error"]["code"], -32602);+ assert_eq!(+ ask("resources/read", stateless_meta())["error"]["code"],+ -32602+ );+ assert_eq!(ask("resources/read", json!({}))["error"]["code"], -32002);+ let legacy = handle(&json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" })).unwrap();+ assert!(legacy["result"].get("_meta").is_none(), "{legacy}");+ let init = handle(&json!({ "jsonrpc": "2.0", "id": 1, "method": "initialize",+ "params": { "protocolVersion": "2026-07-28", "_meta": stateless_meta() } }))+ .unwrap();+ assert_eq!(init["result"]["protocolVersion"], PROTOCOL_VERSION);+ }+#[test]fn tools_carry_annotations() {let list = handle(&json!({ "jsonrpc": "2.0", "id": 1, "method": "tools/list" })).unwrap();