aether-mcp-utils 0.5.34

MCP client and server utilities for the Aether AI agent framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
use crate::client::{RuntimeMcpServer, RuntimeMcpTransport, ToolExposure};
use rmcp::{
    ErrorData as McpError, Peer, RoleServer, ServerHandler,
    model::{
        CacheScope, CallToolRequestParams, CallToolResponse, CallToolResult, CancelTaskParams, ContentBlock,
        CreateTaskResult, DetailedTask, GetTaskParams, GetTaskResult, Implementation, ListToolsResult,
        PaginatedRequestParams, ProgressNotificationParam, ProtocolVersion, ResultType, ServerCapabilities, ServerInfo,
        Tool, UpdateTaskParams,
    },
    service::{DynService, RequestContext},
};
use serde_json::json;
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::sync::{Arc, Mutex};
use std::time::Duration;

pub fn fake_mcp(name: &str, server: FakeMcpServer) -> RuntimeMcpServer {
    RuntimeMcpServer::new(name, RuntimeMcpTransport::InMemory { server: server.into_dyn() }, ToolExposure::ModelVisible)
}

/// A fake MCP server preloaded with the classic math tools (`add_numbers`,
/// `divide_numbers`, `slow_tool`); add scripted tools with [`Self::with_tool`].
#[derive(Clone)]
pub struct FakeMcpServer {
    state: FakeMcpState,
}

#[derive(Clone, Default)]
pub struct FakeMcpState {
    inner: Arc<Mutex<FakeMcpStateInner>>,
}

#[derive(Clone)]
pub struct CapturedToolCall {
    pub request: CallToolRequestParams,
    pub context_meta: serde_json::Map<String, serde_json::Value>,
}

#[derive(Clone)]
pub struct CapturedTaskUpdate {
    pub task_id: String,
    pub input_responses: rmcp::model::InputResponses,
}

#[derive(Clone)]
pub struct FakeTool {
    definition: Tool,
    responses: HashMap<Option<String>, FakeToolResponse>,
    handler: Option<ToolHandler>,
}

#[derive(Clone)]
pub struct FakeToolResponse {
    response: CallToolResponse,
    delay: Duration,
    progress: Vec<(f64, Option<f64>)>,
    task_progress: Vec<(f64, Option<f64>)>,
}

impl FakeMcpServer {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_tool(self, tool: FakeTool) -> Self {
        self.state.add_tool(tool);
        self
    }

    pub fn with_task(self, task_id: impl Into<String>, states: impl IntoIterator<Item = DetailedTask>) -> Self {
        self.state.script_task(task_id, states);
        self
    }

    pub fn with_task_get_failures(self, failures: usize) -> Self {
        self.state.lock().task_get_failures = failures;
        self
    }

    pub fn with_task_update_failures(self, failures: usize) -> Self {
        self.state.lock().task_update_failures = failures;
        self
    }

    pub fn state(&self) -> FakeMcpState {
        self.state.clone()
    }

    pub fn into_dyn(self) -> Box<dyn DynService<RoleServer>> {
        Box::new(self)
    }
}

impl FakeMcpState {
    pub fn calls_for(&self, tool: &str) -> Vec<CapturedToolCall> {
        self.lock().calls.iter().filter(|call| call.request.name.as_ref() == tool).cloned().collect()
    }

    pub fn task_get_ids(&self) -> Vec<String> {
        self.lock().task_get_ids.clone()
    }

    pub fn task_updates(&self) -> Vec<CapturedTaskUpdate> {
        self.lock().task_updates.clone()
    }

    pub fn task_cancel_ids(&self) -> Vec<String> {
        self.lock().task_cancel_ids.clone()
    }

    pub fn script_task(&self, task_id: impl Into<String>, states: impl IntoIterator<Item = DetailedTask>) {
        self.lock().tasks.insert(task_id.into(), states.into_iter().collect());
    }

    fn task_for(&self, task_id: &str) -> Result<Option<DetailedTask>, ()> {
        let mut inner = self.lock();
        inner.task_get_ids.push(task_id.to_string());
        if inner.task_get_failures > 0 {
            inner.task_get_failures -= 1;
            return Err(());
        }
        let Some(states) = inner.tasks.get_mut(task_id) else {
            return Ok(None);
        };
        Ok(if states.len() > 1 { states.pop_front() } else { states.front().cloned() })
    }

    fn record_task_update(&self, request: UpdateTaskParams) -> bool {
        let mut inner = self.lock();
        inner
            .task_updates
            .push(CapturedTaskUpdate { task_id: request.task_id, input_responses: request.input_responses });
        if inner.task_update_failures > 0 {
            inner.task_update_failures -= 1;
            false
        } else {
            true
        }
    }

    fn record_task_cancel(&self, request: CancelTaskParams) {
        self.lock().task_cancel_ids.push(request.task_id);
    }

    pub fn add_tool(&self, tool: FakeTool) {
        self.lock().tools.insert(tool.definition.name.to_string(), tool);
    }

