| 1 | use std::collections::HashMap; |
| 2 | use std::sync::Arc; |
| 3 | use std::time::Duration; |
| 4 | |
| 5 | use chrono::{DateTime, Utc}; |
| 6 | use rmcp::handler::server::router::tool::ToolRouter; |
| 7 | use rmcp::handler::server::wrapper::Parameters; |
| 8 | use rmcp::model::{ProgressNotificationParam, RequestMetaObject}; |
| 9 | use rmcp::service::Peer; |
| 10 | use rmcp::{RoleServer, ServerHandler, schemars, tool, tool_handler, tool_router}; |
| 11 | use serde::{Deserialize, Serialize}; |
| 12 | use serde_json::json; |
| 13 | use store::{HIGHLIGHT_END, HIGHLIGHT_START, MessageRecord, Store, plain_text}; |
| 14 | |
| 15 | use crate::hub::AgentHub; |
| 16 | use crate::policy::{AgentPolicy, ConversationKind}; |
| 17 | use crate::source::TeamsSource; |
| 18 | |
| 19 | const NOT_ALLOWED: &str = |
| 20 | "conversation not found or not allowed (allow it in rusty-teams Settings > MCP)"; |
| 21 | const PROPOSE_DISABLED: &str = |
| 22 | "proposing messages is turned off (enable it in rusty-teams Settings > MCP)"; |
| 23 | const DEFAULT_LIST_LIMIT: usize = 50; |
| 24 | const MAX_LIST_LIMIT: usize = 200; |
| 25 | const DEFAULT_READ_LIMIT: usize = 30; |
| 26 | const MAX_READ_LIMIT: usize = 200; |
| 27 | const DEFAULT_SEARCH_LIMIT: usize = 20; |
| 28 | const MAX_SEARCH_LIMIT: usize = 100; |
| 29 | const DEFAULT_WAIT_SECONDS: u64 = 25; |
| 30 | const MAX_WAIT_SECONDS: u64 = 50; |
| 31 | const PROGRESS_INTERVAL: Duration = Duration::from_secs(10); |
| 32 | const MAX_PROPOSAL_CHARACTERS: usize = 20_000; |
| 33 | const DEFAULT_MEETING_DAYS: i64 = 7; |
| 34 | const MAX_MEETING_DAYS: i64 = 62; |
| 35 | const CALENDAR_DISABLED: &str = |
| 36 | "calendar access is turned off (enable it in rusty-teams Settings > MCP)"; |
| 37 | const TRANSCRIPTS_DISABLED: &str = |
| 38 | "meeting transcripts are turned off (enable them in rusty-teams Settings > MCP)"; |
| 39 | |
| 40 | #[derive(Clone)] |
| 41 | pub struct TeamsTools { |
| 42 | hub: Arc<AgentHub>, |
| 43 | source: Arc<dyn TeamsSource>, |
| 44 | tool_router: ToolRouter<Self>, |
| 45 | } |
| 46 | |
| 47 | #[derive(Debug, Deserialize, schemars::JsonSchema)] |
| 48 | pub struct ListChatsParams { |
| 49 | /// Maximum number of chats to return, newest first. Default 50, max 200. |
| 50 | pub limit: Option<usize>, |
| 51 | } |
| 52 | |
| 53 | #[derive(Debug, Deserialize, schemars::JsonSchema)] |
| 54 | pub struct ReadMessagesParams { |
| 55 | /// Raw conversation id as returned by list_chats or list_channels, for example "19:...@thread.v2". |
| 56 | pub conversation_id: String, |
| 57 | /// Number of messages to return. Default 30, max 200. |
| 58 | pub limit: Option<usize>, |
| 59 | /// Return only messages older than this message id, to page backwards. |
| 60 | pub before_message_id: Option<String>, |
| 61 | } |
| 62 | |
| 63 | #[derive(Debug, Deserialize, schemars::JsonSchema)] |
| 64 | pub struct SearchMessagesParams { |
| 65 | /// Words to search for. Every word is a prefix match. Use "from:name" to filter by sender. |
| 66 | pub query: String, |
| 67 | /// Maximum number of hits, newest first. Default 20, max 100. |
| 68 | pub limit: Option<usize>, |
| 69 | } |
| 70 | |
| 71 | #[derive(Debug, Deserialize, schemars::JsonSchema)] |
| 72 | pub struct ProposeMessageParams { |
| 73 | /// Raw conversation id as returned by list_chats or list_channels. |
| 74 | pub conversation_id: String, |
| 75 | /// Message text. Markdown is allowed. |
| 76 | pub text: String, |
| 77 | /// Id of the message this one answers (threads in channels). |
| 78 | pub reply_to_message_id: Option<String>, |
| 79 | /// Your session id, so the user can tell proposals of different sessions apart. |
| 80 | pub session_id: Option<String>, |
| 81 | /// Your name, shown to the user next to the proposal. |
| 82 | pub agent: Option<String>, |
| 83 | } |
| 84 | |
| 85 | #[derive(Debug, Deserialize, schemars::JsonSchema)] |
| 86 | pub struct WaitForEventParams { |
| 87 | /// Seconds to wait for an event. Default 25, max 50. |
| 88 | pub timeout_seconds: Option<u64>, |
| 89 | /// Cursor from the previous call's "next". Omit it to only see events from now on. |
| 90 | pub since: Option<u64>, |
| 91 | } |
| 92 | |
| 93 | #[derive(Debug, Deserialize, schemars::JsonSchema)] |
| 94 | pub struct ListMeetingsParams { |
| 95 | /// Start of the window, ISO 8601 with offset. Default: the start of today (UTC). |
| 96 | pub start: Option<DateTime<Utc>>, |
| 97 | /// End of the window, ISO 8601 with offset. Default: 7 days after start, max 62 days. |
| 98 | pub end: Option<DateTime<Utc>>, |
| 99 | } |
| 100 | |
| 101 | #[derive(Debug, Deserialize, schemars::JsonSchema)] |
| 102 | pub struct GetTranscriptParams { |
| 103 | /// Meeting chat id as returned by list_meetings (meeting_chat_id). |
| 104 | pub meeting_chat_id: String, |
| 105 | } |
| 106 | |
| 107 | #[derive(Serialize)] |
| 108 | struct MessageView { |
| 109 | message_id: String, |
| 110 | sender: Option<String>, |
| 111 | sender_id: Option<String>, |
| 112 | time: String, |
| 113 | edited_at: Option<String>, |
| 114 | text: String, |
| 115 | subject: Option<String>, |
| 116 | reply_to: Option<String>, |
| 117 | } |
| 118 | |
| 119 | fn timestamp(time: DateTime<Utc>) -> String { |
| 120 | time.to_rfc3339() |
| 121 | } |
| 122 | |
| 123 | fn message_view(message: MessageRecord) -> MessageView { |
| 124 | MessageView { |
| 125 | text: plain_text(&message.body_html), |
| 126 | message_id: message.message_id, |
| 127 | sender: message.sender_name, |
| 128 | sender_id: message.sender_id, |
| 129 | time: timestamp(message.created_at), |
| 130 | edited_at: message.edited_at.map(timestamp), |
| 131 | subject: message.subject, |
| 132 | reply_to: message.reply_to_id, |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | fn render(value: serde_json::Value) -> String { |
| 137 | value.to_string() |
| 138 | } |
| 139 | |
| 140 | fn failure(error: impl std::fmt::Display) -> String { |
| 141 | error.to_string() |
| 142 | } |
| 143 | |
| 144 | #[tool_router] |
| 145 | impl TeamsTools { |
| 146 | pub fn new(hub: Arc<AgentHub>, source: Arc<dyn TeamsSource>) -> Self { |
| 147 | TeamsTools { |
| 148 | hub, |
| 149 | source, |
| 150 | tool_router: Self::tool_router(), |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | #[tool( |
| 155 | description = "List the Teams chats (1:1, group and meeting chats) the user allowed for agents, newest activity first. Returns id, title, kind, last_message_at, unread. Use the id with read_messages and propose_message." |
| 156 | )] |
| 157 | async fn list_chats( |
| 158 | &self, |
| 159 | Parameters(params): Parameters<ListChatsParams>, |
| 160 | ) -> Result<String, String> { |
| 161 | let policy = self.hub.policy(); |
| 162 | let store = self.store()?; |
| 163 | let limit = params |
| 164 | .limit |
| 165 | .unwrap_or(DEFAULT_LIST_LIMIT) |
| 166 | .clamp(1, MAX_LIST_LIMIT); |
| 167 | let chats: Vec<_> = allowed_chats(&store, &policy)? |
| 168 | .into_iter() |
| 169 | .take(limit) |
| 170 | .map(|chat| { |
| 171 | json!({ |
| 172 | "id": chat.id, |
| 173 | "title": chat.display_title(), |
| 174 | "kind": chat.kind, |
| 175 | "last_message_at": chat.last_message_at.map(timestamp), |
| 176 | "unread": chat.unread, |
| 177 | }) |
| 178 | }) |
| 179 | .collect(); |
| 180 | Ok(render(json!({ "chats": chats }))) |
| 181 | } |
| 182 | |
| 183 | #[tool( |
| 184 | description = "List the Teams channels the user allowed for agents. Returns id, team, channel name, last_message_at, unread. Use the id with read_messages and propose_message." |
| 185 | )] |
| 186 | async fn list_channels(&self) -> Result<String, String> { |
| 187 | let policy = self.hub.policy(); |
| 188 | let store = self.store()?; |
| 189 | let mut channels = Vec::new(); |
| 190 | for team in store.sidebar().map_err(failure)?.teams { |
| 191 | for channel in team.channels { |
| 192 | if policy.can_read(ConversationKind::Channel, &channel.id) { |
| 193 | channels.push(json!({ |
| 194 | "id": channel.id, |
| 195 | "team": team.team.name, |
| 196 | "channel": channel.name, |
| 197 | "last_message_at": channel.last_message_at.map(timestamp), |
| 198 | "unread": channel.unread, |
| 199 | })); |
| 200 | } |
| 201 | } |
| 202 | } |
| 203 | Ok(render(json!({ "channels": channels }))) |
| 204 | } |
| 205 | |
| 206 | #[tool( |
| 207 | description = "Read messages of one allowed chat or channel, oldest first. Returns message_id, sender, sender_id, time (RFC 3339), text (plain text), subject, reply_to. Defaults to the 30 newest messages. Pass before_message_id to page backwards." |
| 208 | )] |
| 209 | async fn read_messages( |
| 210 | &self, |
| 211 | Parameters(params): Parameters<ReadMessagesParams>, |
| 212 | ) -> Result<String, String> { |
| 213 | let store = self.store()?; |
| 214 | self.readable_kind(&store, ¶ms.conversation_id)?; |
| 215 | let limit = params |
| 216 | .limit |
| 217 | .unwrap_or(DEFAULT_READ_LIMIT) |
| 218 | .clamp(1, MAX_READ_LIMIT); |
| 219 | let before = match params.before_message_id { |
| 220 | Some(message_id) => { |
| 221 | let mut found = store |
| 222 | .messages_by_id(¶ms.conversation_id, std::slice::from_ref(&message_id)) |
| 223 | .map_err(failure)?; |
| 224 | let message = found |
| 225 | .remove(&message_id) |
| 226 | .ok_or_else(|| format!("unknown before_message_id {message_id}"))?; |
| 227 | Some(message.created_at) |
| 228 | } |
| 229 | None => None, |
| 230 | }; |
| 231 | let messages: Vec<_> = store |
| 232 | .messages(¶ms.conversation_id, before, limit) |
| 233 | .map_err(failure)? |
| 234 | .into_iter() |
| 235 | .filter(|message| !message.deleted) |
| 236 | .map(message_view) |
| 237 | .collect(); |
| 238 | Ok(render(json!({ |
| 239 | "conversation_id": params.conversation_id, |
| 240 | "messages": messages, |
| 241 | }))) |
| 242 | } |
| 243 | |
| 244 | #[tool( |
| 245 | description = "Full-text search over the messages of all allowed chats and channels, newest first. Every word is a prefix match, \"from:name\" filters by sender. Returns conversation_id, conversation title, message_id, sender, time and a snippet." |
| 246 | )] |
| 247 | async fn search_messages( |
| 248 | &self, |
| 249 | Parameters(params): Parameters<SearchMessagesParams>, |
| 250 | ) -> Result<String, String> { |
| 251 | let policy = self.hub.policy(); |
| 252 | let store = self.store()?; |
| 253 | let mut titles: HashMap<String, String> = allowed_chats(&store, &policy)? |
| 254 | .into_iter() |
| 255 | .map(|chat| { |
| 256 | let title = chat.display_title(); |
| 257 | (chat.id, title) |
| 258 | }) |
| 259 | .collect(); |
| 260 | for team in store.sidebar().map_err(failure)?.teams { |
| 261 | for channel in team.channels { |
| 262 | if policy.can_read(ConversationKind::Channel, &channel.id) { |
| 263 | titles.insert(channel.id, format!("{} / {}", team.team.name, channel.name)); |
| 264 | } |
| 265 | } |
| 266 | } |
| 267 | let conversation_ids: Vec<String> = titles.keys().cloned().collect(); |
| 268 | let limit = params |
| 269 | .limit |
| 270 | .unwrap_or(DEFAULT_SEARCH_LIMIT) |
| 271 | .clamp(1, MAX_SEARCH_LIMIT); |
| 272 | let hits: Vec<_> = store |
| 273 | .search_messages_in(¶ms.query, &conversation_ids, limit) |
| 274 | .map_err(failure)? |
| 275 | .into_iter() |
| 276 | .map(|hit| { |
| 277 | json!({ |
| 278 | "conversation_id": hit.conversation_id, |
| 279 | "conversation": titles.get(&hit.conversation_id), |
| 280 | "message_id": hit.message_id, |
| 281 | "sender": hit.sender_name, |
| 282 | "time": timestamp(hit.created_at), |
| 283 | "snippet": hit.snippet.replace([HIGHLIGHT_START, HIGHLIGHT_END], ""), |
| 284 | }) |
| 285 | }) |
| 286 | .collect(); |
| 287 | Ok(render(json!({ "hits": hits }))) |
| 288 | } |
| 289 | |
| 290 | #[tool( |
| 291 | description = "Propose a message for the user to review in rusty-teams. The message is NEVER sent automatically: the user sees it as a draft, can edit it, and sends or discards it. Only one proposal per conversation is pending, a new one replaces the old one. Returns proposal_id and state \"pending\". Use wait_for_event to learn what the user did with it." |
| 292 | )] |
| 293 | async fn propose_message( |
| 294 | &self, |
| 295 | Parameters(params): Parameters<ProposeMessageParams>, |
| 296 | ) -> Result<String, String> { |
| 297 | let store = self.store()?; |
| 298 | self.readable_kind(&store, ¶ms.conversation_id)?; |
| 299 | if !self.hub.policy().propose { |
| 300 | return Err(PROPOSE_DISABLED.to_owned()); |
| 301 | } |
| 302 | if let Some(message_id) = ¶ms.reply_to_message_id { |
| 303 | let found = store |
| 304 | .messages_by_id(¶ms.conversation_id, std::slice::from_ref(message_id)) |
| 305 | .map_err(failure)?; |
| 306 | if !found.contains_key(message_id) { |
| 307 | return Err(format!( |
| 308 | "reply_to_message_id {message_id} is not a message of this conversation" |
| 309 | )); |
| 310 | } |
| 311 | } |
| 312 | let text = params.text.trim(); |
| 313 | if text.is_empty() || text.chars().count() > MAX_PROPOSAL_CHARACTERS { |
| 314 | return Err(format!( |
| 315 | "text must be 1 to {MAX_PROPOSAL_CHARACTERS} characters long" |
| 316 | )); |
| 317 | } |
| 318 | let proposal = self |
| 319 | .hub |
| 320 | .add_proposal( |
| 321 | ¶ms.conversation_id, |
| 322 | text, |
| 323 | params.reply_to_message_id, |
| 324 | params.agent, |
| 325 | params.session_id, |
| 326 | ) |
| 327 | .map_err(failure)?; |
| 328 | Ok(render( |
| 329 | json!({ "proposal_id": proposal.id, "state": "pending" }), |
| 330 | )) |
| 331 | } |
| 332 | |
| 333 | #[tool( |
| 334 | description = "Wait up to timeout_seconds (default 25, max 50) for events in allowed conversations: new_message, user_typing, user_sent, proposal_resolved (outcome sent = the user sent it unchanged and it is queued for delivery, edited, discarded, stale or superseded). Returns {events, next}. Call again with since set to next to continue without missing events. Without since, only events from now on are returned." |
| 335 | )] |
| 336 | async fn wait_for_event( |
| 337 | &self, |
| 338 | Parameters(params): Parameters<WaitForEventParams>, |
| 339 | meta: RequestMetaObject, |
| 340 | client: Peer<RoleServer>, |
| 341 | ) -> Result<String, String> { |
| 342 | let timeout = Duration::from_secs( |
| 343 | params |
| 344 | .timeout_seconds |
| 345 | .unwrap_or(DEFAULT_WAIT_SECONDS) |
| 346 | .clamp(1, MAX_WAIT_SECONDS), |
| 347 | ); |
| 348 | let progress_token = meta.get_progress_token(); |
| 349 | let deadline = tokio::time::Instant::now() + timeout; |
| 350 | let mut cursor = params.since; |
| 351 | let mut elapsed_intervals = 0.0; |
| 352 | loop { |
| 353 | let remaining = deadline.saturating_duration_since(tokio::time::Instant::now()); |
| 354 | let (events, next) = self |
| 355 | .hub |
| 356 | .wait_events(cursor, remaining.min(PROGRESS_INTERVAL)) |
| 357 | .await; |
| 358 | if !events.is_empty() || remaining <= PROGRESS_INTERVAL { |
| 359 | return Ok(render(json!({ "events": events, "next": next }))); |
| 360 | } |
| 361 | cursor = Some(next); |
| 362 | elapsed_intervals += 1.0; |
| 363 | if let Some(token) = progress_token.clone() { |
| 364 | let _ = client |
| 365 | .notify_progress( |
| 366 | ProgressNotificationParam::new(token, elapsed_intervals) |
| 367 | .with_message("waiting for events"), |
| 368 | ) |
| 369 | .await; |
| 370 | } |
| 371 | } |
| 372 | } |
| 373 | |
| 374 | #[tool( |
| 375 | description = "List the user's calendar meetings in a time window, oldest first. Returns title, start, end (RFC 3339), all_day, organizer, join_url and meeting_chat_id (use it with get_transcript). Defaults to today and the next 7 days." |
| 376 | )] |
| 377 | async fn list_meetings( |
| 378 | &self, |
| 379 | Parameters(params): Parameters<ListMeetingsParams>, |
| 380 | ) -> Result<String, String> { |
| 381 | let policy = self.hub.policy(); |
| 382 | if !policy.enabled || !policy.calendar { |
| 383 | return Err(CALENDAR_DISABLED.to_owned()); |
| 384 | } |
| 385 | let start = params.start.unwrap_or_else(start_of_today); |
| 386 | let end = params |
| 387 | .end |
| 388 | .unwrap_or(start + chrono::Duration::days(DEFAULT_MEETING_DAYS)) |
| 389 | .min(start + chrono::Duration::days(MAX_MEETING_DAYS)); |
| 390 | if end <= start { |
| 391 | return Err("end must be after start".to_owned()); |
| 392 | } |
| 393 | let meetings = self.source.calendar(start, end).await.map_err(failure)?; |
| 394 | Ok(render(json!({ "meetings": meetings }))) |
| 395 | } |
| 396 | |
| 397 | #[tool( |
| 398 | description = "Get the spoken text of a meeting by its meeting_chat_id: the finished transcript turns (speaker, start_seconds, end_seconds, text) once the recording is processed, and live_captions while the user is in the meeting right now." |
| 399 | )] |
| 400 | async fn get_transcript( |
| 401 | &self, |
| 402 | Parameters(params): Parameters<GetTranscriptParams>, |
| 403 | ) -> Result<String, String> { |
| 404 | let policy = self.hub.policy(); |
| 405 | if !policy.enabled || !policy.transcripts { |
| 406 | return Err(TRANSCRIPTS_DISABLED.to_owned()); |
| 407 | } |
| 408 | let store = self.store()?; |
| 409 | self.readable_kind(&store, ¶ms.meeting_chat_id)?; |
| 410 | let live_captions = self.hub.live_captions(¶ms.meeting_chat_id); |
| 411 | match self.source.transcript(¶ms.meeting_chat_id).await { |
| 412 | Ok(transcript) => Ok(render(json!({ |
| 413 | "meeting_chat_id": params.meeting_chat_id, |
| 414 | "recording_name": transcript.recording_name, |
| 415 | "created_at": transcript.created_at, |
| 416 | "turns": transcript.turns, |
| 417 | "live_captions": live_captions, |
| 418 | }))), |
| 419 | Err(_) if !live_captions.is_empty() => Ok(render(json!({ |
| 420 | "meeting_chat_id": params.meeting_chat_id, |
| 421 | "turns": [], |
| 422 | "live_captions": live_captions, |
| 423 | }))), |
| 424 | Err(error) => Err(failure(error)), |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | fn store(&self) -> Result<Arc<Store>, String> { |
| 429 | self.source.store().map_err(failure) |
| 430 | } |
| 431 | |
| 432 | fn readable_kind( |
| 433 | &self, |
| 434 | store: &Store, |
| 435 | conversation_id: &str, |
| 436 | ) -> Result<ConversationKind, String> { |
| 437 | let policy = self.hub.policy(); |
| 438 | let kind = conversation_kind(store, conversation_id)?; |
| 439 | match kind { |
| 440 | Some(kind) if policy.can_read(kind, conversation_id) => Ok(kind), |
| 441 | _ => Err(NOT_ALLOWED.to_owned()), |
| 442 | } |
| 443 | } |
| 444 | } |
| 445 | |
| 446 | #[tool_handler( |
| 447 | router = self.tool_router, |
| 448 | name = "rusty-teams", |
| 449 | instructions = "Read-only access to the user's Teams chats and channels from their local rusty-teams app. \ |
| 450 | Only conversations the user allowed in rusty-teams Settings > MCP are visible; anything else looks like it does not exist. \ |
| 451 | Start with list_chats or list_channels, then read_messages or search_messages. \ |
| 452 | To write, call propose_message: the user reviews the draft in the app and sends it, nothing is sent automatically. \ |
| 453 | list_meetings and get_transcript only work when the user turned on calendar or transcripts access. \ |
| 454 | Use wait_for_event to follow new messages and to learn what happened to a proposal." |
| 455 | )] |
| 456 | impl ServerHandler for TeamsTools {} |
| 457 | |
| 458 | fn start_of_today() -> DateTime<Utc> { |
| 459 | Utc::now() |
| 460 | .date_naive() |
| 461 | .and_time(chrono::NaiveTime::MIN) |
| 462 | .and_utc() |
| 463 | } |
| 464 | |
| 465 | fn conversation_kind( |
| 466 | store: &Store, |
| 467 | conversation_id: &str, |
| 468 | ) -> Result<Option<ConversationKind>, String> { |
| 469 | if let Some(chat) = store.chat(conversation_id).map_err(failure)? { |
| 470 | return Ok(Some(chat_kind(&chat))); |
| 471 | } |
| 472 | Ok(store |
| 473 | .channel(conversation_id) |
| 474 | .map_err(failure)? |
| 475 | .map(|_| ConversationKind::Channel)) |
| 476 | } |
| 477 | |
| 478 | fn allowed_chats(store: &Store, policy: &AgentPolicy) -> Result<Vec<store::ChatRecord>, String> { |
| 479 | Ok(store |
| 480 | .recent_chats(usize::MAX >> 1) |
| 481 | .map_err(failure)? |
| 482 | .into_iter() |
| 483 | .filter(|chat| policy.can_read(chat_kind(chat), &chat.id)) |
| 484 | .collect()) |
| 485 | } |
| 486 | |
| 487 | fn chat_kind(chat: &store::ChatRecord) -> ConversationKind { |
| 488 | if chat.kind.eq_ignore_ascii_case("meeting") { |
| 489 | ConversationKind::Meeting |
| 490 | } else { |
| 491 | ConversationKind::Chat |
| 492 | } |
| 493 | } |