Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

test(mcp): trim golden suites and add module tests

Steven Enamakelae7730167604
diff --git a/crates/openhuman-core/src/mcp/server/handler_tests.rs b/crates/openhuman-core/src/mcp/server/handler_tests.rs
index e088355665..66df14ca8b 100644
--- a/crates/openhuman-core/src/mcp/server/handler_tests.rs
+++ b/crates/openhuman-core/src/mcp/server/handler_tests.rs
@@ -1,113 +1,23 @@
-use serde_json::{json, Map, Value};
-use tinymcp::{McpServerHandler, RequestContext, RequestHeaders, RequestHeadersExt, ToolCallError};
-
use super::*;
-use crate::mcp::server::subagent_depth::{HEADER_SUBAGENT_DEPTH, MAX_SUBAGENT_DEPTH};
-
-fn context(headers: RequestHeaders) -> RequestContext {
- RequestContext::new("mcp:test", headers)
-}
#[test]
-fn server_info_is_openhumans_identity_and_guidance() {
- let info = OpenHumanMcpHandler.server_info();
- assert_eq!(info.name, "openhuman-core");
- assert_eq!(info.version, env!("CARGO_PKG_VERSION"));
- let instructions = info.instructions.expect("OpenHuman gives instructions");
- assert!(instructions.contains("core.list_tools"), "{instructions}");
-}
-
-#[test]
-fn sessions_are_attributed_under_the_mcp_prefix() {
- assert_eq!(OpenHumanMcpHandler.source_type_prefix(), "mcp");
-}
-
-#[tokio::test]
-async fn list_tools_advertises_the_base_catalog_with_annotations() {
- let tools = OpenHumanMcpHandler
- .list_tools(&context(RequestHeaders::new()))
- .await;
- let names = tools
- .iter()
- .map(|tool| tool.name.as_str())
- .collect::<Vec<_>>();
- for expected in [
- "core.list_tools",
- "agent.run_subagent",
- "memory.recall",
- "memory.forget",
- ] {
- assert!(names.contains(&expected), "missing {expected}: {names:?}");
- }
- assert!(tools
- .iter()
- .all(|tool| tool.title.is_some() && tool.annotations.is_some()));
-}
-
-#[tokio::test]
-async fn resources_are_the_bundled_prompt_catalog() {
- let resources = OpenHumanMcpHandler.list_resources();
- assert!(resources
- .iter()
- .all(|resource| resource.mime_type.as_deref() == Some("text/markdown")));
- let identity = OpenHumanMcpHandler
- .read_resource("openhuman://prompts/identity")
- .await
- .expect("identity resource");
+fn host_tool_errors_keep_their_category_and_diagnostic() {
assert_eq!(
- identity["contents"][0]["uri"],
- "openhuman://prompts/identity"
+ reply_error(ToolCallError::InvalidParams("argument was empty".to_owned())),
+ ServerHostReply::InvalidParams {
+ message: "argument was empty".to_owned()
+ }
);
- let err = OpenHumanMcpHandler
- .read_resource("openhuman://prompts/nope")
- .await
- .expect_err("unknown uri");
assert_eq!(
- err,
- ToolCallError::ResourceNotFound("no resource with uri `openhuman://prompts/nope`".into())
- );
-}
-
-#[tokio::test]
-async fn call_tool_runs_inside_the_delegation_depth_the_request_carries() {
- // At the cap, `agent.run_subagent` refuses before building anything —
- // which only happens if the header reached the depth scope.
- let mut headers = RequestHeaders::new();
- headers.insert(HEADER_SUBAGENT_DEPTH, MAX_SUBAGENT_DEPTH.to_string());
- let arguments = match json!({"agent_id": "planner", "prompt": "hi"}) {
- Value::Object(map) => map,
- _ => Map::new(),
- };
- let err = OpenHumanMcpHandler
- .call_tool(&context(headers), "agent.run_subagent", arguments)
- .await
- .expect_err("depth cap refuses");
- assert!(
- err.message().contains("delegation depth limit reached"),
- "{err:?}"
+ reply_error(ToolCallError::Internal("provider setup failed".to_owned())),
+ ServerHostReply::Internal {
+ message: "provider setup failed".to_owned()
+ }
);
-}
-
-#[tokio::test]
-async fn call_tool_rejects_unknown_tools_as_invalid_params() {
- let err = OpenHumanMcpHandler
- .call_tool(&context(RequestHeaders::new()), "no.such_tool", Map::new())
- .await
- .expect_err("unknown tool");
assert_eq!(
- err,
- ToolCallError::InvalidParams("unknown MCP tool `no.such_tool`".into())
+ reply_error(ToolCallError::ResourceNotFound("unknown uri".to_owned())),
+ ServerHostReply::ResourceNotFound {
+ message: "unknown uri".to_owned()
+ }
);
}
-
-#[cfg(feature = "http-server")]
-#[tokio::test]
-async fn the_http_client_round_trips_against_the_openhuman_handler() {
- let endpoint = super::super::test_support::spawn_http(None).await;
- let client = crate::mcp::http_client::McpHttpClient::new(endpoint, 5).expect("client");
- let init = client.initialize().await.expect("initialize");
- assert_eq!(init.server_info["name"], "openhuman-core");
- let tools = client.list_tools().await.expect("tools/list");
- assert!(tools.iter().any(|tool| tool.name == "memory.recall"));
- client.close_session().await.expect("DELETE session");
-}
diff --git a/crates/openhuman-core/src/mcp/server/http_golden_tests.rs b/crates/openhuman-core/src/mcp/server/http_golden_tests.rs
deleted file mode 100644
index 71dea1bbb2..0000000000
--- a/crates/openhuman-core/src/mcp/server/http_golden_tests.rs
+++ /dev/null
@@ -1,369 +0,0 @@
-//! Golden fixtures for the Streamable HTTP transport OpenHuman serves.
-//!
-//! Status codes, plain-text rejection bodies, content types, the session
-//! header and the JSON bodies are all wire behavior a remote client depends
-//! on. Captured before the transport moved into `tinymcp::server`; they must
-//! keep passing through that move unchanged.
-
-use reqwest::{header::CONTENT_TYPE, Client, Response, StatusCode};
-use serde_json::{json, Value};
-use tinymcp_bus::{HEADER_PROTOCOL_VERSION, HEADER_SESSION_ID, LATEST_PROTOCOL_VERSION};
-
-use super::test_support::spawn_http;
-
-const PLAIN_TEXT: &str = "text/plain; charset=utf-8";
-
-async fn initialize(http: &Client, endpoint: &str) -> String {
- let response = post(http, endpoint, None, None, &init_body()).await;
- assert_eq!(response.status(), StatusCode::OK);
- response
- .headers()
- .get(HEADER_SESSION_ID)
- .and_then(|value| value.to_str().ok())
- .expect("session header")
- .to_string()
-}
-
-fn init_body() -> Value {
- json!({
- "jsonrpc": "2.0",
- "id": 1,
- "method": "initialize",
- "params": {
- "protocolVersion": LATEST_PROTOCOL_VERSION,
- "capabilities": {},
- "clientInfo": {"name": "golden", "version": "0"}
- }
- })
-}
-
-async fn post(
- http: &Client,
- endpoint: &str,
- session: Option<&str>,
- protocol: Option<&str>,
- body: &Value,
-) -> Response {
- let mut request = http.post(endpoint).json(body);
- if let Some(session) = session {
- request = request.header(HEADER_SESSION_ID, session);
- }
- if let Some(protocol) = protocol {
- request = request.header(HEADER_PROTOCOL_VERSION, protocol);
- }
- request.send().await.expect("post")
-}
-
-async fn assert_text(response: Response, status: StatusCode, body: &str) {
- assert_content(response, status, PLAIN_TEXT, body).await;
-}
-
-async fn assert_content(response: Response, status: StatusCode, content_type: &str, body: &str) {
- assert_eq!(response.status(), status);
- assert_eq!(
- response
- .headers()
- .get(CONTENT_TYPE)
- .and_then(|v| v.to_str().ok()),
- Some(content_type)
- );
- assert_eq!(response.text().await.expect("body"), body);
-}
-
-#[tokio::test]
-async fn initialize_answers_json_and_mints_a_session() {
- let endpoint = spawn_http(None).await;
- let response = post(&Client::new(), &endpoint, None, None, &init_body()).await;
- assert_eq!(response.status(), StatusCode::OK);
- assert_eq!(
- response
- .headers()
- .get(CONTENT_TYPE)
- .and_then(|v| v.to_str().ok()),
- Some("application/json")
- );
- let session = response
- .headers()
- .get(HEADER_SESSION_ID)
- .and_then(|v| v.to_str().ok())
- .expect("session header")
- .to_string();
- assert_eq!(session.len(), 36, "a hyphenated v4 uuid: {session}");
- let body: Value = response.json().await.expect("json");
- assert_eq!(body["result"]["protocolVersion"], LATEST_PROTOCOL_VERSION);
- assert_eq!(body["result"]["serverInfo"]["name"], "openhuman-core");
- assert_eq!(
- body["result"]["serverInfo"]["version"],
- env!("CARGO_PKG_VERSION")
- );
-}
-
-#[tokio::test]
-async fn failed_initialize_answers_the_error_without_a_session() {
- let endpoint = spawn_http(None).await;
- let response = post(
- &Client::new(),
- &endpoint,
- None,
- None,
- &json!({"jsonrpc": "1.0", "id": 1, "method": "initialize"}),
- )
- .await;
- assert_eq!(response.status(), StatusCode::OK);
- assert!(response.headers().get(HEADER_SESSION_ID).is_none());
- assert_eq!(
- response.text().await.expect("body"),
- r#"{"error":{"code":-32600,"data":"jsonrpc must be \"2.0\"","message":"Invalid Request"},"id":1,"jsonrpc":"2.0"}"#
- );
-}
-
-#[tokio::test]
-async fn session_and_protocol_rejections_are_plain_text() {
- let endpoint = spawn_http(None).await;
- let http = Client::new();
- let ping = json!({"jsonrpc": "2.0", "id": 2, "method": "ping"});
-
- let no_session = post(&http, &endpoint, None, None, &ping).await;
- assert_text(
- no_session,
- StatusCode::BAD_REQUEST,
- "missing or invalid Mcp-Session-Id header",
- )
- .await;
-
- let unknown = post(
- &http,
- &endpoint,
- Some("nope"),
- Some(LATEST_PROTOCOL_VERSION),
- &ping,
- )
- .await;
- assert_text(
- unknown,
- StatusCode::NOT_FOUND,
- "unknown or expired MCP session",
- )
- .await;
-
- let session = initialize(&http, &endpoint).await;
- let mismatch = post(&http, &endpoint, Some(&session), Some("2024-11-05"), &ping).await;
- assert_text(
- mismatch,
- StatusCode::BAD_REQUEST,
- "missing or invalid MCP-Protocol-Version header",
- )
- .await;
- let missing = post(&http, &endpoint, Some(&session), None, &ping).await;
- assert_text(
- missing,
- StatusCode::BAD_REQUEST,
- "missing or invalid MCP-Protocol-Version header",
- )
- .await;
-}
-
-#[tokio::test]
-async fn requests_notifications_and_batches_on_a_session() {
- let endpoint = spawn_http(None).await;
- let http = Client::new();
- let session = initialize(&http, &endpoint).await;
- let protocol = Some(LATEST_PROTOCOL_VERSION);
-
- let ping = post(
- &http,
- &endpoint,
- Some(&session),
- protocol,
- &json!({"jsonrpc": "2.0", "id": 2, "method": "ping"}),
- )
- .await;
- assert_eq!(ping.status(), StatusCode::OK);
- assert_eq!(
- ping.text().await.expect("body"),
- r#"{"id":2,"jsonrpc":"2.0","result":{}}"#
- );
-
- let notification = post(
- &http,
- &endpoint,
- Some(&session),
- protocol,
- &json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),
- )
- .await;
- assert_eq!(notification.status(), StatusCode::NO_CONTENT);
- assert_eq!(notification.text().await.expect("body"), "");
-
- // A batch body has no top-level `id`, so the transport answers 204 even
- // when the batch holds requests. Pinned as-is: it is the current wire.
- let batch = post(
- &http,
- &endpoint,
- Some(&session),
- protocol,
- &json!([{"jsonrpc": "2.0", "id": 3, "method": "ping"}]),
- )
- .await;
- assert_eq!(batch.status(), StatusCode::NO_CONTENT);
-
- let unknown_method = post(
- &http,
- &endpoint,
- Some(&session),
- protocol,
- &json!({"jsonrpc": "2.0", "id": 4, "method": "nope"}),
- )
- .await;
- assert_eq!(unknown_method.status(), StatusCode::OK);
- assert_eq!(
- unknown_method.text().await.expect("body"),
- r#"{"error":{"code":-32601,"data":"unsupported MCP method `nope`","message":"Method not found"},"id":4,"jsonrpc":"2.0"}"#
- );
-}
-
-#[tokio::test]
-async fn non_json_body_is_rejected_by_the_extractor() {
- let endpoint = spawn_http(None).await;
- let response = Client::new()
- .post(&endpoint)
- .body("ping")
- .send()
- .await
- .expect("post");
- assert_eq!(response.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE);
- assert_eq!(
- response.text().await.expect("body"),
- "Expected request with `Content-Type: application/json`"
- );
-}
-
-#[tokio::test]
-async fn get_and_delete_follow_the_session_lifecycle() {
- let endpoint = spawn_http(None).await;
- let http = Client::new();
-
- let get_missing = http.get(&endpoint).send().await.expect("get");
- assert_text(
- get_missing,
- StatusCode::BAD_REQUEST,
- "missing Mcp-Session-Id header",
- )
- .await;
- let get_unknown = http
- .get(&endpoint)
- .header(HEADER_SESSION_ID, "nope")
- .send()
- .await
- .expect("get");
- assert_text(
- get_unknown,
- StatusCode::NOT_FOUND,
- "unknown or expired MCP session",
- )
- .await;
-
- let session = initialize(&http, &endpoint).await;
- let get_mismatch = http
- .get(&endpoint)
- .header(HEADER_SESSION_ID, session.as_str())
- .send()
- .await
- .expect("get");
- assert_text(
- get_mismatch,
- StatusCode::BAD_REQUEST,
- "missing or invalid MCP-Protocol-Version header",
- )
- .await;
- let events = http
- .get(&endpoint)
- .header(HEADER_SESSION_ID, session.as_str())
- .header(HEADER_PROTOCOL_VERSION, LATEST_PROTOCOL_VERSION)
- .send()
- .await
- .expect("get");
- assert_eq!(events.status(), StatusCode::OK);
- assert_eq!(
- events
- .headers()
- .get(CONTENT_TYPE)
- .and_then(|v| v.to_str().ok()),
- Some("text/event-stream")
- );
- drop(events);
-
- let delete_missing = http.delete(&endpoint).send().await.expect("delete");
- assert_text(
- delete_missing,
- StatusCode::BAD_REQUEST,
- "missing Mcp-Session-Id header",
- )
- .await;
- let deleted = http
- .delete(&endpoint)
- .header(HEADER_SESSION_ID, session.as_str())
- .send()
- .await
- .expect("delete");
- assert_eq!(deleted.status(), StatusCode::NO_CONTENT);
- let deleted_again = http
- .delete(&endpoint)
- .header(HEADER_SESSION_ID, session.as_str())
- .send()
- .await
- .expect("delete");
- assert_eq!(deleted_again.status(), StatusCode::NO_CONTENT);
-
- let after = post(
- &http,
- &endpoint,
- Some(&session),
- Some(LATEST_PROTOCOL_VERSION),
- &json!({"jsonrpc": "2.0", "id": 2, "method": "ping"}),
- )
- .await;
- assert_text(
- after,
- StatusCode::NOT_FOUND,
- "unknown or expired MCP session",
- )
- .await;
-}
-
-#[tokio::test]
-async fn bearer_auth_rejects_with_plain_text_before_anything_else() {
- let endpoint = spawn_http(Some("golden-secret")).await;
- let http = Client::new();
-
- // The auth rejection sets a bare `text/plain`, unlike the other rejections.
- let missing = post(&http, &endpoint, None, None, &init_body()).await;
- assert_content(
- missing,
- StatusCode::UNAUTHORIZED,
- "text/plain",
- "unauthorized",
- )
- .await;
- let wrong = http
- .post(&endpoint)
- .bearer_auth("wrong")
- .json(&init_body())
- .send()
- .await
- .expect("post");
- assert_eq!(wrong.status(), StatusCode::UNAUTHORIZED);
- let get = http.get(&endpoint).send().await.expect("get");
- assert_eq!(get.status(), StatusCode::UNAUTHORIZED);
- let delete = http.delete(&endpoint).send().await.expect("delete");
- assert_eq!(delete.status(), StatusCode::UNAUTHORIZED);
-
- let allowed = http
- .post(&endpoint)
- .bearer_auth("golden-secret")
- .json(&init_body())
- .send()
- .await
- .expect("post");
- assert_eq!(allowed.status(), StatusCode::OK);
-}
diff --git a/crates/openhuman-core/src/mcp/server/mod.rs b/crates/openhuman-core/src/mcp/server/mod.rs
index 7a6452cf02..148af0b5a9 100644
--- a/crates/openhuman-core/src/mcp/server/mod.rs
+++ b/crates/openhuman-core/src/mcp/server/mod.rs
@@ -70,13 +70,3 @@ pub use tools::McpToolSpec;
mod stub;
#[cfg(not(feature = "mcp"))]
pub use stub::*;
-
-// Golden wire fixtures, and the one seam they call through (see each file).
-#[cfg(all(test, feature = "mcp", feature = "http-server"))]
-#[path = "http_golden_tests.rs"]
-mod http_golden_tests;
-#[cfg(all(test, feature = "mcp"))]
-mod test_support;
-#[cfg(all(test, feature = "mcp"))]
-#[path = "wire_golden_tests.rs"]
-mod wire_golden_tests;
diff --git a/crates/openhuman-core/src/mcp/server/module.rs b/crates/openhuman-core/src/mcp/server/module.rs
index d243a0cdf5..1b73b8cdd3 100644
--- a/crates/openhuman-core/src/mcp/server/module.rs
+++ b/crates/openhuman-core/src/mcp/server/module.rs
@@ -352,3 +352,7 @@ pub(super) fn session_config(
pub(super) fn module_string<T: Serialize>(value: &T) -> Result<String, serde_json::Error> {
serde_json::to_string(value)
}
+
+#[cfg(test)]
+#[path = "module_tests.rs"]
+mod tests;
diff --git a/crates/openhuman-core/src/mcp/server/module_tests.rs b/crates/openhuman-core/src/mcp/server/module_tests.rs
new file mode 100644
index 0000000000..55226e5530
--- /dev/null
+++ b/crates/openhuman-core/src/mcp/server/module_tests.rs
@@ -0,0 +1,170 @@
+use super::*;
+use std::sync::Mutex;
+
+#[derive(Default)]
+struct PortState {
+ opened: Option<ServerSessionConfig>,
+ submitted: Option<ServerInput>,
+ completed: Option<ServerHostReply>,
+ cancelled: bool,
+ unavailable: bool,
+ polls: usize,
+}
+
+struct FixturePort(Mutex<PortState>);
+
+#[async_trait]
+impl ServerPort for FixturePort {
+ async fn open(&self, config: ServerSessionConfig) -> Result<String, ModuleCallError> {
+ let mut state = self.0.lock().unwrap();
+ if state.unavailable {
+ return Err(ModuleCallError::Unavailable);
+ }
+ state.opened = Some(config.clone());
+ Ok(config.session_id)
+ }
+
+ async fn open_http(
+ &self,
+ config: ServerHttpSessionConfig,
+ ) -> Result<String, ModuleCallError> {
+ self.open(config.server).await
+ }
+
+ async fn submit(
+ &self,
+ _session: &str,
+ _headers: Map<String, Value>,
+ input: ServerInput,
+ ) -> Result<(), ModuleCallError> {
+ self.0.lock().unwrap().submitted = Some(input);
+ Ok(())
+ }
+
+ async fn poll(&self, _session: &str) -> Result<ServerOperationSnapshot, ModuleCallError> {
+ let mut state = self.0.lock().unwrap();
+ state.polls += 1;
+ let input = state.submitted.clone().unwrap();
+ if state.polls == 1 {
+ Ok(ServerOperationSnapshot {
+ operation_id: input.operation_id,
+ state: ServerOperationState::Callback {
+ callback: tinymcp_bus::ServerCallback {
+ id: "callback-1".to_owned(),
+ call: ServerHostCall::ReadResource {
+ source_type: "mcp:test".to_owned(),
+ headers: Map::new(),
+ uri: "openhuman://prompts/identity".to_owned(),
+ },
+ },
+ },
+ http_response: None,
+ })
+ } else {
+ Ok(ServerOperationSnapshot {
+ operation_id: input.operation_id,
+ state: ServerOperationState::Complete {
+ response: Some("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{}}".to_owned()),
+ },
+ http_response: None,
+ })
+ }
+ }
+
+ async fn complete(
+ &self,
+ _session: &str,
+ _callback: &str,
+ reply: ServerHostReply,
+ ) -> Result<(), ModuleCallError> {
+ self.0.lock().unwrap().completed = Some(reply);
+ Ok(())
+ }
+
+ async fn cancel(&self, _operation: ServerOperationRef) -> Result<(), ModuleCallError> {
+ self.0.lock().unwrap().cancelled = true;
+ Ok(())
+ }
+
+ async fn close(&self, _session: &str) -> Result<(), ModuleCallError> {
+ Ok(())
+ }
+
+ async fn http_session(
+ &self,
+ _request: ServerHttpSessionRequest,
+ ) -> Result<ServerHttpResponseMetadata, ModuleCallError> {
+ unreachable!()
+ }
+
+ async fn metadata(
+ &self,
+ _session: &str,
+ ) -> Result<tinymcp_bus::ServerSessionMetadata, ModuleCallError> {
+ unreachable!()
+ }
+
+ async fn shutdown(&self) -> Result<usize, ModuleCallError> {
+ Ok(0)
+ }
+}
+
+#[tokio::test]
+async fn server_session_completes_host_resource_callback() {
+ let port = Arc::new(FixturePort(Mutex::new(PortState::default())));
+ let session = ServerSession::open_with_port(port.clone()).await.unwrap();
+ assert!(!Uuid::parse_str(session.id()).unwrap().is_nil());
+
+ let snapshot = session
+ .submit(
+ Map::new(),
+ r#"{"jsonrpc":"2.0","id":1,"method":"resources/read"}"#.to_owned(),
+ &CancellationToken::new(),
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(snapshot.state, ServerOperationState::Complete { .. }));
+ let state = port.0.lock().unwrap();
+ assert!(matches!(
+ state.completed,
+ Some(ServerHostReply::Success { ref value }) if value["contents"][0]["uri"] == "openhuman://prompts/identity"
+ ));
+ let opened = state.opened.as_ref().unwrap();
+ assert_eq!(opened.source_type_prefix, "mcp");
+ assert_eq!(opened.info["name"], "openhuman-core");
+}
+
+#[tokio::test]
+async fn server_session_cancellation_reaches_module_owner() {
+ let port = Arc::new(FixturePort(Mutex::new(PortState::default())));
+ let session = ServerSession::open_with_port(port.clone()).await.unwrap();
+ let cancellation = CancellationToken::new();
+ cancellation.cancel();
+
+ let error = session
+ .submit(Map::new(), "{}".to_owned(), &cancellation)
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, ServerError::Cancelled));
+ assert!(port.0.lock().unwrap().cancelled);
+}
+
+#[tokio::test]
+async fn server_session_fails_closed_when_module_is_unavailable() {
+ let port = Arc::new(FixturePort(Mutex::new(PortState {
+ unavailable: true,
+ ..PortState::default()
+ })));
+
+ let error = match ServerSession::open_with_port(port).await {
+ Ok(_) => panic!("unavailable module unexpectedly opened"),
+ Err(error) => error,
+ };
+
+ assert!(matches!(
+ error,
+ ServerError::Module(ModuleCallError::Unavailable)
+ ));
+}
diff --git a/crates/openhuman-core/src/mcp/server/test_support.rs b/crates/openhuman-core/src/mcp/server/test_support.rs
deleted file mode 100644
index aaad10ffd1..0000000000
--- a/crates/openhuman-core/src/mcp/server/test_support.rs
+++ /dev/null
@@ -1,36 +0,0 @@
-//! Test-only entry points into the served MCP surface.
-//!
-//! The golden suites call these instead of naming the protocol or transport
-//! directly, so the fixtures stay byte-for-byte unchanged while the machinery
-//! underneath them moves.
-
-/// Answer one newline-delimited JSON-RPC line on a fresh session, exactly as
-/// the stdio transport would.
-pub(super) async fn dispatch_line(line: &str) -> Option<String> {
- let mut session = tinymcp::ClientSession::new("mcp");
- tinymcp::server::handle_line(
- &super::handler::OpenHumanMcpHandler,
- &mut session,
- &tinymcp::RequestHeaders::new(),
- line,
- )
- .await
-}
-
-/// Start the Streamable HTTP server on an ephemeral loopback port and return
-/// its endpoint URL.
-#[cfg(feature = "http-server")]
-pub(super) async fn spawn_http(auth_token: Option<&str>) -> String {
- let (tx, rx) = tokio::sync::oneshot::channel();
- let config = super::HttpServerConfig {
- bind_addr: "127.0.0.1:0".parse().expect("loopback address"),
- auth_token: auth_token.map(str::to_string),
- };
- tokio::spawn(async move {
- super::run_http_reporting(config, Some(tx))
- .await
- .expect("mcp http server runs");
- });
- let addr = rx.await.expect("server reports its bound address");
- format!("http://{addr}/")
-}
diff --git a/crates/openhuman-core/src/mcp/server/tools_tests.rs b/crates/openhuman-core/src/mcp/server/tools_tests.rs
index b7233d0cf9..bf47eb1de9 100644
--- a/crates/openhuman-core/src/mcp/server/tools_tests.rs
+++ b/crates/openhuman-core/src/mcp/server/tools_tests.rs
@@ -1,13 +1,12 @@
use super::specs::tool_specs_for_loaded_config;
use super::*;
-use tinymcp::ServerToolSpecExt;
/// The `tools/list` result this config advertises, rendered through the same
/// `tinymcp` conversion the served catalog uses.
fn list_tools_result_for_config(config: &crate::config::Config) -> Value {
let tools = tool_specs_for_loaded_config(config)
.iter()
- .map(|spec| server_tool_spec(spec).to_json())
+ .map(|spec| serde_json::to_value(server_tool_spec(spec)).expect("tool spec serializes"))
.collect::<Vec<_>>();
json!({ "tools": tools })
}
diff --git a/crates/openhuman-core/src/mcp/server/wire_golden_tests.rs b/crates/openhuman-core/src/mcp/server/wire_golden_tests.rs
deleted file mode 100644
index bb728d3cc2..0000000000
--- a/crates/openhuman-core/src/mcp/server/wire_golden_tests.rs
+++ /dev/null
@@ -1,314 +0,0 @@
-//! Golden wire fixtures for the MCP server surface OpenHuman serves.
-//!
-//! These pin the exact bytes a client receives: initialize results, the
-//! tool catalog, every JSON-RPC error shape, batching and notification
-//! handling. They were captured from the implementation before the generic
-//! protocol moved into `tinymcp::server`, and they must keep passing through
-//! that move unchanged — a diff here is a wire change, not a refactor.
-//!
-//! The package version is the only substituted value: it moves on every
-//! release and is not part of what these fixtures protect.
-
-use serde_json::Value;
-
-use super::test_support::dispatch_line;
-
-const VERSION_PLACEHOLDER: &str = "{{CARGO_PKG_VERSION}}";
-
-/// Tools whose presence depends on the search providers the loaded config can
-/// serve. The fixture pins the config-independent base catalog.
-const CONFIG_GATED_TOOLS: &[&str] = &["searxng_search", "web_search", "web_answer"];
-
-/// `(request line, exact response line)` — `None` means no response at all.
-const LINE_CASES: &[(&str, Option<&str>)] = &[
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"Claude Desktop","version":"0"}}}"#,
- Some(
- r#"{"id":1,"jsonrpc":"2.0","result":{"capabilities":{"resources":{"listChanged":false,"subscribe":false},"tools":{}},"instructions":"OpenHuman MCP exposes first-level core integration: inspect the live tool catalog with core.list_tools or core.tool_instructions, inspect subagents with agent.list_subagents, run a standalone subagent with agent.run_subagent, use web_search or web_answer for live web lookups (and searxng_search when self-hosted search is enabled), and use memory.recall (answer with citations), memory.fetch or memory.list to read memory, and memory.learn or memory.forget to change it.","protocolVersion":"2025-06-18","serverInfo":{"name":"openhuman-core","version":"{{CARGO_PKG_VERSION}}"}}}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":"init","method":"initialize","params":{"protocolVersion":"1999-01-01"}}"#,
- Some(
- r#"{"id":"init","jsonrpc":"2.0","result":{"capabilities":{"resources":{"listChanged":false,"subscribe":false},"tools":{}},"instructions":"OpenHuman MCP exposes first-level core integration: inspect the live tool catalog with core.list_tools or core.tool_instructions, inspect subagents with agent.list_subagents, run a standalone subagent with agent.run_subagent, use web_search or web_answer for live web lookups (and searxng_search when self-hosted search is enabled), and use memory.recall (answer with citations), memory.fetch or memory.list to read memory, and memory.learn or memory.forget to change it.","protocolVersion":"2025-11-25","serverInfo":{"name":"openhuman-core","version":"{{CARGO_PKG_VERSION}}"}}}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":7,"method":"initialize"}"#,
- Some(
- r#"{"id":7,"jsonrpc":"2.0","result":{"capabilities":{"resources":{"listChanged":false,"subscribe":false},"tools":{}},"instructions":"OpenHuman MCP exposes first-level core integration: inspect the live tool catalog with core.list_tools or core.tool_instructions, inspect subagents with agent.list_subagents, run a standalone subagent with agent.run_subagent, use web_search or web_answer for live web lookups (and searxng_search when self-hosted search is enabled), and use memory.recall (answer with citations), memory.fetch or memory.list to read memory, and memory.learn or memory.forget to change it.","protocolVersion":"2025-11-25","serverInfo":{"name":"openhuman-core","version":"{{CARGO_PKG_VERSION}}"}}}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":"abc","method":"ping"}"#,
- Some(r#"{"id":"abc","jsonrpc":"2.0","result":{}}"#),
- ),
- (
- r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
- None,
- ),
- (
- r#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":1}}"#,
- None,
- ),
- (r#"{"jsonrpc":"2.0","method":"notifications/other"}"#, None),
- (
- r#"[]"#,
- Some(
- r#"{"error":{"code":-32600,"data":"batch must not be empty","message":"Invalid Request"},"id":null,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"[{"jsonrpc":"2.0","id":1,"method":"ping"},{"jsonrpc":"2.0","method":"notifications/initialized"},42,{"jsonrpc":"2.0","id":3,"method":"nope"}]"#,
- Some(
- r#"[{"id":1,"jsonrpc":"2.0","result":{}},{"error":{"code":-32600,"data":"message must be a JSON object","message":"Invalid Request"},"id":null,"jsonrpc":"2.0"},{"error":{"code":-32601,"data":"unsupported MCP method `nope`","message":"Method not found"},"id":3,"jsonrpc":"2.0"}]"#,
- ),
- ),
- (
- r#"[{"jsonrpc":"2.0","method":"notifications/initialized"}]"#,
- None,
- ),
- (
- r#"42"#,
- Some(
- r#"{"error":{"code":-32600,"data":"message must be a JSON object","message":"Invalid Request"},"id":null,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1.5,"method":"ping"}"#,
- Some(
- r#"{"error":{"code":-32600,"data":"id must be a string or integer","message":"Invalid Request"},"id":null,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":true,"method":"ping"}"#,
- Some(
- r#"{"error":{"code":-32600,"data":"id must be a string or integer","message":"Invalid Request"},"id":null,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":null,"method":"ping"}"#,
- Some(
- r#"{"error":{"code":-32600,"data":"id must be a string or integer","message":"Invalid Request"},"id":null,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"id":1,"method":"ping"}"#,
- Some(
- r#"{"error":{"code":-32600,"data":"jsonrpc must be \"2.0\"","message":"Invalid Request"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"1.0","id":1,"method":"ping"}"#,
- Some(
- r#"{"error":{"code":-32600,"data":"jsonrpc must be \"2.0\"","message":"Invalid Request"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1}"#,
- Some(
- r#"{"error":{"code":-32600,"data":"method must be a string","message":"Invalid Request"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":5}"#,
- Some(
- r#"{"error":{"code":-32600,"data":"method must be a string","message":"Invalid Request"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"prompts/list"}"#,
- Some(
- r#"{"error":{"code":-32601,"data":"unsupported MCP method `prompts/list`","message":"Method not found"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{not-json"#,
- Some(
- r#"{"error":{"code":-32700,"data":"key must be a string at line 1 column 2","message":"Parse error"},"id":null,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"tools/call"}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"tools/call params must be an object","message":"Invalid params"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":[]}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"tools/call params must be an object","message":"Invalid params"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{}}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"tools/call params.name must be a non-empty string","message":"Invalid params"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":" "}}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"tools/call params.name must be a non-empty string","message":"Invalid params"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"memory.recall","arguments":[1,2]}}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"tools/call params.arguments: tool arguments must be a JSON object, not an array","message":"Invalid params"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"memory.recall","arguments":"not json"}}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"tools/call params.arguments: tool arguments must be a JSON object, not a string that is not JSON","message":"Invalid params"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"memory.recall","arguments":7}}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"tools/call params.arguments: tool arguments must be a JSON object, not a number","message":"Invalid params"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"memory.recall","arguments":{}}}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"missing required argument `question`","message":"Invalid params"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"memory.recall","arguments":"{}"}}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"missing required argument `question`","message":"Invalid params"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"memory.recall"}}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"missing required argument `question`","message":"Invalid params"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"memory.recall","arguments":{"question":"x","bogus":1}}}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"unexpected argument `bogus`","message":"Invalid params"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"no.such_tool","arguments":{}}}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"unknown MCP tool `no.such_tool`","message":"Invalid params"},"id":1,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":12,"method":"resources/read","params":{"uri":"openhuman://prompts/agents/does_not_exist"}}"#,
- Some(
- r#"{"error":{"code":-32002,"data":"no resource with uri `openhuman://prompts/agents/does_not_exist`","message":"Resource not found"},"id":12,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":13,"method":"resources/read","params":{}}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"resources/read params.uri must be a non-empty string","message":"Invalid params"},"id":13,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":13,"method":"resources/read","params":{"uri":" "}}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"resources/read params.uri must be a non-empty string","message":"Invalid params"},"id":13,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":13,"method":"resources/read"}"#,
- Some(
- r#"{"error":{"code":-32602,"data":"resources/read params.uri must be a non-empty string","message":"Invalid params"},"id":13,"jsonrpc":"2.0"}"#,
- ),
- ),
- (
- r#"{"jsonrpc":"2.0","id":14,"method":"resources/templates/list"}"#,
- Some(r#"{"id":14,"jsonrpc":"2.0","result":{"resourceTemplates":[]}}"#),
- ),
- (
- r#"{"jsonrpc":"2.0","id":15,"method":"resources/templates/list","params":{"cursor":"x"}}"#,
- Some(r#"{"id":15,"jsonrpc":"2.0","result":{"resourceTemplates":[]}}"#),
- ),
-];
-
-const TOOLS_LIST_BASE: &str = r#"{"id":2,"jsonrpc":"2.0","result":{"tools":[{"annotations":{"openWorldHint":false,"readOnlyHint":true},"description":"List the live core agent tool catalog that OpenHuman exposes to its orchestrator session.","inputSchema":{"additionalProperties":false,"properties":{},"type":"object"},"name":"core.list_tools","title":"List Core Tools"},{"annotations":{"openWorldHint":false,"readOnlyHint":true},"description":"Emit the markdown tool-use instructions block that OpenHuman injects into prompt-guided agents.","inputSchema":{"additionalProperties":false,"properties":{},"type":"object"},"name":"core.tool_instructions","title":"Get Tool Instructions"},{"annotations":{"openWorldHint":false,"readOnlyHint":true},"description":"List registered sub-agent definitions that the core can dispatch for specialized work.","inputSchema":{"additionalProperties":false,"properties":{},"type":"object"},"name":"agent.list_subagents","title":"List Subagents"},{"annotations":{"destructiveHint":true,"idempotentHint":false,"openWorldHint":true,"readOnlyHint":false},"description":"Run a registered OpenHuman sub-agent directly from the core and return its final response.","inputSchema":{"additionalProperties":false,"properties":{"agent_id":{"description":"Registered sub-agent id (for example `planner`, `code_executor`, `critic`).","type":"string"},"prompt":{"description":"Task prompt for the sub-agent. Include the context it needs because this is a fresh session.","type":"string"}},"required":["agent_id","prompt"],"type":"object"},"name":"agent.run_subagent","title":"Run Subagent"},{"annotations":{"openWorldHint":false,"readOnlyHint":true},"description":"Ask OpenHuman's memory a natural-language question and get a synthesised answer with citations to the stored items it rests on. Read-only. Fails with MEMORY_OFF when no memory engine is usable.","inputSchema":{"additionalProperties":false,"properties":{"filter":{"additionalProperties":false,"description":"Metadata filter; every given field must match. An empty filter matches everything.","properties":{"agent_id":{"description":"Exact id of the agent that produced the item.","minLength":1,"type":"string"},"commit":{"description":"Exact commit.","minLength":1,"type":"string"},"file_path":{"description":"File path, exact or as a path prefix.","minLength":1,"type":"string"},"folder":{"description":"Folder, exact or as a path prefix.","minLength":1,"type":"string"},"kinds":{"description":"Item kinds to include; omit for all.","items":{"enum":["document","conversation","learning"],"type":"string"},"type":"array"},"language":{"description":"Exact language (`rust`, `python`, `en`, ...).","minLength":1,"type":"string"},"observed_after":{"description":"Inclusive lower bound on when the fact was observed (RFC 3339).","format":"date-time","type":"string"},"observed_before":{"description":"Exclusive upper bound on when the fact was observed (RFC 3339).","format":"date-time","type":"string"},"repo":{"description":"Exact repository, `owner/name` or a remote URL.","minLength":1,"type":"string"},"sources":{"description":"Source kinds to include; omit for all.","items":{"enum":["folder","file","link","github","rss","composio","conversation","agent","import"],"type":"string"},"type":"array"},"tags_any":{"description":"Match items carrying any one of these tags.","items":{"minLength":1,"type":"string"},"type":"array"},"thread_id":{"description":"Exact conversation thread id.","minLength":1,"type":"string"},"url":{"description":"Exact URL the item was read from.","minLength":1,"type":"string"},"workspace":{"description":"Exact workspace (absolute path or logical id).","minLength":1,"type":"string"}},"type":"object"},"limit":{"description":"Maximum citations to return. Defaults to 10; capped at 100.","maximum":100,"minimum":1,"type":"integer"},"question":{"description":"The question to answer from memory, in natural language.","minLength":1,"type":"string"}},"required":["question"],"type":"object"},"name":"memory.recall","title":"Recall Memory"},{"annotations":{"openWorldHint":false,"readOnlyHint":true},"description":"Raw retrieval over stored memory items: returns matching hits (text, metadata, score) best first, optionally narrowed by a metadata filter. `mode` must be one the active engine supports; both launch engines (`tinyhumans`, `cortexdb`) support only `hybrid`, so omit `mode` unless you know otherwise. Pass the returned `next_cursor` as `cursor` for the next page. Read-only.","inputSchema":{"additionalProperties":false,"properties":{"cursor":{"description":"`next_cursor` from the previous page.","minLength":1,"type":"string"},"filter":{"additionalProperties":false,"description":"Metadata filter; every given field must match. An empty filter matches everything.","properties":{"agent_id":{"description":"Exact id of the agent that produced the item.","minLength":1,"type":"string"},"commit":{"description":"Exact commit.","minLength":1,"type":"string"},"file_path":{"description":"File path, exact or as a path prefix.","minLength":1,"type":"string"},"folder":{"description":"Folder, exact or as a path prefix.","minLength":1,"type":"string"},"kinds":{"description":"Item kinds to include; omit for all.","items":{"enum":["document","conversation","learning"],"type":"string"},"type":"array"},"language":{"description":"Exact language (`rust`, `python`, `en`, ...).","minLength":1,"type":"string"},"observed_after":{"description":"Inclusive lower bound on when the fact was observed (RFC 3339).","format":"date-time","type":"string"},"observed_before":{"description":"Exclusive upper bound on when the fact was observed (RFC 3339).","format":"date-time","type":"string"},"repo":{"description":"Exact repository, `owner/name` or a remote URL.","minLength":1,"type":"string"},"sources":{"description":"Source kinds to include; omit for all.","items":{"enum":["folder","file","link","github","rss","composio","conversation","agent","import"],"type":"string"},"type":"array"},"tags_any":{"description":"Match items carrying any one of these tags.","items":{"minLength":1,"type":"string"},"type":"array"},"thread_id":{"description":"Exact conversation thread id.","minLength":1,"type":"string"},"url":{"description":"Exact URL the item was read from.","minLength":1,"type":"string"},"workspace":{"description":"Exact workspace (absolute path or logical id).","minLength":1,"type":"string"}},"type":"object"},"limit":{"description":"Maximum hits to return. Defaults to 10; capped at 100.","maximum":100,"minimum":1,"type":"integer"},"mode":{"description":"Retrieval mode. Must be one the active engine supports; both launch engines support only `hybrid`. Omit to use the engine's default.","enum":["keyword","vector","hybrid"],"type":"string"},"query":{"description":"What to search for.","minLength":1,"type":"string"}},"required":["query"],"type":"object"},"name":"memory.fetch","title":"Fetch Memory"},{"annotations":{"openWorldHint":false,"readOnlyHint":true},"description":"Page through stored memory items, newest first, optionally narrowed by a metadata filter. Use this to enumerate (\"what did I store last week\") rather than search by query. Pass the returned `next_cursor` as `cursor` for the next page. Read-only.","inputSchema":{"additionalProperties":false,"properties":{"cursor":{"description":"`next_cursor` from the previous page.","minLength":1,"type":"string"},"filter":{"additionalProperties":false,"description":"Metadata filter; every given field must match. An empty filter matches everything.","properties":{"agent_id":{"description":"Exact id of the agent that produced the item.","minLength":1,"type":"string"},"commit":{"description":"Exact commit.","minLength":1,"type":"string"},"file_path":{"description":"File path, exact or as a path prefix.","minLength":1,"type":"string"},"folder":{"description":"Folder, exact or as a path prefix.","minLength":1,"type":"string"},"kinds":{"description":"Item kinds to include; omit for all.","items":{"enum":["document","conversation","learning"],"type":"string"},"type":"array"},"language":{"description":"Exact language (`rust`, `python`, `en`, ...).","minLength":1,"type":"string"},"observed_after":{"description":"Inclusive lower bound on when the fact was observed (RFC 3339).","format":"date-time","type":"string"},"observed_before":{"description":"Exclusive upper bound on when the fact was observed (RFC 3339).","format":"date-time","type":"string"},"repo":{"description":"Exact repository, `owner/name` or a remote URL.","minLength":1,"type":"string"},"sources":{"description":"Source kinds to include; omit for all.","items":{"enum":["folder","file","link","github","rss","composio","conversation","agent","import"],"type":"string"},"type":"array"},"tags_any":{"description":"Match items carrying any one of these tags.","items":{"minLength":1,"type":"string"},"type":"array"},"thread_id":{"description":"Exact conversation thread id.","minLength":1,"type":"string"},"url":{"description":"Exact URL the item was read from.","minLength":1,"type":"string"},"workspace":{"description":"Exact workspace (absolute path or logical id).","minLength":1,"type":"string"}},"type":"object"},"limit":{"description":"Maximum items to return. Defaults to 10; capped at 100.","maximum":100,"minimum":1,"type":"integer"}},"required":[],"type":"object"},"name":"memory.list","title":"List Memory Items"},{"annotations":{"destructiveHint":false,"idempotentHint":false,"openWorldHint":false,"readOnlyHint":false},"description":"Store one explicit learning (a preference, fact, procedure or correction) in OpenHuman's memory. Returns the new item id. Adds an item; never modifies or removes existing ones.","inputSchema":{"additionalProperties":false,"properties":{"confidence":{"description":"Confidence in the learning, 0 to 1. Defaults to 0.8.","maximum":1,"minimum":0,"type":"number"},"kind":{"description":"What kind of learning this is. Defaults to `fact`.","enum":["preference","fact","procedure","correction","other"],"type":"string"},"text":{"description":"What was learned, as a self-contained statement.","minLength":1,"type":"string"}},"required":["text"],"type":"object"},"name":"memory.learn","title":"Learn Memory"},{"annotations":{"destructiveHint":true,"idempotentHint":true,"openWorldHint":false,"readOnlyHint":false},"description":"Permanently remove memory items by id (ids come from memory.fetch, memory.list or the citations of memory.recall). Returns how many were forgotten. This cannot be undone.","inputSchema":{"additionalProperties":false,"properties":{"ids":{"description":"Ids of the memory items to remove permanently.","items":{"minLength":1,"type":"string"},"maxItems":100,"minItems":1,"type":"array"}},"required":["ids"],"type":"object"},"name":"memory.forget","title":"Forget Memory"}]}}"#;
-
-/// The resource catalog's ungated head. The tail depends on the `flows` and
-/// `skills` features, so it is checked by shape rather than by bytes.
-const RESOURCES_LIST_PREFIX: &str = r#"{"id":10,"jsonrpc":"2.0","result":{"resources":[{"description":"Core agent identity definition (IDENTITY.md).","mimeType":"text/markdown","name":"Agent Identity","uri":"openhuman://prompts/identity"},{"description":"Core agent personality and values (SOUL.md).","mimeType":"text/markdown","name":"Agent Soul","uri":"openhuman://prompts/soul"},{"description":"Core user-profile context injected into every session (USER.md).","mimeType":"text/markdown","name":"User Context","uri":"openhuman://prompts/user"},"#;
-
-fn golden(expected: &str) -> String {
- expected.replace(VERSION_PLACEHOLDER, env!("CARGO_PKG_VERSION"))
-}
-
-#[tokio::test]
-async fn every_line_case_answers_with_its_golden_bytes() {
- for (request, expected) in LINE_CASES {
- let actual = dispatch_line(request).await;
- assert_eq!(
- actual,
- expected.map(golden),
- "wire drift for request {request}"
- );
- }
-}
-
-#[tokio::test]
-async fn tools_list_answers_with_the_golden_base_catalog() {
- let line = dispatch_line(r#"{"jsonrpc":"2.0","id":2,"method":"tools/list"}"#)
- .await
- .expect("tools/list answers");
- let mut response: Value = serde_json::from_str(&line).expect("json response");
- response["result"]["tools"]
- .as_array_mut()
- .expect("tools array")
- .retain(|tool| !CONFIG_GATED_TOOLS.contains(&tool["name"].as_str().expect("tool name")));
- assert_eq!(response.to_string(), TOOLS_LIST_BASE);
-}
-
-#[tokio::test]
-async fn resources_list_answers_with_the_golden_catalog_shape() {
- let line = dispatch_line(r#"{"jsonrpc":"2.0","id":10,"method":"resources/list"}"#)
- .await
- .expect("resources/list answers");
- assert!(
- line.starts_with(RESOURCES_LIST_PREFIX),
- "resources/list head drifted: {line}"
- );
- let response: Value = serde_json::from_str(&line).expect("json response");
- for resource in response["result"]["resources"].as_array().expect("array") {
- let mut keys = resource
- .as_object()
- .expect("resource object")
- .keys()
- .cloned()
- .collect::<Vec<_>>();
- keys.sort();
- assert_eq!(keys, ["description", "mimeType", "name", "uri"]);
- assert_eq!(resource["mimeType"], "text/markdown");
- }
-}
-
-#[tokio::test]
-async fn resources_read_answers_with_the_embedded_prompt() {
- let line = dispatch_line(
- r#"{"jsonrpc":"2.0","id":11,"method":"resources/read","params":{"uri":"openhuman://prompts/identity"}}"#,
- )
- .await
- .expect("resources/read answers");
- let expected = serde_json::json!({
- "jsonrpc": "2.0",
- "id": 11,
- "result": {
- "contents": [{
- "uri": "openhuman://prompts/identity",
- "mimeType": "text/markdown",
- "text": include_str!("../../agent/prompts/IDENTITY.md"),
- }]
- }
- });
- assert_eq!(line, expected.to_string());
-}