anda_engine 0.18.2

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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
//! 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, MetaObject,
        ResultType, TaskPayload, UpdateTaskParams,
    },
};
use serde::Deserialize;
use serde_json::json;
use std::{
    collections::{BTreeMap, BTreeSet, 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::select! {
                    biased;
                    _ = cancellation.cancelled() => return Err("MCP tool call cancelled".into()),
                    _ = tokio::time::sleep(MRTR_STATE_ROUND_DELAY) => {}
                }
            }
            CallToolResponse::Task(task) => {
                return match await_task_inner(
                    &route.server_id,
                    &route.name,
                    peer,
                    task,
                    tasks,
                    cancellation,
                    request_timeout,
                    elicitation,
                )
                .await?
                {
                    TaskOutcome::Complete(result) => Ok(result),
                    TaskOutcome::UnsupportedInput(keys) => Ok(unsupported_input_error(
                        route,
                        keys.iter().map(String::as_str),
                    )),
                };
            }
            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())
}

/// Drives one application-level `tools/call` through state-only MRTR rounds and
/// SEP-2663 tasks without prompting for client-side input.
pub(crate) async fn call_server_tool_rounds(
    server_id: &str,
    name: &str,
    peer: &Peer<RoleClient>,
    mut params: CallToolRequestParams,
    tasks: Option<&McpTasksConfig>,
    cancellation: &CancellationToken,
    request_timeout: Duration,
) -> 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 {name} request timed out"))??
            }
        };
        match response {
            CallToolResponse::Complete(result) => return Ok(result),
            CallToolResponse::InputRequired(result) => {
                if result
                    .input_requests
                    .as_ref()
                    .is_some_and(|requests| !requests.is_empty())
                {
                    return Err(format!("MCP tool {name} asked for input").into());
                }
                let Some(request_state) = result.request_state else {
                    return Err(format!(
                        "MCP tool {name} returned an input_required result with neither \
                         input requests nor request state"
                    )
                    .into());
                };
                params.request_state = Some(request_state);
                params.input_responses = None;
                tokio::select! {
                    biased;
                    _ = cancellation.cancelled() => return Err("MCP tool call cancelled".into()),
                    _ = tokio::time::sleep(MRTR_STATE_ROUND_DELAY) => {}
                }
            }
            CallToolResponse::Task(task) => {
                return match await_task_inner(
                    server_id,
                    name,
                    peer,
                    task,
                    tasks,
                    cancellation,
                    request_timeout,
                    None,
                )
                .await?
                {
                    TaskOutcome::Complete(result) => Ok(result),
                    TaskOutcome::UnsupportedInput(_) => {
                        Err(format!("MCP tool {name} asked for input").into())
                    }
                };
            }
            other => {
                return Err(
                    format!("MCP tool {name} returned an unsupported response: {other:?}").into(),
                );
            }
        }
    }

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

enum TaskOutcome {
    Complete(CallToolResult),
    UnsupportedInput(Vec<String>),
}

/// Decodes a completed SEP-2663 task payload into a [`CallToolResult`],
/// tolerating contentless complete results (`{}`, `{"resultType":"complete"}`,
/// or `_meta`-only objects) just like `Peer::call_tool_once`.
fn decode_task_call_tool_result(
    result: serde_json::Map<String, Json>,
) -> Result<CallToolResult, serde_json::Error> {
    match serde_json::from_value::<CallToolResult>(Json::Object(result.clone())) {
        Ok(call_result) => Ok(call_result),
        Err(original_err) => {
            #[derive(Deserialize)]
            #[serde(rename_all = "camelCase", deny_unknown_fields)]
            struct ContentlessCallToolResult {
                #[serde(default)]
                result_type: Option<ResultType>,
                #[serde(rename = "_meta", default)]
                meta: Option<MetaObject>,
            }
            match serde_json::from_value::<ContentlessCallToolResult>(Json::Object(result)) {
                Ok(helper)
                    if helper
                        .result_type
                        .as_ref()
                        .is_none_or(ResultType::is_complete) =>
                {
                    let mut out = CallToolResult::default();
                    out.result_type = helper.result_type;
                    out.meta = helper.meta;
                    Ok(out)
                }
                _ => Err(original_err),
            }
        }
    }
}

