Watch
0
0
Fork
You've already forked hyperhive
0

hive-matrix-mcp: test reading, members, joining, files, unread summaries and the MCP tools

This commit is contained in:
damocles 2026-11-17 00:17:42 +01:00 • committed by mara
commit 2e30163d5c
4 changed files with 299 additions and 0 deletions

1
Cargo.lock generated
View file

@ -2064,6 +2064,7 @@ dependencies = [
"tokio",
"tracing",
"tracing-subscriber",
"wiremock",
]
[[package]]

View file

@ -43,4 +43,6 @@ tempfile = "3"
# The SDK's own mock homeserver (`matrix_sdk::test_utils::mocks`), for the handler tests.
matrix-sdk = { workspace = true, features = ["testing"] }
matrix-sdk-test = "0.18"
# `join_room_by_id_or_alias` posts to `/join/<id>`, which the mock server has no mock for.
wiremock = "0.6"
tokio = { workspace = true, features = ["test-util"] }

View file

@ -236,3 +236,214 @@ async fn rejecting_an_invite_leaves_the_room() {
assert_eq!(got["rejected"], true);
assert_eq!(got["room_id"], "!invited:localhost");
}
#[tokio::test]
async fn reading_a_room_returns_its_events_newest_first_with_sender_and_body() {
let (_server, client) = room_with(vec![
bobs_message("$two:localhost", "second"),
bobs_message("$one:localhost", "first"),
])
.await;
let got = ok(read_room(&client, "!room:localhost", None, None, None).await);
let events = got.as_array().expect("a list");
assert_eq!(events.len(), 2);
assert_eq!(events[0]["event_id"], "$two:localhost");
assert_eq!(events[0]["sender"], "@bob:localhost");
assert_eq!(events[0]["body"], "second");
assert_eq!(events[1]["body"], "first");
}
#[tokio::test]
async fn a_read_asks_for_the_limit_clamped_to_the_allowed_range() {
let server = MatrixMockServer::new().await;
let client = server.client_builder().build().await;
server
.sync_joined_room(&client, room_id!("!room:localhost"))
.await;
server.mock_room_state_encryption().plain().mount().await;
server
.mock_room_messages()
.match_limit(200)
.ok(RoomMessagesResponseTemplate::default())
.expect(1)
.mount()
.await;
ok(read_room(&client, "!room:localhost", Some(5000), None, None).await);
}
#[tokio::test]
async fn a_read_with_both_anchors_or_a_bad_anchor_is_refused() {
let (_server, client) = caught_up_room().await;
let both = err(read_room(
&client,
"!room:localhost",
None,
Some("$a:localhost".to_owned()),
Some("$b:localhost".to_owned()),
)
.await);
assert!(both.contains("mutually exclusive"), "{both}");
let bad = err(read_room(
&client,
"!room:localhost",
None,
Some("nope".to_owned()),
None,
)
.await);
assert!(bad.contains("invalid event_id"), "{bad}");
}
#[tokio::test]
async fn the_joined_members_are_listed_with_their_display_names() {
let (server, client) = caught_up_room().await;
let f = EventFactory::new().room(room_id!("!room:localhost"));
server
.mock_get_members()
.ok(vec![
f.member(user_id!("@bob:localhost"))
.display_name("Bob")
.into_raw(),
])
.mount()
.await;
let got = ok(list_room_members(&client, "!room:localhost").await);
let members = got.as_array().expect("a list");
assert_eq!(members.len(), 1);
assert_eq!(members[0]["user_id"], "@bob:localhost");
assert_eq!(members[0]["display_name"], "Bob");
}
/// `join_room_by_id_or_alias` posts to `/join/<room>`, which the SDK's mock
/// server has no prefab for (`mock_room_join` is `/rooms/<room>/join`).
async fn mock_join(server: &MatrixMockServer, room: &str) {
use wiremock::matchers::{method, path};
use wiremock::{Mock, ResponseTemplate};
Mock::given(method("POST"))
.and(path(format!("/_matrix/client/v3/join/{room}")))
.respond_with(
ResponseTemplate::new(200).set_body_json(serde_json::json!({"room_id": room})),
)
.expect(1)
.mount(server.server())
.await;
}
#[tokio::test]
async fn joining_a_room_asks_the_server_and_a_bad_reference_is_refused() {
let (server, client) = caught_up_room().await;
mock_join(&server, "!other:localhost").await;
let got = ok(join_room(&client, "!other:localhost").await);
assert_eq!(got["joined"], true);
assert_eq!(got["room_id"], "!other:localhost");
let bad = err(join_room(&client, "not a room").await);
assert!(bad.contains("invalid room reference"), "{bad}");
}
#[tokio::test]
async fn accepting_an_invite_is_joining_the_room() {
let (server, client) = caught_up_room().await;
mock_join(&server, "!invited:localhost").await;
let got = ok(resolve_invite(&client, "!invited:localhost", InviteAction::Accept).await);
assert_eq!(got["joined"], true);
}
#[tokio::test]
async fn the_rooms_with_unread_messages_are_summarised_with_the_latest_sender() {
let (_server, client) = room_with(vec![bobs_message("$new:localhost", "are you there?")]).await;
let got = ok(unread_summary(&client).await);
let rooms = got.as_array().expect("a list");
assert_eq!(rooms.len(), 1);
assert_eq!(rooms[0]["label"], "!room:localhost");
assert_eq!(rooms[0]["last_sender"], "@bob:localhost");
assert_eq!(rooms[0]["last_body"], "are you there?");
}
#[tokio::test]
async fn a_caught_up_room_has_nothing_to_summarise() {
let (_server, client) = caught_up_room().await;
let got = ok(unread_summary(&client).await);
assert_eq!(got.as_array().expect("a list").len(), 0);
}
#[tokio::test]
async fn a_file_is_uploaded_and_posted_with_its_guessed_type_and_a_caption() {
let (server, client) = caught_up_room().await;
// The SDK asks for the server's upload limit before it uploads.
server
.mock_authenticated_media_config()
.ok_default()
.mount()
.await;
server
.mock_media_config()
.ok(matrix_sdk::ruma::UInt::from(10_000_000_u32))
.mount()
.await;
let (captured, upload) = server
.mock_upload()
.ok_with_capture(matrix_sdk::ruma::mxc_uri!("mxc://localhost/abc"));
upload.mount().await;
server
.mock_room_send()
.ok(event_id!("$file:localhost"))
.expect(2)
.mount()
.await;
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("notes.txt");
std::fs::write(&path, b"hello").unwrap();
let got = ok(send_file(
&client,
"!room:localhost",
path.to_str().unwrap(),
Some("the notes"),
)
.await);
assert_eq!(got["filename"], "notes.txt");
assert_eq!(got["mime"], "text/plain");
assert_eq!(got["event_id"], "$file:localhost");
assert_eq!(captured.await.unwrap(), b"hello");
}
#[tokio::test]
async fn a_file_that_is_missing_or_not_a_file_is_refused_before_any_upload() {
let (_server, client) = caught_up_room().await;
let dir = tempfile::tempdir().unwrap();
let missing = err(send_file(&client, "!room:localhost", "/nonexistent/file", None).await);
assert!(missing.contains("stat /nonexistent/file"), "{missing}");
let directory = err(send_file(
&client,
"!room:localhost",
dir.path().to_str().unwrap(),
None,
)
.await);
assert!(directory.contains("not a regular file"), "{directory}");
}
#[tokio::test]
async fn a_file_waits_for_the_agent_to_catch_up_like_a_message() {
let (_server, client) = room_with(vec![bobs_message("$new:localhost", "hi")]).await;
let message = err(send_file(&client, "!room:localhost", "/nonexistent", None).await);
assert!(message.contains("unread message"), "{message}");
}

