|
| 1 | +use crate::{play_types::StateOutput, McpServer}; |
| 2 | +use gfa_core::Viewer; |
| 3 | +use gfa_service::GameService; |
| 4 | +use rmcp::{ |
| 5 | + model::{ClientConfig, ResourceUpdatedNotificationParam, SubscriptionFilter}, |
| 6 | + service::{Peer, RequestContext, SubscriptionContext}, |
| 7 | + ErrorData, RoleServer, |
| 8 | +}; |
| 9 | +use std::{sync::Arc, time::Duration}; |
| 10 | +use tokio::{ |
| 11 | + sync::{Mutex, Semaphore}, |
| 12 | + task::JoinHandle, |
| 13 | +}; |
| 14 | + |
| 15 | +const MAX_URIS: usize = 8; |
| 16 | +const POLL: Duration = Duration::from_secs(2); |
| 17 | +const IO_TIMEOUT: Duration = Duration::from_secs(3); |
| 18 | +struct LegacyWatch { |
| 19 | + // The SDK returns clones of this connection's stable Arc. Pointer identity |
| 20 | + // distinguishes clients with identical names without trusting client IDs. |
| 21 | + identity: Arc<ClientConfig>, |
| 22 | + uri: String, |
| 23 | + task: JoinHandle<()>, |
| 24 | +} |
| 25 | +impl Drop for LegacyWatch { |
| 26 | + fn drop(&mut self) { |
| 27 | + self.task.abort(); |
| 28 | + } |
| 29 | +} |
| 30 | +pub(crate) struct Watches { |
| 31 | + capacity: Arc<Semaphore>, |
| 32 | + legacy: Mutex<Vec<LegacyWatch>>, |
| 33 | +} |
| 34 | +impl Default for Watches { |
| 35 | + fn default() -> Self { |
| 36 | + Self { |
| 37 | + capacity: Arc::new(Semaphore::new(16)), |
| 38 | + legacy: Mutex::new(Vec::new()), |
| 39 | + } |
| 40 | + } |
| 41 | +} |
| 42 | +fn state_id(uri: &str) -> Option<&str> { |
| 43 | + let id = uri.strip_prefix("gfa://matches/")?.strip_suffix("/state")?; |
| 44 | + (!id.is_empty() |
| 45 | + && id.len() <= 128 |
| 46 | + && id |
| 47 | + .bytes() |
| 48 | + .all(|byte| byte.is_ascii_alphanumeric() || b"_-".contains(&byte))) |
| 49 | + .then_some(id) |
| 50 | +} |
| 51 | +fn unavailable() -> ErrorData { |
| 52 | + ErrorData::internal_error("Resource subscription unavailable", None) |
| 53 | +} |
| 54 | +async fn snapshot(service: &GameService, viewer: Viewer, uri: &str) -> Result<String, ErrorData> { |
| 55 | + let id = state_id(uri).ok_or_else(|| { |
| 56 | + ErrorData::invalid_params("Only gfa://matches/{match_id}/state can be watched", None) |
| 57 | + })?; |
| 58 | + let state = tokio::time::timeout(IO_TIMEOUT, service.get_state(id, viewer)) |
| 59 | + .await |
| 60 | + .map_err(|_| unavailable())? |
| 61 | + .map_err(|error| ErrorData::invalid_params(error.message, None))?; |
| 62 | + let state = StateOutput::from_state(state, viewer).map_err(|_| unavailable())?; |
| 63 | + let encoded = serde_json::to_string(&state).map_err(|_| unavailable())?; |
| 64 | + if encoded.len() > 64 * 1024 { |
| 65 | + return Err(ErrorData::invalid_params( |
| 66 | + "State exceeds the live watch size limit", |
| 67 | + None, |
| 68 | + )); |
| 69 | + } |
| 70 | + Ok(encoded) |
| 71 | +} |
| 72 | +impl McpServer { |
| 73 | + pub(crate) fn accepted_watches(&self, requested: &SubscriptionFilter) -> SubscriptionFilter { |
| 74 | + let mut uris = requested |
| 75 | + .resource_subscriptions |
| 76 | + .as_ref() |
| 77 | + .into_iter() |
| 78 | + .flatten() |
| 79 | + .filter(|uri| state_id(uri).is_some()) |
| 80 | + .take(MAX_URIS) |
| 81 | + .cloned() |
| 82 | + .collect::<Vec<_>>(); |
| 83 | + uris.sort(); |
| 84 | + uris.dedup(); |
| 85 | + SubscriptionFilter::builder() |
| 86 | + .resource_subscriptions(uris) |
| 87 | + .build() |
| 88 | + } |
| 89 | + pub(crate) async fn listen_states( |
| 90 | + &self, |
| 91 | + context: SubscriptionContext, |
| 92 | + ) -> Result<(), ErrorData> { |
| 93 | + let _permit = self |
| 94 | + .watches |
| 95 | + .capacity |
| 96 | + .clone() |
| 97 | + .try_acquire_owned() |
| 98 | + .map_err(|_| unavailable())?; |
| 99 | + let uris = context |
| 100 | + .accepted() |
| 101 | + .resource_subscriptions |
| 102 | + .clone() |
| 103 | + .unwrap_or_default(); |
| 104 | + if uris.is_empty() { |
| 105 | + return Ok(()); |
| 106 | + } |
| 107 | + let mut previous = vec![None; uris.len()]; |
| 108 | + let mut tick = tokio::time::interval(POLL); |
| 109 | + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip); |
| 110 | + loop { |
| 111 | + tokio::select! { |
| 112 | + _=context.cancelled()=>return Ok(()), |
| 113 | + _=tick.tick()=>{} |
| 114 | + } |
| 115 | + for (index, uri) in uris.iter().enumerate() { |
| 116 | + let current = tokio::select! { |
| 117 | + _=context.cancelled()=>return Ok(()), |
| 118 | + state=snapshot(&self.service,self.viewer,uri)=>state?, |
| 119 | + }; |
| 120 | + if previous[index].as_ref() != Some(¤t) { |
| 121 | + tokio::select! { |
| 122 | + _=context.cancelled()=>return Ok(()), |
| 123 | + sent=tokio::time::timeout(IO_TIMEOUT,context.sink().notify_resource_updated(uri))=> { |
| 124 | + sent.map_err(|_|unavailable())?.map_err(|_|unavailable())?; |
| 125 | + } |
| 126 | + } |
| 127 | + previous[index] = Some(current); |
| 128 | + } |
| 129 | + } |
| 130 | + } |
| 131 | + } |
| 132 | + pub(crate) async fn subscribe_state( |
| 133 | + &self, |
| 134 | + uri: String, |
| 135 | + context: RequestContext<RoleServer>, |
| 136 | + ) -> Result<(), ErrorData> { |
| 137 | + let identity = context.peer.peer_info().ok_or_else(unavailable)?; |
| 138 | + let current = snapshot(&self.service, self.viewer, &uri).await?; |
| 139 | + let mut watches = self.watches.legacy.lock().await; |
| 140 | + watches.retain(|watch| !watch.task.is_finished()); |
| 141 | + if watches |
| 142 | + .iter() |
| 143 | + .any(|watch| Arc::ptr_eq(&watch.identity, &identity) && watch.uri == uri) |
| 144 | + { |
| 145 | + return Ok(()); |
| 146 | + } |
| 147 | + let permit = self |
| 148 | + .watches |
| 149 | + .capacity |
| 150 | + .clone() |
| 151 | + .try_acquire_owned() |
| 152 | + .map_err(|_| unavailable())?; |
| 153 | + let service = self.service.clone(); |
| 154 | + let viewer = self.viewer; |
| 155 | + let watched_uri = uri.clone(); |
| 156 | + let task = tokio::spawn(async move { |
| 157 | + let _permit = permit; |
| 158 | + legacy_loop(service, viewer, watched_uri, context.peer, current).await; |
| 159 | + }); |
| 160 | + watches.push(LegacyWatch { |
| 161 | + identity, |
| 162 | + uri, |
| 163 | + task, |
| 164 | + }); |
| 165 | + Ok(()) |
| 166 | + } |
| 167 | + pub(crate) async fn unsubscribe_state( |
| 168 | + &self, |
| 169 | + uri: &str, |
| 170 | + context: RequestContext<RoleServer>, |
| 171 | + ) -> Result<(), ErrorData> { |
| 172 | + let identity = context.peer.peer_info().ok_or_else(unavailable)?; |
| 173 | + self.watches.legacy.lock().await.retain(|watch| { |
| 174 | + !watch.task.is_finished() |
| 175 | + && !(watch.uri == uri && Arc::ptr_eq(&watch.identity, &identity)) |
| 176 | + }); |
| 177 | + Ok(()) |
| 178 | + } |
| 179 | +} |
| 180 | +async fn legacy_loop( |
| 181 | + service: Arc<GameService>, |
| 182 | + viewer: Viewer, |
| 183 | + uri: String, |
| 184 | + peer: Peer<RoleServer>, |
| 185 | + mut previous: String, |
| 186 | +) { |
| 187 | + loop { |
| 188 | + tokio::time::sleep(POLL).await; |
| 189 | + if peer.is_transport_closed() { |
| 190 | + return; |
| 191 | + } |
| 192 | + let Ok(current) = snapshot(&service, viewer, &uri).await else { |
| 193 | + return; |
| 194 | + }; |
| 195 | + if current != previous { |
| 196 | + let sent = tokio::time::timeout( |
| 197 | + IO_TIMEOUT, |
| 198 | + peer.notify_resource_updated(ResourceUpdatedNotificationParam::new(&uri)), |
| 199 | + ) |
| 200 | + .await; |
| 201 | + if !matches!(sent, Ok(Ok(()))) { |
| 202 | + return; |
| 203 | + } |
| 204 | + previous = current; |
| 205 | + } |
| 206 | + } |
| 207 | +} |
0 commit comments