/// Polls a SEP-2663 task to a terminal state, fulfilling opted-in elicitation
/// rounds via `tasks/update` and cancelling the task best-effort whenever this
/// host walks away from it.
#[allow(clippy::too_many_arguments)]
async fn await_task_inner(
    server_id: &str,
    tool_name: &str,
    peer: &Peer<RoleClient>,
    created: CreateTaskResult,
    tasks: Option<&McpTasksConfig>,
    cancellation: &CancellationToken,
    request_timeout: Duration,
    elicitation: Option<&super::interaction::ElicitationDispatcher>,
) -> Result<TaskOutcome, 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 {tool_name} returned a task handle, but the tasks extension is not enabled \
             for server {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);
    let mut answered_keys = BTreeSet::new();
    let mut input_rounds = 0usize;
    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 {tool_name} task {task_id} did not finish within {}s",
                    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.
                let call_result = decode_task_call_tool_result(result).map_err(|err| {
                    format!("MCP tool {tool_name} returned an unreadable task result: {err}")
                })?;
                return Ok(TaskOutcome::Complete(call_result));
            }
            TaskPayload::Failed { error } => {
                cleanup.armed = false;
                return Err(format!(
                    "MCP tool {tool_name} task {task_id} failed: {}",
                    Json::Object(error)
                )
                .into());
            }
            TaskPayload::Cancelled => {
                cleanup.armed = false;
                return Err(format!("MCP tool {tool_name} task {task_id} was cancelled").into());
            }
            TaskPayload::InputRequired { input_requests } => {
                // SEP-2663 `tasks/update` is eventually consistent: a subsequent
                // `tasks/get` may still list keys we already answered.
                let pending: Vec<(&String, &rmcp::model::InputRequest)> = input_requests
                    .iter()
                    .filter(|(key, _)| !answered_keys.contains(key.as_str()))
                    .collect();
                if pending.is_empty() {
                    continue;
                }
                input_rounds += 1;
                if input_rounds > DEFAULT_MRTR_MAX_ROUNDS {
                    cleanup.armed = false;
                    cancel_task(peer, &task_id).await;
                    return Err(format!(
                        "MCP tool {tool_name} task {task_id} did not complete within \
                         {DEFAULT_MRTR_MAX_ROUNDS} input_required rounds"
                    )
                    .into());
                }
                // Validate the entire round before opening any application prompt.
                let Some(dispatcher) = elicitation.filter(|_| {
                    pending
                        .iter()
                        .all(|(_, req)| matches!(req, rmcp::model::InputRequest::Elicitation(_)))
                }) else {
                    cleanup.armed = false;
                    cancel_task(peer, &task_id).await;
                    return Ok(TaskOutcome::UnsupportedInput(
                        pending.into_iter().map(|(key, _)| key.clone()).collect(),
                    ));
                };
                let mut responses = BTreeMap::new();
                for (key, request) in &pending {
                    let rmcp::model::InputRequest::Elicitation(request) = request else {
                        unreachable!()
                    };
                    let elicited = tokio::select! {
                        biased;
                        _ = cancellation.cancelled() => {
                            cleanup.armed = false;
                            cancel_task(peer, &task_id).await;
                            return Err("MCP task cancelled".into());
                        }
                        res = tokio::time::timeout_at(
                            deadline,
                            dispatcher.elicit(request.params.clone(), cancellation),
                        ) => res,
                    };
                    let response = match elicited {
                        Ok(Ok(response)) => response,
                        Ok(Err(err)) => {
                            cleanup.armed = false;
                            cancel_task(peer, &task_id).await;
                            return Err(err);
                        }
                        Err(_) => {
                            cleanup.armed = false;
                            cancel_task(peer, &task_id).await;
                            return Err(format!(
                                "MCP tool {tool_name} task {task_id} did not finish within {}s",
                                max_wait.as_secs()
                            )
                            .into());
                        }
                    };
                    responses.insert((*key).clone(), serde_json::to_value(response)?);
                }
                let update_deadline = deadline.min(Instant::now() + request_timeout);
                let updated = tokio::select! {
                    biased;
                    _ = cancellation.cancelled() => {
                        cleanup.armed = false;
                        cancel_task(peer, &task_id).await;
                        return Err("MCP task cancelled".into());
                    }
                    res = tokio::time::timeout_at(
                        update_deadline,
                        peer.update_task(UpdateTaskParams::new(task_id.clone(), responses)),
                    ) => res,
                };
                match updated {
                    Ok(Ok(())) => {
                        for (key, _) in pending {
                            answered_keys.insert(key.clone());
                        }
                    }
                    Ok(Err(err)) => {
                        cleanup.armed = false;
                        cancel_task(peer, &task_id).await;
                        return Err(err.into());
                    }
                    Err(_) => {
                        cleanup.armed = false;
                        cancel_task(peer, &task_id).await;
                        return Err(format!(
                            "MCP tool {tool_name} task {task_id} update timed out"
                        )
                        .into());
                    }
                }
            }
            _ => {
                return Err(format!(
                    "MCP tool {tool_name} task {task_id} reported an unsupported status"
                )
                .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,
    /// Process-wide registration identity; changes when a server is 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)
}