Skip to content

Commit ed716a8

Browse files
executor: MCP stdio server in the rocco binary (#109)
Adds `rocco mcp`: a blocking std stdin/stdout MCP server written from the MCP 2025-06-18 specification on lgwks_std::json. No new crate, no pub item, no rmcp. forge-mcp's Codex-adapted client framing (jsonrpc.rs) is not ported and its 2026-07-28 stateless era is not served. - src/mcp/wire.rs: newline-delimited framing, 1 MiB frame bound enforced while streaming (oversized line discarded unbuffered, answered -32600, server keeps serving), JSON-RPC reply shapes. - src/mcp/mod.rs: initialize/initialized lifecycle with version negotiation, ping, tools/list, tools/call, -32700/-32600/-32601/-32602, notifications and client responses never answered, one frame of pending work, EOF exits 0. - src/mcp/tools.rs: one tool, larry_submit_task (goal, repo, files, acceptance), typed TaskError. A well-formed task is refused with the typed tool error executor_not_connected until the executor lands. - src/bin/rocco.rs dispatches `mcp`; src/main.rs routes diagnostics through one stderr helper (behaviour unchanged). Proof (debug build, local pipe): 513 of 513 nextest tests pass, including tests/sim_mcp_stdio.rs and tests/sim_mcp_protocol.rs (seeded, 24 seeds replayed bit-identically, 100 concurrent sessions with kill -9 of a tenth) and tests/mcp_stdio_journey.rs. tools/list round trips n=3000 p50=52us p95=62us p99=89us; peak RSS 8.2 MB over a 5002-frame scripted session. Backout: revert this commit; rocco without arguments is unchanged. Co-Authored-By: Claude Opus 5.5 <[email protected]> Design-Plan: 0e2e05cad5c39473 (blocking std stdin/stdout loop on lgwks_std::json, modules private to the rocco binary) Cited: modelcontextprotocol/servers#4207 Cited: https://modelcontextprotocol.io/specification/draft/basic/transports/stdio Cited: https://inferensys.com/glossary/tool-calling-and-api-execution/model-context-protocol-mcp/message-framing Cited: https://github.com/JSLEEKR/mcpbench Cited: https://www.claudemap.org/en/guides/mcp-debugging
1 parent cee1aec commit ed716a8

10 files changed

Lines changed: 2065 additions & 22 deletions

File tree

‎INVARIANTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,5 @@ Changing a runtime rule is a specification change, never a refactor.
3838

3939
- Synthetic data stays visibly DEMO and orchestration is never simulated. Why: a demo must not become evidence. Test: `tests/demo.rs`, `tests/e2e_journey.rs`.
4040
- No write leaves the gate without an intent, an authority record and a receipt, for two tenants under kill -9 and replay. Why: the accountable-effect promise is the product. Test: `crates/rocco-runtime/tests/sim_crash_restore.rs`, `crates/rocco-runtime/tests/sim_multitenant.rs`.
41+
- `rocco mcp` answers every stdio frame as MCP 2025-06-18 and JSON-RPC 2.0 say, refuses a frame over 1 MiB without buffering it, holds one frame of pending work, and refuses a typed task with `executor_not_connected` until #85 and #83 land, never a success. Why: an oversized or malformed peer must not grow memory or fake an effect. Test: `tests/sim_mcp_stdio.rs`, `tests/mcp_stdio_journey.rs`.
4142
- Memory waits for Logical-DB; no substitute store. Why: state that outlives a run lives in the estate database. Test: review-only, owner Director, 2026-11-03, until Logical-DB ships the store.

‎src/bin/rocco.rs‎

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,40 @@
1-
//! Native AppCUI launcher. Paints the fixture surface and exits when the
2-
//! operator quits; it performs no backend or workspace effect.
3-
use std::io::Write;
1+
//! Native AppCUI launcher, and `rocco mcp`, the MCP stdio server (larry#84).
2+
//! The launcher paints the fixture surface and exits when the operator
3+
//! quits; it performs no backend or workspace effect.
4+
#[path = "../mcp/mod.rs"]
5+
mod mcp;
46

5-
fn main() -> std::process::ExitCode {
6-
if std::env::args_os().len() != 1 {
7-
if writeln!(
8-
std::io::stderr().lock(),
9-
"DEMO: no arguments supported; F1 opens native help"
10-
)
11-
.is_err()
12-
{
13-
return std::process::ExitCode::FAILURE;
7+
use std::io::{self, Write};
8+
use std::process::ExitCode;
9+
10+
/// Writes one diagnostic line to standard error, never to the protocol stream.
11+
fn diagnose(message: &str) -> io::Result<()> {
12+
let mut stderr = io::stderr().lock();
13+
stderr.write_all(message.as_bytes())?;
14+
stderr.write_all(b"\n")
15+
}
16+
17+
fn main() -> ExitCode {
18+
let mut args = std::env::args_os().skip(1);
19+
let outcome = match (args.next(), args.next()) {
20+
(None, _) => {
21+
rocco_demo::native::run().map_err(|error| format!("DEMO terminal failed: {error}"))
1422
}
15-
return std::process::ExitCode::FAILURE;
16-
}
17-
match rocco_demo::native::run() {
18-
Ok(()) => std::process::ExitCode::SUCCESS,
19-
Err(error) => {
20-
if writeln!(std::io::stderr().lock(), "DEMO terminal failed: {error}").is_err() {
21-
return std::process::ExitCode::FAILURE;
23+
(Some(command), None) if command == "mcp" => {
24+
mcp::serve(io::stdin().lock(), io::stdout().lock())
25+
.map_err(|error| format!("MCP server failed: {error}"))
26+
}
27+
_ => Err(String::from(
28+
"DEMO: no arguments supported except `mcp`; F1 opens native help",
29+
)),
30+
};
31+
match outcome {
32+
Ok(()) => ExitCode::SUCCESS,
33+
Err(message) => {
34+
if diagnose(&message).is_err() {
35+
return ExitCode::FAILURE;
2236
}
23-
std::process::ExitCode::FAILURE
37+
ExitCode::FAILURE
2438
}
2539
}
2640
}

‎src/main.rs‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,26 @@ fn run() -> Result<(), Box<dyn std::error::Error>> {
3535
match demo.command(command) {
3636
Ok(false) => break,
3737
Ok(true) => {}
38-
Err(error) => writeln!(io::stderr().lock(), "{error}")?,
38+
Err(error) => diagnose(&error.to_string())?,
3939
}
4040
writeln!(output, "{}", demo.snapshot()?)?;
4141
output.flush()?;
4242
}
4343
Ok(())
4444
}
4545

46+
/// Writes one diagnostic line to standard error.
47+
fn diagnose(message: &str) -> io::Result<()> {
48+
let mut stderr = io::stderr().lock();
49+
stderr.write_all(message.as_bytes())?;
50+
stderr.write_all(b"\n")
51+
}
52+
4653
fn main() -> std::process::ExitCode {
4754
match run() {
4855
Ok(()) => std::process::ExitCode::SUCCESS,
4956
Err(error) => {
50-
if writeln!(io::stderr().lock(), "DEMO failed: {error}").is_err() {
57+
if diagnose(&format!("DEMO failed: {error}")).is_err() {
5158
return std::process::ExitCode::FAILURE;
5259
}
5360
std::process::ExitCode::FAILURE

‎src/mcp/mod.rs‎

Lines changed: 292 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,292 @@
1+
//! MCP server over stdio, started by `rocco mcp`.
2+
//!
3+
//! Written from the Model Context Protocol specification, revision 2025-06-18:
4+
//! the initialize/initialized lifecycle with version negotiation, `ping`,
5+
//! `tools/list`, `tools/call` and JSON-RPC 2.0 errors, one message per line.
6+
//! The forge-mcp copy this replaces is not the reference: its Codex-adapted
7+
//! client framing is not ported and its 2026-07-28 stateless era is not served.
8+
//!
9+
//! Bounds: a frame over `wire::MAX_FRAME_BYTES` (1 MiB) is discarded as it
10+
//! streams in and answered with `-32600`; the server keeps serving. Pending work
11+
//! is exactly one frame, read, answered, then the next is read, so a slow peer
12+
//! can never queue anything. End of input ends the loop with exit code 0.
13+
14+
mod tools;
15+
mod wire;
16+
17+
use lgwks_std::json::{self, Map, Value, json};
18+
use std::io::{self, BufRead, Write};
19+
20+
/// Newest revision served; the reply to an initialize that names an unknown one.
21+
const LATEST_VERSION: &str = "2025-06-18";
22+
/// Revisions whose lifecycle and `tools/*` shapes this server answers, newest first.
23+
const SUPPORTED_VERSIONS: [&str; 3] = [LATEST_VERSION, "2025-03-26", "2024-11-05"];
24+
/// Reply text for a request that needs a completed initialize.
25+
const NOT_INITIALIZED: &str = "server not initialized: send initialize first";
26+
27+
/// Serves MCP until the reader reaches end of input.
28+
pub(crate) fn serve<R: BufRead, W: Write>(reader: R, writer: W) -> io::Result<()> {
29+
serve_bounded(reader, writer, wire::MAX_FRAME_BYTES)
30+
}
31+
32+
/// `serve` with an explicit frame bound, so a unit test can use a small one.
33+
fn serve_bounded<R: BufRead, W: Write>(mut reader: R, mut writer: W, max: usize) -> io::Result<()> {
34+
let mut session = Session::default();
35+
loop {
36+
let reply = match wire::read_frame(&mut reader, max)? {
37+
wire::Frame::End => return Ok(()),
38+
wire::Frame::Oversized => Some(wire::error(
39+
&Value::Null,
40+
wire::INVALID_REQUEST,
41+
"frame exceeds the size limit and was discarded",
42+
)),
43+
wire::Frame::Line(bytes) => session.handle(&bytes),
44+
};
45+
if let Some(value) = reply {
46+
writer.write_all(&wire::encode(&value))?;
47+
writer.flush()?;
48+
}
49+
}
50+
}
51+
52+
/// Per-connection state: the whole lifecycle is one flag.
53+
#[derive(Default)]
54+
struct Session {
55+
/// Set when an initialize request has been answered.
56+
initialized: bool,
57+
}
58+
59+
impl Session {
60+
/// Maps one frame to its reply; `None` when JSON-RPC calls for silence.
61+
fn handle(&mut self, bytes: &[u8]) -> Option<Value> {
62+
match json::from_slice::<Value>(bytes) {
63+
Err(error) => Some(wire::error(
64+
&Value::Null,
65+
wire::PARSE_ERROR,
66+
&format!("parse error: {error}"),
67+
)),
68+
Ok(Value::Object(frame)) => self.handle_object(&frame),
69+
Ok(_) => Some(wire::error(
70+
&Value::Null,
71+
wire::INVALID_REQUEST,
72+
"a frame must be one JSON object; batches are not supported",
73+
)),
74+
}
75+
}
76+
77+
/// Validates one JSON-RPC object and routes it.
78+
fn handle_object(&mut self, frame: &Map<String, Value>) -> Option<Value> {
79+
let id = match frame.get("id") {
80+
None => None,
81+
Some(value) if is_valid_id(value) => Some(value),
82+
Some(_) => {
83+
return Some(wire::error(
84+
&Value::Null,
85+
wire::INVALID_REQUEST,
86+
"id must be a string or an integer",
87+
));
88+
}
89+
};
90+
let reply_id = match id {
91+
Some(value) => value,
92+
None => &Value::Null,
93+
};
94+
if frame.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
95+
return Some(wire::error(
96+
reply_id,
97+
wire::INVALID_REQUEST,
98+
"jsonrpc must be \"2.0\"",
99+
));
100+
}
101+
let Some(method_value) = frame.get("method") else {
102+
if frame.contains_key("result") || frame.contains_key("error") {
103+
return None;
104+
}
105+
return Some(wire::error(
106+
reply_id,
107+
wire::INVALID_REQUEST,
108+
"method is required",
109+
));
110+
};
111+
let Some(method) = method_value.as_str() else {
112+
return Some(wire::error(
113+
reply_id,
114+
wire::INVALID_REQUEST,
115+
"method must be a string",
116+
));
117+
};
118+
let params = match frame.get("params") {
119+
None => None,
120+
Some(value) => match value.as_object() {
121+
Some(map) => Some(map),
122+
None => {
123+
return id.map(|request_id| {
124+
wire::error(request_id, wire::INVALID_PARAMS, "params must be an object")
125+
});
126+
}
127+
},
128+
};
129+
let request_id = id?;
130+
Some(self.request(request_id, method, params))
131+
}
132+
133+
/// Answers one request.
134+
fn request(&mut self, id: &Value, method: &str, params: Option<&Map<String, Value>>) -> Value {
135+
match method {
136+
"ping" => wire::result(id, json!({})),
137+
"initialize" => self.initialize(id, params),
138+
"tools/list" | "tools/call" if !self.initialized => {
139+
wire::error(id, wire::INVALID_REQUEST, NOT_INITIALIZED)
140+
}
141+
"tools/list" => tools_list(id, params),
142+
"tools/call" => tools_call(id, params),
143+
_ => wire::error(id, wire::METHOD_NOT_FOUND, "method not found"),
144+
}
145+
}
146+
147+
/// The lifecycle handshake: negotiate a revision and open the session.
148+
fn initialize(&mut self, id: &Value, params: Option<&Map<String, Value>>) -> Value {
149+
if self.initialized {
150+
return wire::error(id, wire::INVALID_REQUEST, "already initialized");
151+
}
152+
let Some(requested) = params
153+
.and_then(|map| map.get("protocolVersion"))
154+
.and_then(Value::as_str)
155+
else {
156+
return wire::error(
157+
id,
158+
wire::INVALID_PARAMS,
159+
"initialize requires params.protocolVersion as a string",
160+
);
161+
};
162+
let negotiated = match SUPPORTED_VERSIONS
163+
.iter()
164+
.copied()
165+
.find(|version| *version == requested)
166+
{
167+
Some(version) => version,
168+
None => LATEST_VERSION,
169+
};
170+
self.initialized = true;
171+
wire::result(
172+
id,
173+
json!({
174+
"protocolVersion": negotiated,
175+
"capabilities": { "tools": { "listChanged": false } },
176+
"serverInfo": {
177+
"name": "larry",
178+
"title": "Larry",
179+
"version": env!("CARGO_PKG_VERSION")
180+
},
181+
"instructions": "Hand Larry a typed task with larry_submit_task."
182+
}),
183+
)
184+
}
185+
}
186+
187+
/// Whether `value` is a legal request id: a string or an integer, never null.
188+
fn is_valid_id(value: &Value) -> bool {
189+
value.is_string() || value.is_i64() || value.is_u64()
190+
}
191+
192+
/// `tools/list`: the declared tools; no cursor is ever issued, so none is valid.
193+
fn tools_list(id: &Value, params: Option<&Map<String, Value>>) -> Value {
194+
if params.is_some_and(|map| map.contains_key("cursor")) {
195+
return wire::error(id, wire::INVALID_PARAMS, "invalid cursor");
196+
}
197+
wire::result(id, tools::list())
198+
}
199+
200+
/// `tools/call`: an unknown tool or a malformed call is a protocol error; a
201+
/// tool's own failure comes back as a result with `isError` true.
202+
fn tools_call(id: &Value, params: Option<&Map<String, Value>>) -> Value {
203+
let Some(name) = params
204+
.and_then(|map| map.get("name"))
205+
.and_then(Value::as_str)
206+
else {
207+
return wire::error(
208+
id,
209+
wire::INVALID_PARAMS,
210+
"tools/call requires params.name as a string",
211+
);
212+
};
213+
let none = Map::new();
214+
let arguments = match params.and_then(|map| map.get("arguments")) {
215+
None => &none,
216+
Some(value) => match value.as_object() {
217+
Some(map) => map,
218+
None => {
219+
return wire::error(
220+
id,
221+
wire::INVALID_PARAMS,
222+
"params.arguments must be an object",
223+
);
224+
}
225+
},
226+
};
227+
match tools::call(name, arguments) {
228+
Some(outcome) => wire::result(id, outcome),
229+
None => wire::error(id, wire::INVALID_PARAMS, "unknown tool"),
230+
}
231+
}
232+
233+
#[cfg(test)]
234+
mod tests {
235+
use super::serve_bounded;
236+
use lgwks_std::json::{self, Value};
237+
use std::io::Cursor;
238+
239+
/// Serves `input` and returns every reply line parsed.
240+
fn replies(input: &str, max: usize) -> Result<Vec<Value>, Box<dyn std::error::Error>> {
241+
let mut out = Vec::new();
242+
serve_bounded(Cursor::new(input.as_bytes().to_vec()), &mut out, max)?;
243+
let mut parsed = Vec::new();
244+
for line in String::from_utf8(out)?.lines() {
245+
parsed.push(json::from_str(line)?);
246+
}
247+
Ok(parsed)
248+
}
249+
250+
/// The lifecycle, in order, with the notification silent.
251+
#[test]
252+
fn initialize_then_list_then_ping() -> Result<(), Box<dyn std::error::Error>> {
253+
let input = concat!(
254+
r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#,
255+
"\n",
256+
r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
257+
"\n",
258+
r#"{"jsonrpc":"2.0","id":"a","method":"tools/list"}"#,
259+
"\n",
260+
r#"{"jsonrpc":"2.0","id":3,"method":"ping"}"#,
261+
"\n",
262+
);
263+
let got = replies(input, 1_048_576)?;
264+
assert_eq!(got.len(), 3, "the notification gets no reply");
265+
assert_eq!(
266+
got[0]["result"]["protocolVersion"], "2025-06-18",
267+
"version echoed"
268+
);
269+
assert_eq!(got[1]["id"], "a", "string ids come back as strings");
270+
assert_eq!(
271+
got[1]["result"]["tools"][0]["name"], "larry_submit_task",
272+
"tool listed"
273+
);
274+
assert_eq!(got[2]["result"], json::json!({}), "ping is an empty result");
275+
Ok(())
276+
}
277+
278+
/// A tool request before initialize is refused, an oversized line is
279+
/// refused, and the server keeps serving after both.
280+
#[test]
281+
fn pre_initialize_and_oversized_are_refused_then_serving_continues()
282+
-> Result<(), Box<dyn std::error::Error>> {
283+
let input = "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"tools/list\"}\n\
284+
xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n\
285+
{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"ping\"}\n";
286+
let got = replies(input, 64)?;
287+
assert_eq!(got[0]["error"]["code"], -32600, "not initialized");
288+
assert_eq!(got[1]["error"]["code"], -32600, "oversized");
289+
assert_eq!(got[2]["id"], 2, "still serving");
290+
Ok(())
291+
}
292+
}

0 commit comments

Comments
 (0)