    pub async fn add_tool_and_notify(&self, tool: FakeTool) {
        let peers = {
            let mut inner = self.lock();
            inner.tools.insert(tool.definition.name.to_string(), tool);
            inner.peers.clone()
        };
        for peer in peers {
            let _ = peer.notify_tool_list_changed().await;
        }
    }

    pub async fn clear_tools_and_notify(&self) {
        let peers = {
            let mut inner = self.lock();
            inner.tools.clear();
            inner.peers.clone()
        };
        for peer in peers {
            let _ = peer.notify_tool_list_changed().await;
        }
    }

    pub fn fail_next_tool_list(&self) {
        self.lock().tool_list_failures += 1;
    }

    fn definitions(&self) -> Vec<Tool> {
        self.lock().tools.values().map(|tool| tool.definition.clone()).collect()
    }

    fn response_for(
        &self,
        request: &CallToolRequestParams,
        context_meta: serde_json::Map<String, serde_json::Value>,
    ) -> Option<FakeToolResponse> {
        let mut inner = self.lock();
        inner.calls.push(CapturedToolCall { request: request.clone(), context_meta });
        inner.tools.get(request.name.as_ref()).and_then(|tool| tool.response_for(request))
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, FakeMcpStateInner> {
        self.inner.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
    }
}

impl FakeTool {
    pub fn new(name: impl Into<String>) -> Self {
        let name = name.into();
        let schema = serde_json::from_value(json!({ "type": "object", "properties": {} }))
            .expect("empty object schema is valid");
        Self {
            definition: Tool::new(name, "Fake MCP tool", Arc::new(schema)),
            responses: HashMap::new(),
            handler: None,
        }
    }

    pub fn description(mut self, description: impl Into<String>) -> Self {
        self.definition.description = Some(description.into().into());
        self
    }

    pub fn responds(mut self, response: impl Into<FakeToolResponse>) -> Self {
        self.responses.insert(None, response.into());
        self
    }

    pub fn when_state(mut self, state: impl Into<String>, response: impl Into<FakeToolResponse>) -> Self {
        self.responses.insert(Some(state.into()), response.into());
        self
    }

    /// Compute the response from the request, for tools whose output depends
    /// on their arguments. Scripted responses take precedence.
    pub fn responds_with(
        mut self,
        handler: impl Fn(&CallToolRequestParams) -> FakeToolResponse + Send + Sync + 'static,
    ) -> Self {
        self.handler = Some(Arc::new(handler));
        self
    }

    fn response_for(&self, request: &CallToolRequestParams) -> Option<FakeToolResponse> {
        self.responses
            .get(&request.request_state.as_deref().map(str::to_string))
            .cloned()
            .or_else(|| self.handler.as_ref().map(|handler| handler(request)))
    }
}

impl FakeToolResponse {
    pub fn new(response: impl Into<CallToolResponse>) -> Self {
        Self { response: response.into(), delay: Duration::ZERO, progress: Vec::new(), task_progress: Vec::new() }
    }

    pub fn text(text: impl Into<String>) -> Self {
        Self::new(CallToolResult::success(vec![ContentBlock::text(text.into())]))
    }

    pub fn task(task: CreateTaskResult) -> Self {
        Self::new(CallToolResponse::Task(task))
    }

    pub fn delay(mut self, delay: Duration) -> Self {
        self.delay = delay;
        self
    }

    pub fn progress(mut self, progress: f64, total: Option<f64>) -> Self {
        self.progress.push((progress, total));
        self
    }

