aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-mcp / src / transport.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | //! `rmcp` client and server transports behind [`crate::McpWire`]. |
| 17 | //! |
| 18 | //! Effect class is not read from the server. Enrollment supplies it. A listed |
| 19 | //! tool with no enrolled class fails discovery instead of being treated as safe. |
| 20 | |
| 21 | use std::collections::HashMap; |
| 22 | use std::sync::{Arc, Mutex}; |
| 23 | |
| 24 | use aien_capability::{Digest32, ToolDescriptor, ToolEffects}; |
| 25 | use rmcp::model::{ |
| 26 | CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Implementation, |
| 27 | JsonObject, ListToolsResult, ServerCapabilities, ServerConfig, |
| 28 | }; |
| 29 | use rmcp::service::{ClientCacheConfig, RequestContext, RoleClient, RoleServer, RunningService}; |
| 30 | use rmcp::transport::IntoTransport; |
| 31 | use rmcp::{Peer, ServerHandler, ServiceExt}; |
| 32 | use serde_json::Value; |
| 33 | |
| 34 | use crate::{CallOutcome, Error, McpWire}; |
| 35 | |
| 36 | /// Client peer for one admitted provider. The `rmcp` session stays inside this type. |
| 37 | pub(crate) struct RmcpClientWire { |
| 38 | peer: Peer<RoleClient>, |
| 39 | service: Mutex<Option<RunningService<RoleClient, ()>>>, |
| 40 | effects: HashMap<String, ToolEffects>, |
| 41 | } |
| 42 | |
| 43 | impl RmcpClientWire { |
| 44 | pub(crate) async fn connect<T, E, A>( |
| 45 | transport: T, |
| 46 | effects: HashMap<String, ToolEffects>, |
| 47 | ) -> Result<Self, Error> |
| 48 | where |
| 49 | T: IntoTransport<RoleClient, E, A>, |
| 50 | E: std::error::Error + Send + Sync + 'static, |
| 51 | { |
| 52 | let service = ().serve(transport).await.map_err(|err| Error::Transport(err.to_string()))?; |
| 53 | service |
| 54 | .set_response_cache_config(ClientCacheConfig::disabled()) |
| 55 | .await; |
| 56 | let peer = service.peer().clone(); |
| 57 | Ok(Self { |
| 58 | peer, |
| 59 | service: Mutex::new(Some(service)), |
| 60 | effects, |
| 61 | }) |
| 62 | } |
| 63 | } |
| 64 | |
| 65 | impl Drop for RmcpClientWire { |
| 66 | fn drop(&mut self) { |
| 67 | if let Ok(mut guard) = self.service.lock() { |
| 68 | drop(guard.take()); |
| 69 | } |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | #[async_trait::async_trait] |
| 74 | impl McpWire for RmcpClientWire { |
| 75 | async fn list_tools(&self) -> Result<Vec<ToolDescriptor>, Error> { |
| 76 | let listed = self |
| 77 | .peer |
| 78 | .list_all_tools() |
| 79 | .await |
| 80 | .map_err(|err| Error::Transport(err.to_string()))?; |
| 81 | let mut descriptors = Vec::with_capacity(listed.len()); |
| 82 | let mut seen = std::collections::HashSet::new(); |
| 83 | for tool in listed { |
| 84 | let name = tool.name.into_owned(); |
| 85 | if !seen.insert(name.clone()) { |
| 86 | return Err(Error::Transport(format!("duplicate tool `{name}`"))); |
| 87 | } |
| 88 | let Some(effects) = self.effects.get(&name).copied() else { |
| 89 | return Err(Error::UnclassifiedTool(name)); |
| 90 | }; |
| 91 | let schema = Value::Object((*tool.input_schema).clone()); |
| 92 | descriptors.push(ToolDescriptor::new( |
| 93 | name, |
| 94 | effects, |
| 95 | Digest32::of(&canonical_bytes(&schema)), |
| 96 | )); |
| 97 | } |
| 98 | Ok(descriptors) |
| 99 | } |
| 100 | |
| 101 | async fn call_tool(&self, name: &str, arguments: &Value) -> Result<CallOutcome, Error> { |
| 102 | let arguments = match arguments { |
| 103 | Value::Null => None, |
| 104 | Value::Object(map) => Some(map.clone()), |
| 105 | _ => { |
| 106 | return Ok(CallOutcome::Rejected( |
| 107 | "tool arguments must be a JSON object".into(), |
| 108 | )); |
| 109 | } |
| 110 | }; |
| 111 | let mut params = CallToolRequestParams::new(name.to_owned()); |
| 112 | if let Some(arguments) = arguments { |
| 113 | params = params.with_arguments(arguments); |
| 114 | } |
| 115 | match self.peer.call_tool(params).await { |
| 116 | Ok(result) => Ok(outcome_from(result)), |
| 117 | Err(err) => Err(Error::Transport(err.to_string())), |
| 118 | } |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | fn outcome_from(result: CallToolResult) -> CallOutcome { |
| 123 | if result.is_error.unwrap_or(false) { |
| 124 | let reason = result |
| 125 | .content |
| 126 | .iter() |
| 127 | .find_map(|block| block.as_text().map(|text| text.text.clone())) |
| 128 | .unwrap_or_else(|| "tool call failed".into()); |
| 129 | return CallOutcome::Rejected(reason); |
| 130 | } |
| 131 | if let Some(value) = result.structured_content { |
| 132 | return CallOutcome::Finished(value); |
| 133 | } |
| 134 | let text = result |
| 135 | .content |
| 136 | .iter() |
| 137 | .find_map(|block| block.as_text().map(|text| text.text.clone())) |
| 138 | .unwrap_or_default(); |
| 139 | CallOutcome::Finished(Value::String(text)) |
| 140 | } |
| 141 | |
| 142 | type ToolCall = Arc<dyn Fn(&Value) -> Result<Value, String> + Send + Sync>; |
| 143 | |
| 144 | /// One tool the in-process server exposes over `rmcp`. |
| 145 | pub struct LocalTool { |
| 146 | name: String, |
| 147 | description: String, |
| 148 | input_schema: JsonObject, |
| 149 | call: ToolCall, |
| 150 | } |
| 151 | |
| 152 | impl LocalTool { |
| 153 | pub fn new<F>( |
| 154 | name: impl Into<String>, |
| 155 | description: impl Into<String>, |
| 156 | input_schema: JsonObject, |
| 157 | call: F, |
| 158 | ) -> Self |
| 159 | where |
| 160 | F: Fn(&Value) -> Result<Value, String> + Send + Sync + 'static, |
| 161 | { |
| 162 | Self { |
| 163 | name: name.into(), |
| 164 | description: description.into(), |
| 165 | input_schema, |
| 166 | call: Arc::new(call) as ToolCall, |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | /// Server transport. It speaks `tools/list` and `tools/call` and does not mint |
| 172 | /// [`crate::AuthorizedEffect`]. |
| 173 | #[derive(Clone)] |
| 174 | pub struct LocalToolServer { |
| 175 | tools: Arc<Mutex<Vec<LocalTool>>>, |
| 176 | } |
| 177 | |
| 178 | impl LocalToolServer { |
| 179 | pub fn new(tools: Vec<LocalTool>) -> Self { |
| 180 | Self { |
| 181 | tools: Arc::new(Mutex::new(tools)), |
| 182 | } |
| 183 | } |
| 184 | |
| 185 | /// Replace the advertised catalog. The next admitted refresh observes it. |
| 186 | pub fn replace_tools(&self, tools: Vec<LocalTool>) { |
| 187 | *self |
| 188 | .tools |
| 189 | .lock() |
| 190 | .unwrap_or_else(|poisoned| poisoned.into_inner()) = tools; |
| 191 | } |
| 192 | |
| 193 | pub async fn serve<T, E, A>( |
| 194 | &self, |
| 195 | transport: T, |
| 196 | ) -> Result<RunningService<RoleServer, Self>, Error> |
| 197 | where |
| 198 | T: IntoTransport<RoleServer, E, A>, |
| 199 | E: std::error::Error + Send + Sync + 'static, |
| 200 | { |
| 201 | self.clone() |
| 202 | .serve(transport) |
| 203 | .await |
| 204 | .map_err(|err| Error::Transport(err.to_string())) |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | impl ServerHandler for LocalToolServer { |
| 209 | fn get_info(&self) -> ServerConfig { |
| 210 | ServerConfig::new(ServerCapabilities::builder().enable_tools().build()) |
| 211 | .with_server_info(Implementation::new("aien-mcp", env!("CARGO_PKG_VERSION"))) |
| 212 | .with_instructions("AIEN MCP transport. Effect class is enrolled separately.") |
| 213 | } |
| 214 | |
| 215 | async fn list_tools( |
| 216 | &self, |
| 217 | _request: Option<rmcp::model::PaginatedRequestParams>, |
| 218 | _context: RequestContext<RoleServer>, |
| 219 | ) -> Result<ListToolsResult, rmcp::ErrorData> { |
| 220 | let tools = self |
| 221 | .tools |
| 222 | .lock() |
| 223 | .unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 224 | let listed = tools |
| 225 | .iter() |
| 226 | .map(|tool| { |
| 227 | rmcp::model::Tool::new( |
| 228 | tool.name.clone(), |
| 229 | tool.description.clone(), |
| 230 | Arc::new(tool.input_schema.clone()), |
| 231 | ) |
| 232 | }) |
| 233 | .collect(); |
| 234 | Ok(ListToolsResult::with_all_items(listed).with_ttl_ms(0)) |
| 235 | } |
| 236 | |
| 237 | async fn call_tool( |
| 238 | &self, |
| 239 | request: CallToolRequestParams, |
| 240 | _context: RequestContext<RoleServer>, |
| 241 | ) -> Result<CallToolResponse, rmcp::ErrorData> { |
| 242 | let tools = self |
| 243 | .tools |
| 244 | .lock() |
| 245 | .unwrap_or_else(|poisoned| poisoned.into_inner()); |
| 246 | let Some(tool) = tools.iter().find(|tool| tool.name == request.name.as_ref()) else { |
| 247 | return Ok(CallToolResult::error(vec![ContentBlock::text(format!( |
| 248 | "unknown tool {}", |
| 249 | request.name |
| 250 | ))]) |
| 251 | .into()); |
| 252 | }; |
| 253 | let call = tool.call.clone(); |
| 254 | drop(tools); |
| 255 | let arguments = Value::Object(request.arguments.unwrap_or_default()); |
| 256 | match call(&arguments) { |
| 257 | Ok(value) => Ok(CallToolResult::structured(value).into()), |
| 258 | Err(reason) => Ok(CallToolResult::error(vec![ContentBlock::text(reason)]).into()), |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | fn canonical_bytes(value: &Value) -> Vec<u8> { |
| 264 | let mut out = Vec::new(); |
| 265 | write_canonical(value, &mut out); |
| 266 | out |
| 267 | } |
| 268 | |
| 269 | fn write_canonical(value: &Value, out: &mut Vec<u8>) { |
| 270 | match value { |
| 271 | Value::Null => out.extend_from_slice(b"null"), |
| 272 | Value::Bool(true) => out.extend_from_slice(b"true"), |
| 273 | Value::Bool(false) => out.extend_from_slice(b"false"), |
| 274 | Value::Number(number) => out.extend_from_slice(number.to_string().as_bytes()), |
| 275 | Value::String(text) => { |
| 276 | if let Ok(encoded) = serde_json::to_vec(text) { |
| 277 | out.extend_from_slice(&encoded); |
| 278 | } |
| 279 | } |
| 280 | Value::Array(items) => { |
| 281 | out.push(b'['); |
| 282 | for (index, item) in items.iter().enumerate() { |
| 283 | if index > 0 { |
| 284 | out.push(b','); |
| 285 | } |
| 286 | write_canonical(item, out); |
| 287 | } |
| 288 | out.push(b']'); |
| 289 | } |
| 290 | Value::Object(map) => { |
| 291 | let mut keys: Vec<&String> = map.keys().collect(); |
| 292 | keys.sort(); |
| 293 | out.push(b'{'); |
| 294 | for (index, key) in keys.iter().enumerate() { |
| 295 | if index > 0 { |
| 296 | out.push(b','); |
| 297 | } |
| 298 | if let Ok(encoded) = serde_json::to_vec(key) { |
| 299 | out.extend_from_slice(&encoded); |
| 300 | } |
| 301 | out.push(b':'); |
| 302 | write_canonical(&map[*key], out); |
| 303 | } |
| 304 | out.push(b'}'); |
| 305 | } |
| 306 | } |
| 307 | } |