anda_engine 0.16.6

Agents engine for Anda -- an AI agent framework built with Rust, powered by ICP and TEEs.
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
//! MCP tool routing: local name mapping, call rounds, and result adaptation.
//!
//! Maps remote MCP tool names onto collision-free Anda-facing names, drives one
//! `tools/call` through the `2026-07-28` intermediate answers (MRTR
//! `input_required` rounds, task handles) until a final result, and adapts
//! [`CallToolResult`] into the audited [`ToolOutput`] envelope.

use anda_core::{BoxError, CancellationToken, FunctionDefinition, Json, ToolOutput, Usage};
use rmcp::{
    Peer, RoleClient,
    model::{
        CallToolRequestParams, CallToolResponse, CallToolResult, CancelTaskParams, ContentBlock,
        CreateTaskResult, DEFAULT_MRTR_MAX_ROUNDS, GetTaskParams, InputRequiredResult, TaskPayload,
    },
};
use serde_json::json;
use std::{
    collections::hash_map::DefaultHasher,
    hash::{Hash, Hasher},
    time::Duration,
};

use super::McpTasksConfig;
use tokio::time::Instant;

const TASK_CANCEL_TIMEOUT: Duration = Duration::from_secs(2);

/// How many times to re-derive a local tool name before giving up on a collision.
pub(crate) const MAX_LOCAL_NAME_ATTEMPTS: usize = 8;

/// Pause between MRTR rounds that carry only `requestState`, i.e. the server
/// asking to be polled rather than asking for input.
pub(crate) const MRTR_STATE_ROUND_DELAY: Duration = Duration::from_millis(200);

/// Poll interval used when a task suggests none, plus the bounds applied to a
/// server-suggested one. A remote server controls `pollIntervalMs`, so it is
/// clamped instead of trusted.
pub(crate) const TASK_POLL_INTERVAL: Duration = Duration::from_secs(1);
pub(crate) const TASK_POLL_INTERVAL_MIN: Duration = Duration::from_millis(250);
pub(crate) const TASK_POLL_INTERVAL_MAX: Duration = Duration::from_secs(10);

/// Default ceiling on how long one tool call waits for a task to finish.
pub(crate) const DEFAULT_TASK_MAX_WAIT_SECS: u64 = 300;

/// Hard ceiling on a configured `max_wait_secs`.
///
/// A tool call blocks for the whole wait, so a day is already far past anything
/// sane; the bound also keeps the poll deadline from overflowing `Instant`.
pub(crate) const MAX_TASK_MAX_WAIT_SECS: u64 = 24 * 60 * 60;

/// Drives one `tools/call` until the server produces a result.
///
/// Before `2026-07-28` that took a single round trip. The revision adds two
/// intermediate answers: an MRTR `input_required` result (SEP-2322) and a task
/// handle (SEP-2663). Both are resolved here so the caller still sees one
/// [`CallToolResult`].
pub(crate) async fn call_tool_rounds(
    route: &McpToolRoute,
    peer: &Peer<RoleClient>,
    mut params: CallToolRequestParams,
    tasks: Option<&McpTasksConfig>,
    cancellation: &CancellationToken,
    request_timeout: Duration,
    elicitation: Option<&super::interaction::ElicitationDispatcher>,
) -> Result<CallToolResult, BoxError> {
    for _ in 0..DEFAULT_MRTR_MAX_ROUNDS {
        let response = tokio::select! {
            biased;
            _ = cancellation.cancelled() => return Err("MCP tool call cancelled".into()),
            response = tokio::time::timeout(request_timeout, peer.call_tool_once(params.clone())) => {
                response.map_err(|_| format!("MCP tool {} request timed out", route.name))??
            }
        };
        match response {
            CallToolResponse::Complete(result) => return Ok(result),
            CallToolResponse::InputRequired(result) => {
                // Only explicitly enabled standard elicitation reaches the app.
                // State-only rounds are polled within the same logical deadline.
                if let Some(requests) = result
                    .input_requests
                    .as_ref()
                    .filter(|requests| !requests.is_empty())
                {
                    // Validate the entire round before opening any application prompt.
                    let Some(dispatcher) = elicitation.filter(|_| {
                        requests.values().all(|request| {
                            matches!(request, rmcp::model::InputRequest::Elicitation(_))
                        })
                    }) else {
                        return Ok(input_required_error(route, &result));
                    };
                    let mut responses = std::collections::BTreeMap::new();
                    for (key, request) in requests {
                        let rmcp::model::InputRequest::Elicitation(request) = request else {
                            unreachable!()
                        };
                        let response = dispatcher
                            .elicit(request.params.clone(), cancellation)
                            .await?;
                        responses.insert(key.clone(), serde_json::to_value(response)?);
                    }
                    params.input_responses = Some(responses);
                    params.request_state = result.request_state;
                    continue;
                }
                let Some(request_state) = result.request_state else {
                    return Err(format!(
                        "MCP tool {} returned an input_required result with neither \
                         input requests nor request state",
                        route.name
                    )
                    .into());
                };
                params.request_state = Some(request_state);
                params.input_responses = None;
                tokio::time::sleep(MRTR_STATE_ROUND_DELAY).await;
            }
            CallToolResponse::Task(task) => {
                return await_task(route, peer, task, tasks, cancellation).await;
            }
            other => {
                return Err(format!(
                    "MCP tool {} returned an unsupported response: {other:?}",
                    route.name
                )
                .into());
            }
        }
    }

    Err(format!(
        "MCP tool {} did not complete within {DEFAULT_MRTR_MAX_ROUNDS} input_required rounds",
        route.name
    )
    .into())
}

