|
| 1 | +use crate::{decode, internal, play_types::StateOutput, success, types::Failure, McpServer}; |
| 2 | +use gfa_api_types::{ |
| 3 | + AnalysisRequest, ApiError, OpponentConfig, SearchBudget, SimulateRequest, SimulationFrom, |
| 4 | + SimulationOutput, UciOptions, |
| 5 | +}; |
| 6 | +use rmcp::{model::CallToolResult, schemars::JsonSchema}; |
| 7 | +use serde::{Deserialize, Serialize}; |
| 8 | +use serde_json::{json, Value}; |
| 9 | + |
| 10 | +#[derive(Deserialize, JsonSchema)] |
| 11 | +#[schemars(crate = "rmcp::schemars")] |
| 12 | +#[serde(deny_unknown_fields)] |
| 13 | +pub(crate) struct SimulationArgs { |
| 14 | + pub match_id: String, |
| 15 | + /// Up to 16 independent lines, each with at most 32 canonical moves. |
| 16 | + pub lines: Vec<Vec<Value>>, |
| 17 | + pub from_turn: Option<u64>, |
| 18 | + /// Independent planning seed; never changes the match RNG. |
| 19 | + pub seed: Option<u64>, |
| 20 | +} |
| 21 | +#[derive(Serialize, JsonSchema)] |
| 22 | +#[schemars(crate = "rmcp::schemars")] |
| 23 | +pub(crate) struct LineError { |
| 24 | + pub index: usize, |
| 25 | + pub error: Failure, |
| 26 | +} |
| 27 | +#[derive(Serialize, JsonSchema)] |
| 28 | +#[schemars(crate = "rmcp::schemars")] |
| 29 | +pub(crate) struct Line { |
| 30 | + pub moves_applied: u32, |
| 31 | + pub state: StateOutput, |
| 32 | + pub error: Option<LineError>, |
| 33 | +} |
| 34 | +#[derive(Serialize, JsonSchema)] |
| 35 | +#[schemars(crate = "rmcp::schemars")] |
| 36 | +pub(crate) struct Simulation { |
| 37 | + pub game_id: String, |
| 38 | + pub seed: u64, |
| 39 | + pub lines: Vec<Line>, |
| 40 | +} |
| 41 | +#[derive(Deserialize, JsonSchema)] |
| 42 | +#[schemars(crate = "rmcp::schemars")] |
| 43 | +#[serde(deny_unknown_fields)] |
| 44 | +pub(crate) struct AnalysisArgs { |
| 45 | + pub match_id: String, |
| 46 | + pub turn: Option<u64>, |
| 47 | + /// Installed analysis provider; defaults to Stockfish, reference, minimax, MCTS, then random. |
| 48 | + pub opponent: Option<String>, |
| 49 | + pub level: Option<u8>, |
| 50 | + pub nodes: Option<u64>, |
| 51 | + pub depth: Option<u8>, |
| 52 | + pub time_ms: Option<u64>, |
| 53 | + /// 1..16 ranked lines; only supported by UCI providers. |
| 54 | + pub multi_pv: Option<u8>, |
| 55 | + pub seed: Option<u64>, |
| 56 | +} |
| 57 | +#[derive(Serialize, JsonSchema)] |
| 58 | +#[schemars(crate = "rmcp::schemars")] |
| 59 | +pub(crate) struct Recommendation { |
| 60 | + pub action: String, |
| 61 | + /// Expected game return, never a centipawn or mate score. |
| 62 | + pub evaluation: Option<f64>, |
| 63 | + pub principal_variation: Vec<String>, |
| 64 | + pub nodes: u64, |
| 65 | + pub depth: u8, |
| 66 | + pub budget_exhausted: bool, |
| 67 | + /// Provider explanation and labeled score units, if available. |
| 68 | + pub advice: Option<Value>, |
| 69 | +} |
| 70 | +#[derive(Serialize, JsonSchema)] |
| 71 | +#[schemars(crate = "rmcp::schemars")] |
| 72 | +pub(crate) struct Analysis { |
| 73 | + pub game_id: String, |
| 74 | + pub opponent: String, |
| 75 | + pub seed: u64, |
| 76 | + pub variations: Vec<Recommendation>, |
| 77 | +} |
| 78 | + |
| 79 | +impl McpServer { |
| 80 | + pub(crate) async fn simulate_tool(&self, arguments: Value) -> Result<CallToolResult, ApiError> { |
| 81 | + let args: SimulationArgs = decode(arguments)?; |
| 82 | + let seat = self.player()?; |
| 83 | + let game = self.service.get_match(&args.match_id).await?.game_id; |
| 84 | + let result = self |
| 85 | + .service |
| 86 | + .simulate( |
| 87 | + &game, |
| 88 | + SimulateRequest { |
| 89 | + from: SimulationFrom::Match { |
| 90 | + match_id: args.match_id, |
| 91 | + seat, |
| 92 | + turn: args.from_turn, |
| 93 | + }, |
| 94 | + config: json!({}), |
| 95 | + lines: args.lines, |
| 96 | + seed: args.seed, |
| 97 | + output: SimulationOutput::Final, |
| 98 | + }, |
| 99 | + self.viewer, |
| 100 | + ) |
| 101 | + .await?; |
| 102 | + let lines = result |
| 103 | + .lines |
| 104 | + .into_iter() |
| 105 | + .map(|line| { |
| 106 | + let state = StateOutput::from_state( |
| 107 | + line.states.into_iter().last().ok_or_else(internal)?, |
| 108 | + self.viewer, |
| 109 | + )?; |
| 110 | + Ok(Line { |
| 111 | + moves_applied: line.moves_applied, |
| 112 | + state, |
| 113 | + error: line.error.map(|error| LineError { |
| 114 | + index: error.index, |
| 115 | + error: crate::compact_failure(error.error), |
| 116 | + }), |
| 117 | + }) |
| 118 | + }) |
| 119 | + .collect::<Result<Vec<_>, ApiError>>()?; |
| 120 | + let text = lines |
| 121 | + .iter() |
| 122 | + .enumerate() |
| 123 | + .map(|(index, line)| { |
| 124 | + let error = line |
| 125 | + .error |
| 126 | + .as_ref() |
| 127 | + .map(|failure| { |
| 128 | + format!( |
| 129 | + "\nStopped at move {}: {} — {}", |
| 130 | + failure.index, failure.error.message, failure.error.hint |
| 131 | + ) |
| 132 | + }) |
| 133 | + .unwrap_or_default(); |
| 134 | + format!( |
| 135 | + "Line {}: {} moves applied{}\n{}", |
| 136 | + index + 1, |
| 137 | + line.moves_applied, |
| 138 | + error, |
| 139 | + line.state.text() |
| 140 | + ) |
| 141 | + }) |
| 142 | + .collect::<Vec<_>>() |
| 143 | + .join("\n\n"); |
| 144 | + success( |
| 145 | + Simulation { |
| 146 | + game_id: game, |
| 147 | + seed: result.seed, |
| 148 | + lines, |
| 149 | + }, |
| 150 | + text, |
| 151 | + ) |
| 152 | + } |
| 153 | + pub(crate) async fn analyze_tool(&self, arguments: Value) -> Result<CallToolResult, ApiError> { |
| 154 | + let args: AnalysisArgs = decode(arguments)?; |
| 155 | + let seat = self.player()?; |
| 156 | + let game = self.service.get_match(&args.match_id).await?.game_id; |
| 157 | + let opponent = if let Some(opponent) = args.opponent { |
| 158 | + opponent |
| 159 | + } else { |
| 160 | + let catalog = self.service.list_opponents(&game)?; |
| 161 | + ["stockfish", "reference", "minimax", "mcts", "random"] |
| 162 | + .into_iter() |
| 163 | + .find(|id| catalog.iter().any(|candidate| candidate.id == *id)) |
| 164 | + .ok_or_else(|| { |
| 165 | + ApiError::new( |
| 166 | + "ENGINE_UNAVAILABLE", |
| 167 | + "No analysis provider is installed", |
| 168 | + "Install a compatible opponent.", |
| 169 | + ) |
| 170 | + })? |
| 171 | + .to_string() |
| 172 | + }; |
| 173 | + let result = self |
| 174 | + .service |
| 175 | + .analyze( |
| 176 | + AnalysisRequest { |
| 177 | + game_id: game.clone(), |
| 178 | + from: SimulationFrom::Match { |
| 179 | + match_id: args.match_id, |
| 180 | + seat, |
| 181 | + turn: args.turn, |
| 182 | + }, |
| 183 | + config: json!({}), |
| 184 | + opponent: OpponentConfig { |
| 185 | + id: opponent, |
| 186 | + level: args.level, |
| 187 | + limits: SearchBudget { |
| 188 | + nodes: args.nodes, |
| 189 | + depth: args.depth, |
| 190 | + time_ms: args.time_ms, |
| 191 | + }, |
| 192 | + uci: args.multi_pv.map(|multipv| UciOptions { |
| 193 | + multipv: Some(multipv), |
| 194 | + ..Default::default() |
| 195 | + }), |
| 196 | + }, |
| 197 | + seed: args.seed, |
| 198 | + }, |
| 199 | + self.viewer, |
| 200 | + ) |
| 201 | + .await?; |
| 202 | + let variations = result |
| 203 | + .variations |
| 204 | + .into_iter() |
| 205 | + .map(|choice| { |
| 206 | + Ok(Recommendation { |
| 207 | + action: choice.action.string, |
| 208 | + evaluation: choice.info.evaluation, |
| 209 | + principal_variation: choice.info.principal_variation, |
| 210 | + nodes: choice.info.nodes, |
| 211 | + depth: choice.info.depth, |
| 212 | + budget_exhausted: choice.info.budget_exhausted, |
| 213 | + advice: choice |
| 214 | + .info |
| 215 | + .advice |
| 216 | + .map(serde_json::to_value) |
| 217 | + .transpose() |
| 218 | + .map_err(|_| internal())?, |
| 219 | + }) |
| 220 | + }) |
| 221 | + .collect::<Result<Vec<_>, ApiError>>()?; |
| 222 | + let text = variations.iter().enumerate().map(|(index,line)|format!( |
| 223 | + "{}. {} — expected return: {:?}, depth: {}, nodes: {}, budget exhausted: {}\nPV: {}\nAdvice: {}", |
| 224 | + index+1,line.action,line.evaluation,line.depth,line.nodes,line.budget_exhausted,line.principal_variation.join(" "), |
| 225 | + line.advice.as_ref().map_or_else(||"none".into(),Value::to_string) |
| 226 | + )).collect::<Vec<_>>().join("\n"); |
| 227 | + success( |
| 228 | + Analysis { |
| 229 | + game_id: game, |
| 230 | + opponent: result.opponent, |
| 231 | + seed: result.seed, |
| 232 | + variations, |
| 233 | + }, |
| 234 | + text, |
| 235 | + ) |
| 236 | + } |
| 237 | +} |
0 commit comments