View file

@ -610,3 +610,88 @@ pub async fn serve_http(addr: std::net::SocketAddr, registry: Arc<Registry>) ->
axum::serve(listener, app).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use matrix_sdk::ruma::room_id;
use matrix_sdk::test_utils::mocks::MatrixMockServer;
use super::*;
/// A tool set whose only account, the primary, is a client of `server` that
/// has joined `!room:localhost`.
async fn tools_on(server: &MatrixMockServer) -> MatrixMcp {
let client = server.client_builder().build().await;
server
.sync_joined_room(&client, room_id!("!room:localhost"))
.await;
let registry = Registry::new("main".to_owned());
registry.insert("main".to_owned(), client);
MatrixMcp {
registry: Arc::new(registry),
}
}
#[test]
fn an_ok_is_pretty_json_and_an_error_says_it_is_one() {
let ok = render(DaemonResponse::ok(&serde_json::json!({"a": 1})));
assert_eq!(ok, "{\n \"a\": 1\n}");
assert_eq!(
render(DaemonResponse::error("no room")),
"matrix error: no room"
);
}
#[tokio::test]
async fn a_tool_acts_as_the_primary_account_when_none_is_named() {
let server = MatrixMockServer::new().await;
let tools = tools_on(&server).await;
let out = tools
.list_rooms(Parameters(ListRoomsArgs { account: None }))
.await;
assert!(out.contains("!room:localhost"), "{out}");
}
#[tokio::test]
async fn a_tool_for_an_unknown_account_says_which_ones_exist() {
let server = MatrixMockServer::new().await;
let tools = tools_on(&server).await;
let out = tools
.list_rooms(Parameters(ListRoomsArgs {
account: Some("other".to_owned()),
}))
.await;
assert!(out.starts_with("matrix error: "), "{out}");
assert!(out.contains("available accounts: [main]"), "{out}");
}
#[tokio::test]
async fn the_unread_summary_endpoint_answers_for_the_primary_account() {
let server = MatrixMockServer::new().await;
let tools = tools_on(&server).await;
server.mock_room_state_encryption().plain().mount().await;
server
.mock_room_messages()
.ok(matrix_sdk::test_utils::mocks::RoomMessagesResponseTemplate::default())
.mount()
.await;
let axum::Json(body) = unread_summary_handler(axum::extract::State(tools.registry)).await;
assert_eq!(body["kind"], "ok");
assert_eq!(body["payload"], serde_json::json!([]));
}
#[tokio::test]
async fn the_unread_summary_endpoint_reports_a_registry_without_accounts() {
let registry = Arc::new(Registry::new("main".to_owned()));
let axum::Json(body) = unread_summary_handler(axum::extract::State(registry)).await;
assert_eq!(body["kind"], "error");
}
}