/// Polls a SEP-2663 task to a terminal state and returns its tool result.
///
/// The task is cancelled best-effort whenever this host walks away from it, so
/// an abandoned task does not keep running on the server.
async fn await_task(
    route: &McpToolRoute,
    peer: &Peer<RoleClient>,
    created: CreateTaskResult,
    tasks: Option<&McpTasksConfig>,
    cancellation: &CancellationToken,
) -> Result<CallToolResult, BoxError> {
    let task_id = created.task.task_id.clone();
    let mut cleanup = TaskCleanup {
        peer: peer.clone(),
        task_id: task_id.clone(),
        armed: true,
    };
    let Some(tasks) = tasks else {
        cleanup.armed = false;
        cancel_task(peer, &task_id).await;
        return Err(format!(
            "MCP tool {} returned a task handle, but the tasks extension is not enabled \
             for server {}",
            route.name, route.server_id
        )
        .into());
    };

    let max_wait = tasks.max_wait();
    let deadline = Instant::now() + max_wait;
    let mut interval = task_poll_interval(created.task.poll_interval_ms);
    loop {
        let poll = tokio::select! {
            biased;
            _ = cancellation.cancelled() => {
                cleanup.armed = false;
                cancel_task(peer, &task_id).await;
                return Err("MCP task cancelled".into());
            }
            poll = tokio::time::timeout_at(deadline, async {
                tokio::time::sleep(interval).await;
                peer.get_task(GetTaskParams::new(task_id.clone())).await
            }) => poll,
        };
        let task = match poll {
            Ok(result) => result?.task,
            Err(_) => {
                cleanup.armed = false;
                cancel_task(peer, &task_id).await;
                return Err(format!(
                    "MCP tool {} task {task_id} did not finish within {}s",
                    route.name,
                    max_wait.as_secs()
                )
                .into());
            }
        };
        interval = task_poll_interval(task.task.poll_interval_ms);
        match task.payload {
            TaskPayload::Working => continue,
            TaskPayload::Completed { result } => {
                cleanup.armed = false;
                // The payload mirrors the result of the original request, so it
                // deserializes as the `tools/call` result it stands in for.
                return serde_json::from_value(Json::Object(result)).map_err(|err| {
                    format!(
                        "MCP tool {} returned an unreadable task result: {err}",
                        route.name
                    )
                    .into()
                });
            }
            TaskPayload::Failed { error } => {
                cleanup.armed = false;
                return Err(format!(
                    "MCP tool {} task {task_id} failed: {}",
                    route.name,
                    Json::Object(error)
                )
                .into());
            }
            TaskPayload::Cancelled => {
                cleanup.armed = false;
                return Err(format!("MCP tool {} task {task_id} was cancelled", route.name).into());
            }
            TaskPayload::InputRequired { input_requests } => {
                cleanup.armed = false;
                // Same reasoning as the MRTR round above: nothing here can answer a
                // sampling, elicitation, or roots request.
                cancel_task(peer, &task_id).await;
                return Ok(unsupported_input_error(
                    route,
                    input_requests.keys().map(String::as_str),
                ));
            }
            _ => {
                return Err(format!(
                    "MCP tool {} task {task_id} reported an unsupported status",
                    route.name
                )
                .into());
            }
        }
    }
}

// Also cancel a remote task when a parent runner drops the polling future.
struct TaskCleanup {
    peer: Peer<RoleClient>,
    task_id: String,
    armed: bool,
}

impl Drop for TaskCleanup {
    fn drop(&mut self) {
        if self.armed
            && let Ok(runtime) = tokio::runtime::Handle::try_current()
        {
            let peer = self.peer.clone();
            let task_id = self.task_id.clone();
            runtime.spawn(async move {
                cancel_task(&peer, &task_id).await;
            });
        }
    }
}

/// One Anda-facing route to an MCP tool.
#[derive(Debug, Clone)]
pub struct McpToolRoute {
    /// Anda-facing tool name.
    pub name: String,
    /// Configured MCP server id.
    pub server_id: String,
    /// Original MCP tool name.
    pub remote_name: String,
    /// Model-facing function definition.
    pub definition: FunctionDefinition,
    /// Original MCP definition, including untrusted annotations and output schema.
    pub tool: rmcp::model::Tool,
    /// Registration identity; changes when a server is removed and registered again.
    pub server_generation: u64,
    /// Catalog revision from which this route was published.
    pub catalog_revision: u64,
}

