Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

A request that arrives before initialize is answered, not fatal (#260) (#261)

Fabio Rovai0e0a2b451b49
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3e88744b..733839cc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,25 @@ All notable changes to Open Ontologies are documented here.
### Fixed
+- **A request sent before `initialize` no longer ends the MCP server** (#260).
+ rmcp's handshake reads messages itself until it sees `initialize`, answers a
+ pre-initialize `ping` and turns away everything else
+ (rmcp-1.4.0/src/service/server.rs:191 and :200), so `serve` returned
+ `ExpectedInitializeRequest`, `main.rs:1867` propagated it with `?`, and the
+ client read the exit as EOF while waiting on its own `initialize`. One line
+ was enough: a client whose first message was
+ `{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{}}` never got
+ as far as the handshake. That same request one message later is answered
+ -32601 by rmcp's default `on_custom_request` and costs nothing, so arrival
+ order was the whole difference between a reply and a dead process. The stdio
+ transport is now wrapped: a pre-initialize request is answered with a
+ JSON-RPC error, -32601 for an unknown method so the reply matches what the
+ post-handshake path already returns and -32600 for a known MCP method sent
+ out of order, and a pre-initialize notification is dropped. Nothing changes
+ after `initialize`. Measured on both rmcp versions in the registry, 1.4.0 and
+ 1.8.0: unguarded, both reject the reported byte sequence; guarded, both
+ complete the handshake, so the version bump was not the fix it looked like.
+
- **`onto_temporal_conflicts` no longer files a withdrawn assertion as a live
contradiction partner** (#128). The tool takes no `as_of` and read the
validity map after the lineage pass, so a retracted graph carried its
diff --git a/src/lib.rs b/src/lib.rs
index 4c89c5e8..f5c3806e 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -73,6 +73,10 @@ pub mod language;
pub mod lineage;
pub mod mapping;
pub mod marketplace;
+/// Tolerating a request that arrives before `initialize` instead of exiting.
+/// Issue #260: one such request ended the process before the handshake was
+/// answered, on rmcp 1.4.0 and on 1.8.0 alike.
+pub mod mcp_handshake;
pub mod monitor;
pub mod ontology;
pub mod ossie;
diff --git a/src/main.rs b/src/main.rs
index 32a6125a..e18e587c 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1864,7 +1864,16 @@ async fn async_main() -> anyhow::Result<()> {
ontology_dirs,
);
let _evictor = open_ontologies::registry::spawn_evictor(server.registry());
- let service = server.serve(rmcp::transport::stdio()).await?;
+ // A request that arrives before `initialize` is answered with a
+ // JSON-RPC error rather than ending the process. Issue #260: one
+ // `server/discover` probe sent ahead of `initialize` made rmcp
+ // return `ExpectedInitializeRequest` here, and `?` turned that
+ // into an exit the client read as EOF on `initialize`.
+ let service = server
+ .serve(open_ontologies::mcp_handshake::guard(
+ rmcp::transport::stdio(),
+ ))
+ .await?;
service.waiting().await?;
}
Commands::ServeHttp {
diff --git a/src/mcp_handshake.rs b/src/mcp_handshake.rs
new file mode 100644
index 00000000..ef2aef26
--- /dev/null
+++ b/src/mcp_handshake.rs
@@ -0,0 +1,134 @@
+//! A guard over the MCP server transport for the window before `initialize`.
+//!
+//! rmcp's server handshake reads messages itself until it sees `initialize`
+//! (rmcp-1.4.0/src/service/server.rs:170-203). It answers a pre-initialize
+//! `ping` in that loop and it accepts nothing else: any other request falls
+//! through `ClientJsonRpcMessage::Request(req) => break (req.request, req.id)`
+//! at line 191 into the `else` at line 200, and `serve` returns
+//! `ServerInitializeError::ExpectedInitializeRequest`. `main` propagates that
+//! with `?` at main.rs:1867, the process exits, and the client sees EOF.
+//!
+//! Issue #260 is that failure caused by one line. A client sent
+//! `{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{}}` as its
+//! first message and 2.0 died before answering the handshake at all. The same
+//! request one message later, after `initialize`, is answered -32601 by rmcp's
+//! default `on_custom_request` (rmcp-1.4.0/src/handler/server.rs:282-294) and
+//! costs nothing. Arrival order was the only difference between a reply and a
+//! dead process.
+//!
+//! Answering instead of exiting is a deliberate protocol choice. JSON-RPC 2.0
+//! requires a reply to every request that carries an id, and the MCP lifecycle
+//! says a client SHOULD NOT send non-ping requests before the initialize
+//! response, not MUST NOT. Exiting without a reply is the less conformant of
+//! the two behaviours, so this wrapper replies. It changes nothing after the
+//! handshake: once the `initialize` request has passed through, every message
+//! reaches rmcp untouched, which is what
+//! `guard_is_transparent_after_initialize` in
+//! `tests/mcp_handshake_guard_test.rs` measures.
+//!
+//! rmcp's own authors reason the same way one screen further down. The comment
+//! at rmcp-1.4.0/src/service/server.rs:250-256 says the spec uses SHOULD NOT
+//! rather than MUST NOT for pre-`initialized` messages and that a request
+//! arriving before the `initialized` notification is therefore processed
+//! normally. This wrapper applies their stated rule one message earlier.
+
+use rmcp::RoleServer;
+use rmcp::model::{ClientJsonRpcMessage, ClientRequest, ErrorCode, ErrorData};
+use rmcp::service::{RxJsonRpcMessage, TxJsonRpcMessage};
+use rmcp::transport::{IntoTransport, Transport};
+
+/// Wrap a transport so that a request arriving before `initialize` is answered
+/// with a JSON-RPC error instead of ending the process.
+pub fn guard<E, A>(
+ transport: impl IntoTransport<RoleServer, E, A>,
+) -> impl Transport<RoleServer, Error = E> + 'static
+where
+ E: std::error::Error + Send + Sync + 'static,
+{
+ HandshakeGuard {
+ inner: transport.into_transport(),
+ initialize_seen: false,
+ }
+}
+
+struct HandshakeGuard<T> {
+ inner: T,
+ /// Set when the `initialize` request has been handed up to rmcp. From that
+ /// point on this wrapper forwards every message without inspecting it.
+ initialize_seen: bool,
+}
+
+impl<T> Transport<RoleServer> for HandshakeGuard<T>
+where
+ T: Transport<RoleServer> + Send + 'static,
+{
+ type Error = T::Error;
+
+ fn send(
+ &mut self,
+ item: TxJsonRpcMessage<RoleServer>,
+ ) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send + 'static {
+ self.inner.send(item)
+ }
+
+ async fn receive(&mut self) -> Option<RxJsonRpcMessage<RoleServer>> {
+ loop {
+ let msg = self.inner.receive().await?;
+ if self.initialize_seen {
+ return Some(msg);
+ }
+ match &msg {
+ ClientJsonRpcMessage::Request(req) => match &req.request {
+ ClientRequest::InitializeRequest(_) => {
+ self.initialize_seen = true;
+ return Some(msg);
+ }
+ // rmcp answers a pre-initialize ping itself, in the
+ // same loop that rejects everything else, so this one
+ // still goes up.
+ ClientRequest::PingRequest(_) => return Some(msg),
+ other => {
+ let method = other.method().to_string();
+ let id = req.id.clone();
+ // An unknown method gets the code rmcp's own
+ // `on_custom_request` gives it after the
+ // handshake, so the reply a client sees does not
+ // depend on which side of `initialize` its probe
+ // landed on. A known MCP method sent early is a
+ // real ordering fault and is named as one.
+ let error = if matches!(other, ClientRequest::CustomRequest(_)) {
+ ErrorData::new(ErrorCode::METHOD_NOT_FOUND, method.clone(), None)
+ } else {
+ ErrorData::new(
+ ErrorCode::INVALID_REQUEST,
+ format!("{method} was received before initialize"),
+ None,
+ )
+ };
+ tracing::info!(
+ "answering {method} with an error because it arrived before initialize"
+ );
+ if let Err(e) = self
+ .inner
+ .send(TxJsonRpcMessage::<RoleServer>::error(error, id))
+ .await
+ {
+ tracing::warn!("could not answer a pre-initialize request: {e}");
+ }
+ }
+ },
+ // Nothing without an id is owed a reply, so a stray
+ // pre-initialize notification or response is dropped rather
+ // than ending the handshake the way rmcp's `other =>` arm
+ // at server.rs:192-196 does.
+ _ => {
+ tracing::debug!("dropping a message received before initialize: {msg:?}");
+ }
+ }
+ }
+ }
+
+ fn close(&mut self) -> impl std::future::Future<Output = Result<(), Self::Error>> + Send {
+ self.inner.close()
+ }
+}
diff --git a/tests/mcp_handshake_guard_test.rs b/tests/mcp_handshake_guard_test.rs
new file mode 100644
index 00000000..4fecae85
--- /dev/null
+++ b/tests/mcp_handshake_guard_test.rs
@@ -0,0 +1,149 @@
+//! Issue #260: a request arriving before `initialize` must not end the process.
+//!
+//! The report was a fresh 2.0 install whose client sent
+//! `{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{}}` as its
+//! first line. rmcp's handshake loop (rmcp-1.4.0/src/service/server.rs:170-203)
+//! answers a pre-initialize `ping` and rejects everything else, so `serve`
+//! returned `ExpectedInitializeRequest`, `main` propagated it, and the client's
+//! `initialize` hit EOF. Measured on rmcp 1.4.0 and on 1.8.0: the same two
+//! lines reject it in both, so this is not a version bump away.
+//!
+//! These tests drive the real handler over a `tokio::io::duplex` pipe, so no
+//! MCP client is involved. Every line is written before `serve` is called,
+//! which is what the reporter's process did in effect: the pipe holds the
+//! bytes while the server spends its startup loading the embedding model.
+
+use open_ontologies::config::{CacheConfig, EmbeddingsConfig};
+use open_ontologies::graph::GraphStore;
+use open_ontologies::server::OpenOntologiesServer;
+use open_ontologies::state::StateDb;
+use open_ontologies::toolfilter::ToolFilter;
+use rmcp::ServiceExt;
+use std::sync::Arc;
+use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
+
+const INITIALIZE: &str = r#"{"jsonrpc":"2.0","id":2,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"issue-260","version":"0"}}}"#;
+/// The reporter's line, verbatim. "server/discover" is not an MCP method and
+/// appears nowhere in this repository, so it is the client's own probe.
+const DISCOVER: &str = r#"{"jsonrpc":"2.0","id":1,"method":"server/discover","params":{}}"#;
+
+/// Feed `lines` to a guarded server over a pipe and collect `want` replies.
+///
+/// Every path is inside the tempdir, including the cache dir and the embedding
+/// model paths: `CacheConfig::default()` points at `~/.open-ontologies/cache`
+/// (src/config.rs:281) and an unset `model_path` resolves under
+/// `~/.open-ontologies/models`, and a test must touch neither.
+async fn handshake_replies(lines: &[&str], want: usize) -> Result<Vec<serde_json::Value>, String> {
+ let tmp = tempfile::tempdir().unwrap();
+ let db = StateDb::open(&tmp.path().join("state.db")).unwrap();
+ let embeddings = EmbeddingsConfig {
+ model_path: Some(tmp.path().join("absent.onnx").to_string_lossy().into_owned()),
+ tokenizer_path: Some(
+ tmp.path()
+ .join("absent-tokenizer.json")
+ .to_string_lossy()
+ .into_owned(),
+ ),
+ ..Default::default()
+ };
+ let cache = CacheConfig {
+ dir: tmp.path().join("cache").to_string_lossy().into_owned(),
+ ..Default::default()
+ };
+ let server = OpenOntologiesServer::new_with_registry_options(
+ db,
+ Arc::new(GraphStore::new()),
+ None,
+ embeddings,
+ cache,
+ ToolFilter::default(),
+ );
+
+ let (mut client, pipe) = tokio::io::duplex(64 * 1024);
+ for line in lines {
+ client.write_all(line.as_bytes()).await.unwrap();
+ client.write_all(b"\n").await.unwrap();
+ }
+ client.flush().await.unwrap();
+
+ let service = server
+ .serve(open_ontologies::mcp_handshake::guard(pipe))
+ .await
+ .map_err(|e| e.to_string())?;
+
+ let mut reader = BufReader::new(client).lines();
+ let mut out = Vec::new();
+ while out.len() < want {
+ let line = tokio::time::timeout(std::time::Duration::from_secs(10), reader.next_line())
+ .await
+ .map_err(|_| format!("timed out holding {} of {want} replies", out.len()))?
+ .map_err(|e| e.to_string())?;
+ match line {
+ Some(l) => out.push(serde_json::from_str(&l).map_err(|e| format!("{e}: {l}"))?),
+ None => {
+ return Err(format!(
+ "pipe closed holding {} of {want} replies",
+ out.len()
+ ));
+ }
+ }
+ }
+ // Held until the last reply is read. Dropping the running service cancels
+ // rmcp's service loop, and a reply not yet written is then lost: that cost
+ // the second reply in the rmcp 1.4.0 reproduction before the read moved
+ // ahead of the drop.
+ drop(service);
+ Ok(out)
+}
+
+/// FAILS without the guard: the handshake ends with
+/// `ServerInitializeError::ExpectedInitializeRequest` and no reply is written.
+#[tokio::test]
+async fn unknown_request_before_initialize_does_not_end_the_handshake() {
+ let out = handshake_replies(&[DISCOVER, INITIALIZE], 2)
+ .await
+ .expect("the handshake must survive a request sent before initialize");
+ assert_eq!(out[0]["id"], 1, "the probe is answered first: {:?}", out[0]);
+ assert_eq!(
+ out[0]["error"]["code"], -32601,
+ "an unknown method gets the code rmcp gives it after the handshake: {:?}",
+ out[0]
+ );
+ assert_eq!(out[1]["id"], 2, "then the initialize reply: {:?}", out[1]);
+ assert!(
+ out[1]["result"]["protocolVersion"].is_string(),
+ "initialize must still be answered, not swallowed: {:?}",
+ out[1]
+ );
+}
+
+/// FAILS without the guard for the same reason: rmcp's pre-initialize loop
+/// turns away every request that is not `ping`, a known MCP method included.
+#[tokio::test]
+async fn known_request_before_initialize_is_answered_invalid_request() {
+ const TOOLS_LIST: &str = r#"{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}"#;
+ let out = handshake_replies(&[TOOLS_LIST, INITIALIZE], 2)
+ .await
+ .expect("the handshake must survive tools/list sent before initialize");
+ assert_eq!(
+ out[0]["error"]["code"], -32600,
+ "a known method out of order is an ordering fault, not a missing method: {:?}",
+ out[0]
+ );
+ assert!(out[1]["result"]["protocolVersion"].is_string());
+}
+
+/// Passes before and after the change, so it is a regression guard and not
+/// evidence of the bug. It measures that the wrapper does not intercept live
+/// traffic: this -32601 comes from rmcp's own `on_custom_request`.
+#[tokio::test]
+async fn guard_is_transparent_after_initialize() {
+ const INITIALIZED: &str = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;
+ let out = handshake_replies(&[INITIALIZE, INITIALIZED, DISCOVER], 2)
+ .await
+ .expect("handshake");
+ assert_eq!(out[0]["id"], 2);
+ assert!(out[0]["result"]["protocolVersion"].is_string());
+ assert_eq!(out[1]["id"], 1);
+ assert_eq!(out[1]["error"]["code"], -32601);
+}