| 1 | use std::collections::BTreeSet; |
| 2 | use std::sync::Arc; |
| 3 | |
| 4 | use base64::Engine; |
| 5 | use base64::engine::general_purpose::STANDARD; |
| 6 | use chrono::{DateTime, TimeZone, Utc}; |
| 7 | use mcp::{ |
| 8 | Access, AgentHub, AgentPolicy, EncodedImage, FileInfo, ImageInfo, ImageKind, LinkInfo, Meeting, |
| 9 | MentionInfo, MessageExtras, Outcome, QuoteInfo, ReactionInfo, ServerHandle, SourceError, |
| 10 | SourceFuture, TeamsSource, Transcript, TranscriptTurn, |
| 11 | }; |
| 12 | use rmcp::ServiceExt; |
| 13 | use rmcp::model::{CallToolRequestParams, CallToolResult, ClientConfig}; |
| 14 | use rmcp::service::RunningService; |
| 15 | use rmcp::transport::StreamableHttpClientTransport; |
| 16 | use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig; |
| 17 | use serde_json::{Value, json}; |
| 18 | use store::{ChannelRecord, ChatRecord, MessageRecord, Store, TeamRecord}; |
| 19 | use tokio::io::{AsyncReadExt, AsyncWriteExt}; |
| 20 | use tokio::net::TcpStream; |
| 21 | |
| 22 | const TOKEN: &str = "test-token"; |
| 23 | const ALLOWED_CHAT: &str = "19:alpha@thread.v2"; |
| 24 | const HIDDEN_CHAT: &str = "19:beta@thread.v2"; |
| 25 | const CHANNEL: &str = "19:channel@thread.tacv2"; |
| 26 | const MEETING_CHAT: &str = "19:meeting_abc@thread.v2"; |
| 27 | const LIVE_MEETING_CHAT: &str = "19:meeting_live@thread.v2"; |
| 28 | const HIDDEN_MEETING_CHAT: &str = "19:meeting_hidden@thread.v2"; |
| 29 | const RICH_MESSAGE: &str = "m5"; |
| 30 | const RICH_IMAGE: &str = "0-1a2b3c4d"; |
| 31 | const PIXEL_PNG: [u8; 67] = [ |
| 32 | 0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, |
| 33 | 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4, |
| 34 | 0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0x00, 0x01, 0x00, 0x00, |
| 35 | 0x05, 0x00, 0x01, 0x0D, 0x0A, 0x2D, 0xB4, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4E, 0x44, 0xAE, |
| 36 | 0x42, 0x60, 0x82, |
| 37 | ]; |
| 38 | |
| 39 | struct FakeSource { |
| 40 | store: Arc<Store>, |
| 41 | } |
| 42 | |
| 43 | impl TeamsSource for FakeSource { |
| 44 | fn store(&self) -> Result<Arc<Store>, SourceError> { |
| 45 | Ok(self.store.clone()) |
| 46 | } |
| 47 | |
| 48 | fn me_id(&self) -> Option<String> { |
| 49 | Some("user-me".to_owned()) |
| 50 | } |
| 51 | |
| 52 | fn message_extras(&self, message: &MessageRecord, _my_user_id: Option<&str>) -> MessageExtras { |
| 53 | let text = store::plain_text(&message.body_html); |
| 54 | if message.message_id != RICH_MESSAGE { |
| 55 | return MessageExtras { |
| 56 | text, |
| 57 | ..MessageExtras::default() |
| 58 | }; |
| 59 | } |
| 60 | MessageExtras { |
| 61 | text, |
| 62 | images: vec![ImageInfo { |
| 63 | image_id: RICH_IMAGE.to_owned(), |
| 64 | kind: ImageKind::Gif, |
| 65 | alt: Some("dancing cat".to_owned()), |
| 66 | }], |
| 67 | reactions: vec![ReactionInfo { |
| 68 | emoji: "\u{1F44D}".to_owned(), |
| 69 | count: 2, |
| 70 | mine: true, |
| 71 | }], |
| 72 | mentions: vec![MentionInfo { |
| 73 | name: "Bob Sample".to_owned(), |
| 74 | user_id: Some("user-bob".to_owned()), |
| 75 | }], |
| 76 | files: vec![FileInfo { |
| 77 | name: "Plan.docx".to_owned(), |
| 78 | size: None, |
| 79 | file_type: Some("word".to_owned()), |
| 80 | link: "https://example.sharepoint.com/Plan.docx".to_owned(), |
| 81 | }], |
| 82 | quote: Some(QuoteInfo { |
| 83 | message_id: "m1".to_owned(), |
| 84 | sender: Some("Ada Example".to_owned()), |
| 85 | text: "budget plan".to_owned(), |
| 86 | }), |
| 87 | cards: vec!["Build passed".to_owned()], |
| 88 | links: vec![LinkInfo { |
| 89 | url: "https://news.example.com/story".to_owned(), |
| 90 | title: Some("A story".to_owned()), |
| 91 | }], |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | fn image<'a>( |
| 96 | &'a self, |
| 97 | _message: &'a MessageRecord, |
| 98 | _image_id: &'a str, |
| 99 | _max_edge: u32, |
| 100 | ) -> SourceFuture<'a, EncodedImage> { |
| 101 | Box::pin(async { |
| 102 | Ok(EncodedImage { |
| 103 | bytes: PIXEL_PNG.to_vec(), |
| 104 | mime_type: "image/png".to_owned(), |
| 105 | kind: ImageKind::Gif, |
| 106 | alt: Some("dancing cat".to_owned()), |
| 107 | width: 1, |
| 108 | height: 1, |
| 109 | }) |
| 110 | }) |
| 111 | } |
| 112 | |
| 113 | fn calendar(&self, start: DateTime<Utc>, end: DateTime<Utc>) -> SourceFuture<'_, Vec<Meeting>> { |
| 114 | let meeting = Meeting { |
| 115 | title: "Sprint review".to_owned(), |
| 116 | start: Utc.with_ymd_and_hms(2026, 10, 7, 9, 0, 0).unwrap(), |
| 117 | end: Utc.with_ymd_and_hms(2026, 10, 7, 10, 0, 0).unwrap(), |
| 118 | all_day: false, |
| 119 | organizer: Some("Ada Example".to_owned()), |
| 120 | join_url: Some("https://teams.example/join".to_owned()), |
| 121 | meeting_chat_id: Some(MEETING_CHAT.to_owned()), |
| 122 | }; |
| 123 | Box::pin(async move { |
| 124 | Ok(vec![meeting] |
| 125 | .into_iter() |
| 126 | .filter(|meeting| meeting.start >= start && meeting.start < end) |
| 127 | .collect()) |
| 128 | }) |
| 129 | } |
| 130 | |
| 131 | fn transcript<'a>(&'a self, meeting_chat_id: &'a str) -> SourceFuture<'a, Transcript> { |
| 132 | Box::pin(async move { |
| 133 | if meeting_chat_id != MEETING_CHAT { |
| 134 | return Err(SourceError::Failed( |
| 135 | "no finished recording in this meeting chat".to_owned(), |
| 136 | )); |
| 137 | } |
| 138 | Ok(Transcript { |
| 139 | recording_name: Some("Sprint review".to_owned()), |
| 140 | created_at: None, |
| 141 | turns: vec![TranscriptTurn { |
| 142 | speaker: "Ada Example".to_owned(), |
| 143 | start_seconds: 1.0, |
| 144 | end_seconds: 4.5, |
| 145 | text: "Welcome everyone".to_owned(), |
| 146 | }], |
| 147 | }) |
| 148 | }) |
| 149 | } |
| 150 | } |
| 151 | |
| 152 | struct Harness { |
| 153 | store: Arc<Store>, |
| 154 | hub: Arc<AgentHub>, |
| 155 | server: ServerHandle, |
| 156 | } |
| 157 | |
| 158 | impl Harness { |
| 159 | async fn start(propose: bool) -> Harness { |
| 160 | Harness::start_with(propose, false, false).await |
| 161 | } |
| 162 | |
| 163 | async fn start_with(propose: bool, calendar: bool, transcripts: bool) -> Harness { |
| 164 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 165 | seed(&store); |
| 166 | let policy = AgentPolicy { |
| 167 | enabled: true, |
| 168 | chats: Access::Selected(BTreeSet::from([ |
| 169 | ALLOWED_CHAT.to_owned(), |
| 170 | MEETING_CHAT.to_owned(), |
| 171 | LIVE_MEETING_CHAT.to_owned(), |
| 172 | ])), |
| 173 | channels: Access::Selected(BTreeSet::from([CHANNEL.to_owned()])), |
| 174 | propose, |
| 175 | calendar, |
| 176 | transcripts, |
| 177 | ..AgentPolicy::default() |
| 178 | }; |
| 179 | let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel(); |
| 180 | let hub = AgentHub::new(store.clone(), policy, ui); |
| 181 | let server = mcp::start( |
| 182 | hub.clone(), |
| 183 | Arc::new(FakeSource { |
| 184 | store: store.clone(), |
| 185 | }), |
| 186 | 0, |
| 187 | TOKEN.to_owned(), |
| 188 | ) |
| 189 | .await |
| 190 | .unwrap(); |
| 191 | Harness { store, hub, server } |
| 192 | } |
| 193 | |
| 194 | fn url(&self) -> String { |
| 195 | format!("http://{}/mcp", self.server.addr) |
| 196 | } |
| 197 | |
| 198 | async fn client(&self) -> RunningService<rmcp::RoleClient, ClientConfig> { |
| 199 | let transport = StreamableHttpClientTransport::from_config( |
| 200 | StreamableHttpClientTransportConfig::with_uri(self.url()).auth_header(TOKEN), |
| 201 | ); |
| 202 | ClientConfig::default().serve(transport).await.unwrap() |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | fn seed(store: &Store) { |
| 207 | let time = |minute: u32| Utc.with_ymd_and_hms(2026, 10, 6, 9, minute, 0).unwrap(); |
| 208 | let chat_of_kind = |id: &str, kind: &str, title: &str| ChatRecord { |
| 209 | id: id.to_owned(), |
| 210 | kind: kind.to_owned(), |
| 211 | title: title.to_owned(), |
| 212 | last_message_at: Some(time(5)), |
| 213 | ..ChatRecord::default() |
| 214 | }; |
| 215 | let chat = |id: &str, title: &str| chat_of_kind(id, "group", title); |
| 216 | store |
| 217 | .upsert_chats(&[ |
| 218 | chat(ALLOWED_CHAT, "Planning"), |
| 219 | chat(HIDDEN_CHAT, "Secrets"), |
| 220 | chat_of_kind(MEETING_CHAT, "meeting", "Sprint review"), |
| 221 | chat_of_kind(LIVE_MEETING_CHAT, "meeting", "Live sync"), |
| 222 | chat_of_kind(HIDDEN_MEETING_CHAT, "meeting", "Board meeting"), |
| 223 | ]) |
| 224 | .unwrap(); |
| 225 | store |
| 226 | .upsert_teams(&[TeamRecord { |
| 227 | id: "team-1".to_owned(), |
| 228 | name: "Platform".to_owned(), |
| 229 | }]) |
| 230 | .unwrap(); |
| 231 | store |
| 232 | .upsert_channels(&[ChannelRecord { |
| 233 | id: CHANNEL.to_owned(), |
| 234 | team_id: "team-1".to_owned(), |
| 235 | name: "General".to_owned(), |
| 236 | membership_type: None, |
| 237 | last_message_at: Some(time(6)), |
| 238 | unread: false, |
| 239 | }]) |
| 240 | .unwrap(); |
| 241 | let message = |
| 242 | |conversation_id: &str, message_id: &str, minute: u32, html: &str| MessageRecord { |
| 243 | conversation_id: conversation_id.to_owned(), |
| 244 | message_id: message_id.to_owned(), |
| 245 | sender_id: Some("user-ada".to_owned()), |
| 246 | sender_name: Some("Ada Example".to_owned()), |
| 247 | created_at: time(minute), |
| 248 | body_html: html.to_owned(), |
| 249 | attachments_json: "[]".to_owned(), |
| 250 | reactions_json: "[]".to_owned(), |
| 251 | mentions_json: "[]".to_owned(), |
| 252 | links_json: "[]".to_owned(), |
| 253 | ..MessageRecord::default() |
| 254 | }; |
| 255 | store |
| 256 | .upsert_messages(&[ |
| 257 | message(ALLOWED_CHAT, "m1", 1, "<p>budget <b>plan</b></p>"), |
| 258 | message(ALLOWED_CHAT, "m2", 2, "<p>lunch at noon</p>"), |
| 259 | message(HIDDEN_CHAT, "m3", 3, "<p>budget secrets</p>"), |
| 260 | message(CHANNEL, "m4", 4, "<p>budget channel post</p>"), |
| 261 | message(ALLOWED_CHAT, RICH_MESSAGE, 7, "<p>see the cat</p>"), |
| 262 | message(CHANNEL, "t1", 8, "<p>thread root</p>"), |
| 263 | MessageRecord { |
| 264 | reply_to_id: Some("t1".to_owned()), |
| 265 | ..message(CHANNEL, "t2", 9, "<p>thread reply</p>") |
| 266 | }, |
| 267 | ]) |
| 268 | .unwrap(); |
| 269 | } |
| 270 | |
| 271 | async fn call( |
| 272 | client: &RunningService<rmcp::RoleClient, ClientConfig>, |
| 273 | tool: &'static str, |
| 274 | arguments: Value, |
| 275 | ) -> (bool, String) { |
| 276 | let params = CallToolRequestParams::new(tool) |
| 277 | .with_arguments(arguments.as_object().cloned().unwrap_or_default()); |
| 278 | let result = client.call_tool(params).await.unwrap(); |
| 279 | let text = result |
| 280 | .content |
| 281 | .first() |
| 282 | .and_then(|content| content.as_text()) |
| 283 | .map(|text| text.text.clone()) |
| 284 | .unwrap_or_default(); |
| 285 | (result.is_error == Some(true), text) |
| 286 | } |
| 287 | |
| 288 | async fn call_raw( |
| 289 | client: &RunningService<rmcp::RoleClient, ClientConfig>, |
| 290 | tool: &'static str, |
| 291 | arguments: Value, |
| 292 | ) -> CallToolResult { |
| 293 | let params = CallToolRequestParams::new(tool) |
| 294 | .with_arguments(arguments.as_object().cloned().unwrap_or_default()); |
| 295 | client.call_tool(params).await.unwrap() |
| 296 | } |
| 297 | |
| 298 | fn json_of(text: &str) -> Value { |
| 299 | serde_json::from_str(text).unwrap() |
| 300 | } |
| 301 | |
| 302 | fn message_ids(body: &Value) -> Vec<&str> { |
| 303 | body["messages"] |
| 304 | .as_array() |
| 305 | .unwrap() |
| 306 | .iter() |
| 307 | .map(|message| message["message_id"].as_str().unwrap()) |
| 308 | .collect() |
| 309 | } |
| 310 | |
| 311 | async fn raw_status(addr: std::net::SocketAddr, host: &str, authorization: Option<&str>) -> u16 { |
| 312 | let mut stream = TcpStream::connect(addr).await.unwrap(); |
| 313 | let authorization = authorization |
| 314 | .map(|value| format!("Authorization: {value}\r\n")) |
| 315 | .unwrap_or_default(); |
| 316 | let request = format!( |
| 317 | "POST /mcp HTTP/1.1\r\nHost: {host}\r\n{authorization}Content-Type: application/json\r\nContent-Length: 2\r\nConnection: close\r\n\r\n{{}}" |
| 318 | ); |
| 319 | stream.write_all(request.as_bytes()).await.unwrap(); |
| 320 | let mut response = String::new(); |
| 321 | stream.read_to_string(&mut response).await.unwrap(); |
| 322 | response.split_whitespace().nth(1).unwrap().parse().unwrap() |
| 323 | } |
| 324 | |
| 325 | #[tokio::test] |
| 326 | async fn lists_all_ten_tools_and_marks_reads_read_only() { |
| 327 | let harness = Harness::start(true).await; |
| 328 | let client = harness.client().await; |
| 329 | let tools = client.list_all_tools().await.unwrap(); |
| 330 | let mut names: Vec<String> = tools.iter().map(|tool| tool.name.to_string()).collect(); |
| 331 | names.sort(); |
| 332 | for tool in &tools { |
| 333 | let read_only = tool |
| 334 | .annotations |
| 335 | .as_ref() |
| 336 | .and_then(|annotations| annotations.read_only_hint); |
| 337 | assert_eq!( |
| 338 | read_only == Some(true), |
| 339 | tool.name != "propose_message", |
| 340 | "{}", |
| 341 | tool.name |
| 342 | ); |
| 343 | } |
| 344 | assert_eq!( |
| 345 | names, |
| 346 | [ |
| 347 | "get_image", |
| 348 | "get_transcript", |
| 349 | "list_channels", |
| 350 | "list_chats", |
| 351 | "list_meetings", |
| 352 | "propose_message", |
| 353 | "read_messages", |
| 354 | "recent_messages", |
| 355 | "search_messages", |
| 356 | "wait_for_event" |
| 357 | ] |
| 358 | ); |
| 359 | let info = client.peer_info().unwrap(); |
| 360 | assert_eq!(info.server_info.as_ref().unwrap().name, "rusty-teams"); |
| 361 | } |
| 362 | |
| 363 | #[tokio::test] |
| 364 | async fn rejects_missing_token_bad_host_and_serves_healthz() { |
| 365 | let harness = Harness::start(true).await; |
| 366 | let addr = harness.server.addr; |
| 367 | let own_host = addr.to_string(); |
| 368 | assert_eq!(raw_status(addr, &own_host, None).await, 401); |
| 369 | assert_eq!(raw_status(addr, &own_host, Some("Bearer wrong")).await, 401); |
| 370 | assert_eq!( |
| 371 | raw_status(addr, "evil.example", Some("Bearer test-token")).await, |
| 372 | 403 |
| 373 | ); |
| 374 | let authorized = raw_status(addr, &own_host, Some("Bearer test-token")).await; |
| 375 | assert!(authorized != 401 && authorized != 403, "{authorized}"); |
| 376 | |
| 377 | let mut stream = TcpStream::connect(addr).await.unwrap(); |
| 378 | stream |
| 379 | .write_all( |
| 380 | format!("GET /healthz HTTP/1.1\r\nHost: {own_host}\r\nConnection: close\r\n\r\n") |
| 381 | .as_bytes(), |
| 382 | ) |
| 383 | .await |
| 384 | .unwrap(); |
| 385 | let mut response = String::new(); |
| 386 | stream.read_to_string(&mut response).await.unwrap(); |
| 387 | assert!(response.starts_with("HTTP/1.1 200"), "{response}"); |
| 388 | assert!(response.ends_with("ok"), "{response}"); |
| 389 | } |
| 390 | |
| 391 | #[tokio::test] |
| 392 | async fn lists_only_allowed_conversations() { |
| 393 | let harness = Harness::start(true).await; |
| 394 | let client = harness.client().await; |
| 395 | let (_, chats) = call(&client, "list_chats", json!({})).await; |
| 396 | let chats: Value = serde_json::from_str(&chats).unwrap(); |
| 397 | let mut ids: Vec<&str> = chats["chats"] |
| 398 | .as_array() |
| 399 | .unwrap() |
| 400 | .iter() |
| 401 | .map(|chat| chat["id"].as_str().unwrap()) |
| 402 | .collect(); |
| 403 | ids.sort_unstable(); |
| 404 | let mut expected = vec![ALLOWED_CHAT, MEETING_CHAT, LIVE_MEETING_CHAT]; |
| 405 | expected.sort_unstable(); |
| 406 | assert_eq!(ids, expected); |
| 407 | let (_, channels) = call(&client, "list_channels", json!({})).await; |
| 408 | let channels: Value = serde_json::from_str(&channels).unwrap(); |
| 409 | assert_eq!(channels["channels"][0]["team"], "Platform"); |
| 410 | assert_eq!(channels["channels"][0]["channel"], "General"); |
| 411 | } |
| 412 | |
| 413 | #[tokio::test] |
| 414 | async fn read_messages_respects_scope_and_paging() { |
| 415 | let harness = Harness::start(true).await; |
| 416 | let client = harness.client().await; |
| 417 | let (is_error, text) = call( |
| 418 | &client, |
| 419 | "read_messages", |
| 420 | json!({"conversation_id": HIDDEN_CHAT}), |
| 421 | ) |
| 422 | .await; |
| 423 | assert!(is_error); |
| 424 | assert!( |
| 425 | text.contains("conversation not found or not allowed"), |
| 426 | "{text}" |
| 427 | ); |
| 428 | let (is_error, unknown) = call( |
| 429 | &client, |
| 430 | "read_messages", |
| 431 | json!({"conversation_id": "19:nope@thread.v2"}), |
| 432 | ) |
| 433 | .await; |
| 434 | assert!(is_error); |
| 435 | assert_eq!(unknown, text); |
| 436 | |
| 437 | let (is_error, body) = call( |
| 438 | &client, |
| 439 | "read_messages", |
| 440 | json!({"conversation_id": ALLOWED_CHAT}), |
| 441 | ) |
| 442 | .await; |
| 443 | assert!(!is_error, "{body}"); |
| 444 | let body: Value = serde_json::from_str(&body).unwrap(); |
| 445 | assert_eq!(body["messages"][0]["text"], "budget plan"); |
| 446 | assert_eq!(body["messages"][1]["message_id"], "m2"); |
| 447 | |
| 448 | let (_, older) = call( |
| 449 | &client, |
| 450 | "read_messages", |
| 451 | json!({"conversation_id": ALLOWED_CHAT, "before_message_id": "m2"}), |
| 452 | ) |
| 453 | .await; |
| 454 | let older: Value = serde_json::from_str(&older).unwrap(); |
| 455 | assert_eq!(older["messages"].as_array().unwrap().len(), 1); |
| 456 | assert_eq!(older["messages"][0]["message_id"], "m1"); |
| 457 | } |
| 458 | |
| 459 | #[tokio::test] |
| 460 | async fn search_stays_inside_the_allowed_scope() { |
| 461 | let harness = Harness::start(true).await; |
| 462 | let client = harness.client().await; |
| 463 | let (is_error, body) = call(&client, "search_messages", json!({"query": "budget"})).await; |
| 464 | assert!(!is_error, "{body}"); |
| 465 | let body: Value = serde_json::from_str(&body).unwrap(); |
| 466 | let mut message_ids: Vec<&str> = body["hits"] |
| 467 | .as_array() |
| 468 | .unwrap() |
| 469 | .iter() |
| 470 | .map(|hit| hit["message_id"].as_str().unwrap()) |
| 471 | .collect(); |
| 472 | message_ids.sort(); |
| 473 | assert_eq!(message_ids, ["m1", "m4"]); |
| 474 | assert!(!body.to_string().contains('\u{1}')); |
| 475 | } |
| 476 | |
| 477 | #[tokio::test] |
| 478 | async fn proposal_resolution_reaches_wait_for_event() { |
| 479 | let harness = Harness::start(true).await; |
| 480 | let client = harness.client().await; |
| 481 | let (_, start) = call(&client, "wait_for_event", json!({"timeout_seconds": 1})).await; |
| 482 | let start: Value = serde_json::from_str(&start).unwrap(); |
| 483 | let cursor = start["next"].as_u64().unwrap(); |
| 484 | |
| 485 | let (is_error, body) = call( |
| 486 | &client, |
| 487 | "propose_message", |
| 488 | json!({"conversation_id": ALLOWED_CHAT, "text": "Sounds good", "agent": "test"}), |
| 489 | ) |
| 490 | .await; |
| 491 | assert!(!is_error, "{body}"); |
| 492 | let body: Value = serde_json::from_str(&body).unwrap(); |
| 493 | assert_eq!(body["state"], "pending"); |
| 494 | let proposal_id = body["proposal_id"].as_str().unwrap(); |
| 495 | assert!(harness.hub.resolve(proposal_id, Outcome::Sent)); |
| 496 | |
| 497 | let (_, events) = call( |
| 498 | &client, |
| 499 | "wait_for_event", |
| 500 | json!({"timeout_seconds": 5, "since": cursor}), |
| 501 | ) |
| 502 | .await; |
| 503 | let events: Value = serde_json::from_str(&events).unwrap(); |
| 504 | assert_eq!(events["events"][0]["type"], "proposal_resolved"); |
| 505 | assert_eq!(events["events"][0]["outcome"], "sent"); |
| 506 | assert_eq!(events["events"][0]["proposal_id"], proposal_id); |
| 507 | } |
| 508 | |
| 509 | #[tokio::test] |
| 510 | async fn propose_is_refused_when_turned_off_or_out_of_scope() { |
| 511 | let harness = Harness::start(false).await; |
| 512 | let client = harness.client().await; |
| 513 | let (is_error, text) = call( |
| 514 | &client, |
| 515 | "propose_message", |
| 516 | json!({"conversation_id": ALLOWED_CHAT, "text": "hi"}), |
| 517 | ) |
| 518 | .await; |
| 519 | assert!(is_error); |
| 520 | assert!(text.contains("turned off"), "{text}"); |
| 521 | |
| 522 | let (is_error, text) = call( |
| 523 | &client, |
| 524 | "propose_message", |
| 525 | json!({"conversation_id": HIDDEN_CHAT, "text": "hi"}), |
| 526 | ) |
| 527 | .await; |
| 528 | assert!(is_error); |
| 529 | assert!(text.contains("not found or not allowed"), "{text}"); |
| 530 | assert!(harness.hub.pending_proposal(ALLOWED_CHAT).is_none()); |
| 531 | } |
| 532 | |
| 533 | #[tokio::test] |
| 534 | async fn a_second_server_on_the_same_port_reports_it_clearly() { |
| 535 | let harness = Harness::start(true).await; |
| 536 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 537 | let (ui, _receiver) = tokio::sync::mpsc::unbounded_channel(); |
| 538 | let hub = AgentHub::new(store.clone(), AgentPolicy::default(), ui); |
| 539 | let result = mcp::start( |
| 540 | hub, |
| 541 | Arc::new(FakeSource { store }), |
| 542 | harness.server.addr.port(), |
| 543 | TOKEN.to_owned(), |
| 544 | ) |
| 545 | .await; |
| 546 | let error = result.err().expect("port is taken"); |
| 547 | assert!(error.to_string().contains("already in use"), "{error}"); |
| 548 | } |
| 549 | |
| 550 | #[tokio::test] |
| 551 | async fn meetings_and_transcripts_need_their_switches() { |
| 552 | let harness = Harness::start(true).await; |
| 553 | let client = harness.client().await; |
| 554 | let (is_error, text) = call(&client, "list_meetings", json!({})).await; |
| 555 | assert!(is_error); |
| 556 | assert!(text.contains("calendar access is turned off"), "{text}"); |
| 557 | let (is_error, text) = call( |
| 558 | &client, |
| 559 | "get_transcript", |
| 560 | json!({"meeting_chat_id": MEETING_CHAT}), |
| 561 | ) |
| 562 | .await; |
| 563 | assert!(is_error); |
| 564 | assert!(text.contains("transcripts are turned off"), "{text}"); |
| 565 | } |
| 566 | |
| 567 | #[tokio::test] |
| 568 | async fn list_meetings_returns_the_window() { |
| 569 | let harness = Harness::start_with(true, true, false).await; |
| 570 | let client = harness.client().await; |
| 571 | let (is_error, body) = call( |
| 572 | &client, |
| 573 | "list_meetings", |
| 574 | json!({"start": "2026-10-07T00:00:00Z", "end": "2026-10-08T00:00:00Z"}), |
| 575 | ) |
| 576 | .await; |
| 577 | assert!(!is_error, "{body}"); |
| 578 | let body: Value = serde_json::from_str(&body).unwrap(); |
| 579 | assert_eq!(body["meetings"][0]["title"], "Sprint review"); |
| 580 | assert_eq!(body["meetings"][0]["meeting_chat_id"], MEETING_CHAT); |
| 581 | |
| 582 | let (_, empty) = call( |
| 583 | &client, |
| 584 | "list_meetings", |
| 585 | json!({"start": "2026-10-09T00:00:00Z", "end": "2026-10-10T00:00:00Z"}), |
| 586 | ) |
| 587 | .await; |
| 588 | let empty: Value = serde_json::from_str(&empty).unwrap(); |
| 589 | assert!(empty["meetings"].as_array().unwrap().is_empty()); |
| 590 | |
| 591 | let (is_error, text) = call( |
| 592 | &client, |
| 593 | "list_meetings", |
| 594 | json!({"start": "2026-10-09T00:00:00Z", "end": "2026-10-08T00:00:00Z"}), |
| 595 | ) |
| 596 | .await; |
| 597 | assert!(is_error); |
| 598 | assert!(text.contains("end must be after start"), "{text}"); |
| 599 | } |
| 600 | |
| 601 | #[tokio::test] |
| 602 | async fn get_transcript_returns_turns_and_live_captions() { |
| 603 | let harness = Harness::start_with(true, false, true).await; |
| 604 | let client = harness.client().await; |
| 605 | let (is_error, body) = call( |
| 606 | &client, |
| 607 | "get_transcript", |
| 608 | json!({"meeting_chat_id": MEETING_CHAT}), |
| 609 | ) |
| 610 | .await; |
| 611 | assert!(!is_error, "{body}"); |
| 612 | let body: Value = serde_json::from_str(&body).unwrap(); |
| 613 | assert_eq!(body["turns"][0]["text"], "Welcome everyone"); |
| 614 | assert!(body["live_captions"].as_array().unwrap().is_empty()); |
| 615 | |
| 616 | let (is_error, text) = call( |
| 617 | &client, |
| 618 | "get_transcript", |
| 619 | json!({"meeting_chat_id": HIDDEN_MEETING_CHAT}), |
| 620 | ) |
| 621 | .await; |
| 622 | assert!(is_error); |
| 623 | assert!(text.contains("not found or not allowed"), "{text}"); |
| 624 | |
| 625 | let live_chat = LIVE_MEETING_CHAT; |
| 626 | let (is_error, text) = call( |
| 627 | &client, |
| 628 | "get_transcript", |
| 629 | json!({"meeting_chat_id": live_chat}), |
| 630 | ) |
| 631 | .await; |
| 632 | assert!(is_error); |
| 633 | assert!(text.contains("no finished recording"), "{text}"); |
| 634 | |
| 635 | harness.hub.push_caption(live_chat, "1", "Bo", "Hi all"); |
| 636 | let (is_error, body) = call( |
| 637 | &client, |
| 638 | "get_transcript", |
| 639 | json!({"meeting_chat_id": live_chat}), |
| 640 | ) |
| 641 | .await; |
| 642 | assert!(!is_error, "{body}"); |
| 643 | let body: Value = serde_json::from_str(&body).unwrap(); |
| 644 | assert!(body["turns"].as_array().unwrap().is_empty()); |
| 645 | assert_eq!(body["live_captions"][0]["speaker"], "Bo"); |
| 646 | assert_eq!(body["live_captions"][0]["text"], "Hi all"); |
| 647 | } |
| 648 | |
| 649 | #[tokio::test] |
| 650 | async fn propose_rejects_a_reply_target_from_another_conversation() { |
| 651 | let harness = Harness::start(true).await; |
| 652 | let client = harness.client().await; |
| 653 | let (is_error, text) = call( |
| 654 | &client, |
| 655 | "propose_message", |
| 656 | json!({"conversation_id": ALLOWED_CHAT, "text": "ok", "reply_to_message_id": "m3"}), |
| 657 | ) |
| 658 | .await; |
| 659 | assert!(is_error); |
| 660 | assert!( |
| 661 | text.contains("is not a message of this conversation"), |
| 662 | "{text}" |
| 663 | ); |
| 664 | let (is_error, body) = call( |
| 665 | &client, |
| 666 | "propose_message", |
| 667 | json!({"conversation_id": ALLOWED_CHAT, "text": "ok", "reply_to_message_id": "m1"}), |
| 668 | ) |
| 669 | .await; |
| 670 | assert!(!is_error, "{body}"); |
| 671 | } |
| 672 | |
| 673 | #[tokio::test] |
| 674 | async fn read_messages_adds_rich_fields_only_where_present() { |
| 675 | let harness = Harness::start(true).await; |
| 676 | let client = harness.client().await; |
| 677 | let (_, body) = call( |
| 678 | &client, |
| 679 | "read_messages", |
| 680 | json!({"conversation_id": ALLOWED_CHAT}), |
| 681 | ) |
| 682 | .await; |
| 683 | let body = json_of(&body); |
| 684 | let messages = body["messages"].as_array().unwrap(); |
| 685 | let plain = &messages[0]; |
| 686 | for field in [ |
| 687 | "images", |
| 688 | "reactions", |
| 689 | "mentions", |
| 690 | "files", |
| 691 | "quote", |
| 692 | "cards", |
| 693 | "links", |
| 694 | "thread_root_id", |
| 695 | ] { |
| 696 | assert!(plain.get(field).is_none(), "{field}"); |
| 697 | } |
| 698 | let rich = messages |
| 699 | .iter() |
| 700 | .find(|message| message["message_id"] == RICH_MESSAGE) |
| 701 | .unwrap(); |
| 702 | assert_eq!(rich["text"], "see the cat"); |
| 703 | assert_eq!( |
| 704 | rich["images"], |
| 705 | json!([{"image_id": RICH_IMAGE, "kind": "gif", "alt": "dancing cat"}]) |
| 706 | ); |
| 707 | assert_eq!( |
| 708 | rich["reactions"], |
| 709 | json!([{"emoji": "\u{1F44D}", "count": 2, "mine": true}]) |
| 710 | ); |
| 711 | assert_eq!( |
| 712 | rich["mentions"], |
| 713 | json!([{"name": "Bob Sample", "user_id": "user-bob"}]) |
| 714 | ); |
| 715 | assert_eq!(rich["files"][0]["name"], "Plan.docx"); |
| 716 | assert_eq!(rich["files"][0]["type"], "word"); |
| 717 | assert_eq!(rich["quote"]["message_id"], "m1"); |
| 718 | assert_eq!(rich["cards"], json!(["Build passed"])); |
| 719 | assert_eq!(rich["links"][0]["title"], "A story"); |
| 720 | } |
| 721 | |
| 722 | #[tokio::test] |
| 723 | async fn read_messages_filters_one_channel_thread() { |
| 724 | let harness = Harness::start(true).await; |
| 725 | let client = harness.client().await; |
| 726 | let (_, body) = call( |
| 727 | &client, |
| 728 | "read_messages", |
| 729 | json!({"conversation_id": CHANNEL, "thread_root_id": "t1"}), |
| 730 | ) |
| 731 | .await; |
| 732 | let body = json_of(&body); |
| 733 | assert_eq!(message_ids(&body), ["t1", "t2"]); |
| 734 | assert_eq!(body["messages"][1]["thread_root_id"], "t1"); |
| 735 | assert_eq!(body["messages"][0]["thread_root_id"], "t1"); |
| 736 | |
| 737 | let (_, body) = call( |
| 738 | &client, |
| 739 | "read_messages", |
| 740 | json!({"conversation_id": CHANNEL, "thread_root_id": "t1", "limit": 1}), |
| 741 | ) |
| 742 | .await; |
| 743 | assert_eq!(message_ids(&json_of(&body)), ["t2"]); |
| 744 | |
| 745 | let (is_error, text) = call( |
| 746 | &client, |
| 747 | "read_messages", |
| 748 | json!({"conversation_id": CHANNEL, "thread_root_id": "t2"}), |
| 749 | ) |
| 750 | .await; |
| 751 | assert!(is_error); |
| 752 | assert!(text.contains("is a reply"), "{text}"); |
| 753 | |
| 754 | let (is_error, text) = call( |
| 755 | &client, |
| 756 | "read_messages", |
| 757 | json!({"conversation_id": ALLOWED_CHAT, "thread_root_id": "m1"}), |
| 758 | ) |
| 759 | .await; |
| 760 | assert!(is_error); |
| 761 | assert!(text.contains("only works in channels"), "{text}"); |
| 762 | |
| 763 | let (is_error, text) = call( |
| 764 | &client, |
| 765 | "read_messages", |
| 766 | json!({"conversation_id": CHANNEL, "thread_root_id": "nope"}), |
| 767 | ) |
| 768 | .await; |
| 769 | assert!(is_error); |
| 770 | assert!(text.contains("unknown thread_root_id"), "{text}"); |
| 771 | } |
| 772 | |
| 773 | #[tokio::test] |
| 774 | async fn get_image_returns_an_image_block_and_a_description() { |
| 775 | let harness = Harness::start(true).await; |
| 776 | let client = harness.client().await; |
| 777 | let result = call_raw( |
| 778 | &client, |
| 779 | "get_image", |
| 780 | json!({"conversation_id": ALLOWED_CHAT, "message_id": RICH_MESSAGE, "image_id": RICH_IMAGE}), |
| 781 | ) |
| 782 | .await; |
| 783 | assert_ne!(result.is_error, Some(true)); |
| 784 | let image = result.content[0].as_image().unwrap(); |
| 785 | assert_eq!(image.mime_type, "image/png"); |
| 786 | assert_eq!(STANDARD.decode(&image.data).unwrap(), PIXEL_PNG); |
| 787 | let description = json_of(&result.content[1].as_text().unwrap().text); |
| 788 | assert_eq!(description["kind"], "gif"); |
| 789 | assert_eq!(description["alt"], "dancing cat"); |
| 790 | assert_eq!(description["width"], 1); |
| 791 | } |
| 792 | |
| 793 | #[tokio::test] |
| 794 | async fn get_image_refuses_foreign_hidden_and_unknown_targets() { |
| 795 | let harness = Harness::start(true).await; |
| 796 | let client = harness.client().await; |
| 797 | let refused = |conversation_id: &str, message_id: &str, image_id: &str| json!({"conversation_id": conversation_id, "message_id": message_id, "image_id": image_id}); |
| 798 | let (is_error, text) = call(&client, "get_image", refused(HIDDEN_CHAT, "m3", RICH_IMAGE)).await; |
| 799 | assert!(is_error); |
| 800 | assert!(text.contains("not allowed"), "{text}"); |
| 801 | |
| 802 | let (is_error, text) = call( |
| 803 | &client, |
| 804 | "get_image", |
| 805 | refused(ALLOWED_CHAT, "m3", RICH_IMAGE), |
| 806 | ) |
| 807 | .await; |
| 808 | assert!(is_error); |
| 809 | assert!(text.contains("unknown message_id"), "{text}"); |
| 810 | |
| 811 | let (is_error, text) = call( |
| 812 | &client, |
| 813 | "get_image", |
| 814 | refused(ALLOWED_CHAT, RICH_MESSAGE, "9-deadbeef"), |
| 815 | ) |
| 816 | .await; |
| 817 | assert!(is_error); |
| 818 | assert!(text.contains("unknown image_id"), "{text}"); |
| 819 | |
| 820 | let (is_error, text) = call( |
| 821 | &client, |
| 822 | "get_image", |
| 823 | refused(ALLOWED_CHAT, "m1", RICH_IMAGE), |
| 824 | ) |
| 825 | .await; |
| 826 | assert!(is_error); |
| 827 | assert!(text.contains("unknown image_id"), "{text}"); |
| 828 | } |
| 829 | |
| 830 | fn since_start_of_seed() -> Value { |
| 831 | json!("2026-10-06T00:00:00Z") |
| 832 | } |
| 833 | |
| 834 | #[tokio::test] |
| 835 | async fn recent_messages_run_newest_first_inside_the_allowed_scope() { |
| 836 | let harness = Harness::start(true).await; |
| 837 | let client = harness.client().await; |
| 838 | let (is_error, body) = call( |
| 839 | &client, |
| 840 | "recent_messages", |
| 841 | json!({"since": since_start_of_seed()}), |
| 842 | ) |
| 843 | .await; |
| 844 | assert!(!is_error, "{body}"); |
| 845 | let body = json_of(&body); |
| 846 | assert_eq!( |
| 847 | message_ids(&body), |
| 848 | ["t2", "t1", RICH_MESSAGE, "m4", "m2", "m1"] |
| 849 | ); |
| 850 | assert_eq!(body["messages"][0]["conversation"], "Platform / General"); |
| 851 | assert_eq!(body["messages"][0]["conversation_id"], CHANNEL); |
| 852 | assert_eq!(body["messages"][0]["thread_root_id"], "t1"); |
| 853 | assert_eq!(body["messages"][2]["conversation"], "Planning"); |
| 854 | assert_eq!(body["messages"][2]["images"][0]["image_id"], RICH_IMAGE); |
| 855 | assert!(body["next_cursor"].is_null()); |
| 856 | assert!(!body.to_string().contains("m3")); |
| 857 | |
| 858 | let (_, body) = call( |
| 859 | &client, |
| 860 | "recent_messages", |
| 861 | json!({"since": "2026-10-06T09:05:00Z"}), |
| 862 | ) |
| 863 | .await; |
| 864 | assert_eq!(message_ids(&json_of(&body)), ["t2", "t1", RICH_MESSAGE]); |
| 865 | |
| 866 | let (_, body) = call( |
| 867 | &client, |
| 868 | "recent_messages", |
| 869 | json!({"since": since_start_of_seed(), "kinds": ["channel"]}), |
| 870 | ) |
| 871 | .await; |
| 872 | assert_eq!(message_ids(&json_of(&body)), ["t2", "t1", "m4"]); |
| 873 | |
| 874 | let (_, body) = call( |
| 875 | &client, |
| 876 | "recent_messages", |
| 877 | json!({"since": since_start_of_seed(), "kinds": ["chat", "meeting"]}), |
| 878 | ) |
| 879 | .await; |
| 880 | assert_eq!(message_ids(&json_of(&body)), [RICH_MESSAGE, "m2", "m1"]); |
| 881 | } |
| 882 | |
| 883 | #[tokio::test] |
| 884 | async fn recent_messages_page_with_a_cursor() { |
| 885 | let harness = Harness::start(true).await; |
| 886 | let client = harness.client().await; |
| 887 | let mut collected: Vec<String> = Vec::new(); |
| 888 | let mut cursor = Value::Null; |
| 889 | for _ in 0..4 { |
| 890 | let mut arguments = json!({"since": since_start_of_seed(), "limit": 4}); |
| 891 | if !cursor.is_null() { |
| 892 | arguments["cursor"] = cursor.clone(); |
| 893 | } |
| 894 | let (is_error, body) = call(&client, "recent_messages", arguments).await; |
| 895 | assert!(!is_error, "{body}"); |
| 896 | let body = json_of(&body); |
| 897 | collected.extend(message_ids(&body).into_iter().map(str::to_owned)); |
| 898 | cursor = body["next_cursor"].clone(); |
| 899 | if cursor.is_null() { |
| 900 | break; |
| 901 | } |
| 902 | } |
| 903 | assert_eq!(collected, ["t2", "t1", RICH_MESSAGE, "m4", "m2", "m1"]); |
| 904 | |
| 905 | let (_, first_page) = call( |
| 906 | &client, |
| 907 | "recent_messages", |
| 908 | json!({"since": since_start_of_seed(), "limit": 2}), |
| 909 | ) |
| 910 | .await; |
| 911 | let cursor = json_of(&first_page)["next_cursor"].clone(); |
| 912 | let (_, later_page) = call( |
| 913 | &client, |
| 914 | "recent_messages", |
| 915 | json!({"since": "2030-01-01T00:00:00Z", "cursor": cursor}), |
| 916 | ) |
| 917 | .await; |
| 918 | assert_eq!( |
| 919 | message_ids(&json_of(&later_page)), |
| 920 | [RICH_MESSAGE, "m4", "m2", "m1"] |
| 921 | ); |
| 922 | |
| 923 | let (is_error, text) = call(&client, "recent_messages", json!({"cursor": "garbage"})).await; |
| 924 | assert!(is_error); |
| 925 | assert!(text.contains("invalid cursor"), "{text}"); |
| 926 | } |
| 927 | |
| 928 | #[tokio::test] |
| 929 | async fn recent_messages_unread_only_covers_chats_and_channels() { |
| 930 | let harness = Harness::start(true).await; |
| 931 | let client = harness.client().await; |
| 932 | let arguments = || json!({"since": since_start_of_seed(), "unread_only": true}); |
| 933 | let (_, body) = call(&client, "recent_messages", arguments()).await; |
| 934 | assert!(message_ids(&json_of(&body)).is_empty()); |
| 935 | |
| 936 | let read_until = Utc.with_ymd_and_hms(2026, 10, 6, 9, 2, 0).unwrap(); |
| 937 | harness |
| 938 | .store |
| 939 | .mark_chat_unread(ALLOWED_CHAT, read_until) |
| 940 | .unwrap(); |
| 941 | let (_, body) = call(&client, "recent_messages", arguments()).await; |
| 942 | assert_eq!(message_ids(&json_of(&body)), [RICH_MESSAGE]); |
| 943 | |
| 944 | harness |
| 945 | .store |
| 946 | .upsert_channels(&[ChannelRecord { |
| 947 | id: CHANNEL.to_owned(), |
| 948 | team_id: "team-1".to_owned(), |
| 949 | name: "General".to_owned(), |
| 950 | membership_type: None, |
| 951 | last_message_at: Some(Utc.with_ymd_and_hms(2026, 10, 6, 9, 6, 0).unwrap()), |
| 952 | unread: true, |
| 953 | }]) |
| 954 | .unwrap(); |
| 955 | let (_, body) = call(&client, "recent_messages", arguments()).await; |
| 956 | assert_eq!( |
| 957 | message_ids(&json_of(&body)), |
| 958 | ["t2", "t1", RICH_MESSAGE, "m4"] |
| 959 | ); |
| 960 | } |