pub(super) fn tool_is_model_visible(tool: &rmcp::model::Tool) -> bool {
    let visibility = tool
        .meta
        .as_deref()
        .and_then(|meta| meta.get("ui"))
        .and_then(|ui| ui.get("visibility"));
    match visibility {
        None => true,
        Some(Json::Array(targets)) => targets
            .iter()
            .any(|target| target.as_str() == Some("model")),
        Some(_) => false,
    }
}

/// Minimal compatibility lowering; retain all remote constraints and references.
pub(super) fn model_schema(schema: &serde_json::Map<String, Json>) -> Json {
    let mut schema = schema.clone();
    if schema.get("type").and_then(Json::as_str) == Some("object")
        && schema.get("properties").is_none_or(Json::is_null)
    {
        schema.insert("properties".into(), json!({}));
    }
    Json::Object(schema)
}

/// Clamps a server-suggested `tasks/get` poll interval into a sane range.
pub(crate) fn task_poll_interval(poll_interval_ms: Option<u64>) -> Duration {
    poll_interval_ms
        .map(Duration::from_millis)
        .unwrap_or(TASK_POLL_INTERVAL)
        .clamp(TASK_POLL_INTERVAL_MIN, TASK_POLL_INTERVAL_MAX)
}

/// Abandons a task this host will not wait for, so the server can release it.
async fn cancel_task(peer: &Peer<RoleClient>, task_id: &str) {
    match tokio::time::timeout(
        TASK_CANCEL_TIMEOUT,
        peer.cancel_task(CancelTaskParams::new(task_id)),
    )
    .await
    {
        Ok(Ok(_)) => {}
        Ok(Err(err)) => log::debug!("MCP task {task_id} could not be cancelled: {err}"),
        Err(_) => log::debug!("MCP task {task_id} cancellation acknowledgement timed out"),
    }
}

pub(crate) fn input_required_error(
    route: &McpToolRoute,
    result: &InputRequiredResult,
) -> CallToolResult {
    let keys = result
        .input_requests
        .iter()
        .flat_map(|requests| requests.keys().map(String::as_str));
    unsupported_input_error(route, keys)
}

/// Tool-level error for a server round this host cannot answer.
///
/// Sampling and Roots are never advertised; elicitation requires explicit opt-in. Returning it as a failed tool result — rather
/// than an error that aborts the turn — lets the model choose another path.
pub(crate) fn unsupported_input_error<'a>(
    route: &McpToolRoute,
    request_keys: impl Iterator<Item = &'a str>,
) -> CallToolResult {
    let keys: Vec<&str> = request_keys.collect();
    let requested = if keys.is_empty() {
        String::new()
    } else {
        format!(" (requests: {})", keys.join(", "))
    };
    CallToolResult::error(vec![ContentBlock::text(format!(
        "MCP tool {} on server {} requires client-side input{requested}, which this host \
         does not provide for this call: sampling and roots are not supported; elicitation requires opt-in. Call the tool \
         with complete arguments, or use a different tool.",
        route.remote_name, route.server_id
    ))])
}

pub(crate) fn mcp_result_to_tool_output(
    route: &McpToolRoute,
    result: CallToolResult,
    limits: &super::McpLimits,
) -> ToolOutput<Json> {
    let mut output = ToolOutput::new(json!({
        "server_id": route.server_id,
        "tool": route.remote_name,
        "structured_content": result.structured_content,
        "content": result.content,
        "_meta": result.meta,
    }));
    output.model_output = Some(super::presentation::present_result(&output.output, limits));
    output.is_error = result.is_error;
    output.usage = Usage {
        requests: 1,
        ..Usage::default()
    };
    output
}

pub(crate) fn sanitize_name_part(input: &str) -> String {
    let mut out = String::new();
    let mut previous_underscore = false;
    for c in input.chars() {
        let c = c.to_ascii_lowercase();
        let valid = matches!(c, 'a'..='z' | '0'..='9');
        if valid {
            out.push(c);
            previous_underscore = false;
        } else if !previous_underscore {
            out.push('_');
            previous_underscore = true;
        }
    }
    let trimmed = out.trim_matches('_').to_string();
    let mut normalized = if trimmed.is_empty() {
        "x".to_string()
    } else {
        trimmed
    };
    if !normalized
        .chars()
        .next()
        .is_some_and(|c: char| c.is_ascii_lowercase())
    {
        normalized.insert(0, 'x');
    }
    normalized
}

pub(crate) fn shorten_with_hash(base: &str, key: &str) -> String {
    let mut hasher = DefaultHasher::new();
    key.hash(&mut hasher);
    let suffix = format!("{:08x}", hasher.finish() as u32);
    let max_prefix = 64usize.saturating_sub(suffix.len() + 1);
    let mut prefix = base.chars().take(max_prefix).collect::<String>();
    prefix = prefix.trim_end_matches('_').to_string();
    format!("{}_{}", prefix, suffix)
}