    pub fn task_progress(mut self, progress: f64, total: Option<f64>) -> Self {
        self.task_progress.push((progress, total));
        self
    }
}

impl<T> From<T> for FakeToolResponse
where
    T: Into<CallToolResponse>,
{
    fn from(response: T) -> Self {
        Self::new(response)
    }
}

impl Default for FakeMcpServer {
    fn default() -> Self {
        Self { state: FakeMcpState::default() }
            .with_tool(add_numbers())
            .with_tool(divide_numbers())
            .with_tool(slow_tool())
    }
}

impl ServerHandler for FakeMcpServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo::new(ServerCapabilities::builder().enable_tools().enable_tasks().build())
            .with_server_info(
                Implementation::new("fake-mcp-server", "0.1.0").with_description("A fake MCP server for testing"),
            )
            .with_instructions("A fake MCP server for testing")
    }

    async fn get_task(
        &self,
        request: GetTaskParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<GetTaskResult, McpError> {
        let task = match self.state.task_for(&request.task_id) {
            Ok(Some(task)) => task,
            Ok(None) => return Err(McpError::invalid_params(format!("unknown task: {}", request.task_id), None)),
            Err(()) => return Err(McpError::internal_error("scripted tasks/get failure", None)),
        };
        Ok(GetTaskResult::new(task))
    }

    async fn update_task(
        &self,
        request: UpdateTaskParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<(), McpError> {
        if !self.state.record_task_update(request) {
            return Err(McpError::internal_error("scripted tasks/update failure", None));
        }
        Ok(())
    }
    async fn cancel_task(
        &self,
        request: CancelTaskParams,
        _context: RequestContext<RoleServer>,
    ) -> Result<(), McpError> {
        self.state.record_task_cancel(request);
        Ok(())
    }

    async fn list_tools(
        &self,
        _request: Option<PaginatedRequestParams>,
        context: RequestContext<RoleServer>,
    ) -> Result<ListToolsResult, McpError> {
        let supports_cache_hints =
            context.protocol_version().is_some_and(|version| version >= ProtocolVersion::V_2026_07_28);
        let tools = {
            let mut inner = self.state.lock();
            if inner.tool_list_failures > 0 {
                inner.tool_list_failures -= 1;
                return Err(McpError::internal_error("scripted tools/list failure", None));
            }
            if inner.peers.is_empty() {
                inner.peers.push(context.peer);
            }
            inner.tools.values().map(|tool| tool.definition.clone()).collect()
        };
        Ok(ListToolsResult {
            result_type: Some(ResultType::COMPLETE),
            tools,
            meta: None,
            next_cursor: None,
            ttl_ms: supports_cache_hints.then_some(0),
            cache_scope: supports_cache_hints.then_some(CacheScope::Public),
        })
    }

    fn get_tool(&self, name: &str) -> Option<Tool> {
        self.state.definitions().into_iter().find(|tool| tool.name == name)
    }

    async fn call_tool(
        &self,
        request: CallToolRequestParams,
        context: RequestContext<RoleServer>,
    ) -> Result<CallToolResponse, McpError> {
        let response = self.state.response_for(&request, context.meta.0.0.clone());
        let Some(response) = response else {
            return Err(McpError::invalid_params(format!("unknown tool: {}", request.name), None));
        };

        if !response.delay.is_zero() {
            tokio::time::sleep(response.delay).await;
        }
        if let Some(token) = context.meta.get_progress_token() {
            for (progress, total) in response.progress {
                let mut notification = ProgressNotificationParam::new(token.clone(), progress);
                if let Some(total) = total {
                    notification = notification.with_total(total);
                }
                let _ = context.peer.notify_progress(notification).await;
            }
            if !response.task_progress.is_empty() {
                let peer = context.peer.clone();
                let token = token.clone();
                tokio::spawn(async move {
                    tokio::task::yield_now().await;
                    for (progress, total) in response.task_progress {
                        let mut notification = ProgressNotificationParam::new(token.clone(), progress);
                        if let Some(total) = total {
                            notification = notification.with_total(total);
                        }
                        let _ = peer.notify_progress(notification).await;
                    }
                });
            }
        }
        Ok(response.response)
    }
}

type ToolHandler = Arc<dyn Fn(&CallToolRequestParams) -> FakeToolResponse + Send + Sync>;

#[derive(Default)]
struct FakeMcpStateInner {
    tools: BTreeMap<String, FakeTool>,
    calls: Vec<CapturedToolCall>,
    tasks: HashMap<String, VecDeque<DetailedTask>>,
    task_get_ids: Vec<String>,
    task_updates: Vec<CapturedTaskUpdate>,
    task_cancel_ids: Vec<String>,
    task_get_failures: usize,
    task_update_failures: usize,
    tool_list_failures: usize,
    peers: Vec<Peer<RoleServer>>,
}

fn add_numbers() -> FakeTool {
    FakeTool::new("add_numbers").description("Adds two numbers together").responds_with(|request| {
        let sum = int_arg(request, "a") + int_arg(request, "b");
        FakeToolResponse::new(CallToolResult::structured(json!({ "sum": sum })))
    })
}

fn divide_numbers() -> FakeTool {
    FakeTool::new("divide_numbers").description("Divides two numbers").responds_with(|request| {
        let (a, b) = (int_arg(request, "a"), int_arg(request, "b"));
        if b == 0 {
            return FakeToolResponse::new(CallToolResult::error(vec![ContentBlock::text("Division by zero")]));
        }
        FakeToolResponse::new(CallToolResult::structured(json!({ "quotient": a / b })))
    })
}

fn slow_tool() -> FakeTool {
    FakeTool::new("slow_tool")
        .description("A tool that sleeps for a specified duration (for testing timeouts)")
        .responds_with(|request| {
            let sleep_ms = int_arg(request, "sleep_ms").unsigned_abs();
            FakeToolResponse::new(CallToolResult::structured(json!({ "message": format!("Slept for {sleep_ms}ms") })))
                .delay(Duration::from_millis(sleep_ms))
        })
}

fn int_arg(request: &CallToolRequestParams, name: &str) -> i64 {
    request.arguments.as_ref().and_then(|args| args.get(name)).and_then(serde_json::Value::as_i64).unwrap_or_default()
}