use std::collections::HashMap;
use sha2::{Digest, Sha256};
use crate::llm::LlmToolSchema;
use crate::llm_openai::{encode_tool_name, split_tool_name};
const MAX_WIRE_LEN: usize = 64;
const DIGEST_LEN: usize = 8;
const SEPARATOR: &str = "_FN_";
const MIN_EXT_SLUG: usize = 8;
#[must_use]
pub fn is_wire_safe(name: &str) -> bool {
!name.is_empty()
&& name.len() <= MAX_WIRE_LEN
&& name
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
}
#[must_use]
pub fn wire_tool_name(extension_id: &str, tool_name: &str) -> String {
let upstream = encode_tool_name(extension_id, tool_name);
if is_wire_safe(&upstream) {
return upstream;
}
let digest = pair_digest(extension_id, tool_name);
let budget = MAX_WIRE_LEN - DIGEST_LEN - 1;
let body = compose(&slug(extension_id), &slug(tool_name), budget);
if body.is_empty() {
return digest;
}
format!("{body}_{digest}")
}
#[derive(Debug, Default)]
pub struct ToolNameCodec {
by_wire: HashMap<String, (String, String)>,
}
impl ToolNameCodec {
#[must_use]
pub fn for_tools(tools: &[LlmToolSchema]) -> Self {
let mut by_wire: HashMap<String, (String, String)> = HashMap::new();
for tool in tools {
let wire = wire_tool_name(&tool.extension_id, &tool.tool_name);
let pair = (tool.extension_id.clone(), tool.tool_name.clone());
if let Some(existing) = by_wire.get(&wire)
&& *existing != pair
{
tracing::warn!(
wire_name = %wire, kept = ?existing, dropped = ?pair,
"two declared tools encode to the same LLM tool name; keeping the first"
);
continue;
}
by_wire.insert(wire, pair);
}
Self { by_wire }
}
#[must_use]
pub fn decode(&self, wire: &str) -> (String, String) {
self.by_wire
.get(wire)
.cloned()
.unwrap_or_else(|| split_tool_name(wire))
}
}
fn pair_digest(extension_id: &str, tool_name: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(extension_id.as_bytes());
hasher.update([0x1f]);
hasher.update(tool_name.as_bytes());
let bytes = hasher.finalize();
let mut out = String::with_capacity(DIGEST_LEN);
for byte in bytes.iter().take(DIGEST_LEN / 2) {
out.push_str(&format!("{byte:02x}"));
}
out
}
fn slug(raw: &str) -> String {
let mut out = String::with_capacity(raw.len());
let mut prev_underscore = false;
for c in raw.chars() {
if c.is_ascii_alphanumeric() || c == '-' {
out.push(c);
prev_underscore = false;
} else if !prev_underscore {
out.push('_');
prev_underscore = true;
}
}
out.trim_matches('_').to_string()
}
fn compose(ext_slug: &str, tool_slug: &str, budget: usize) -> String {
if ext_slug.is_empty() {
return clamp(tool_slug, budget);
}
let reserved = ext_slug.len().min(MIN_EXT_SLUG);
let tool = clamp(tool_slug, budget.saturating_sub(SEPARATOR.len() + reserved));
let ext = clamp(
ext_slug,
budget.saturating_sub(SEPARATOR.len() + tool.len()),
);
if ext.is_empty() {
return tool;
}
if tool.is_empty() {
return ext;
}
format!("{ext}{SEPARATOR}{tool}")
}
fn clamp(s: &str, max: usize) -> String {
if s.len() <= max {
return s.to_string();
}
s[..max].trim_end_matches(['_', '-']).to_string()
}
#[cfg(test)]
mod tests {
use super::*;
fn assert_safe(name: &str) {
assert!(
is_wire_safe(name),
"provider would reject this function name: {name:?}"
);
}
fn schema(extension_id: &str, tool_name: &str) -> LlmToolSchema {
LlmToolSchema {
extension_id: extension_id.into(),
tool_name: tool_name.into(),
description: String::new(),
parameters: serde_json::json!({ "type": "object" }),
}
}
#[test]
fn an_already_acceptable_name_is_left_exactly_as_encode_tool_name_makes_it() {
for (ext, tool) in [
("greentic.adaptive-cards", "validate_card"),
("http", "fetch"),
("", "remember"),
] {
assert_eq!(wire_tool_name(ext, tool), encode_tool_name(ext, tool));
}
}
#[test]
fn every_prefixed_id_family_is_made_acceptable() {
for (ext, tool) in [
("mcp:7f1c9a80-2b4e-4d55-9f1a-6c0d2e3b4a51", "get_quote"),
("component:ghcr.io/greentic/demo@sha256:abc123", "quote"),
("sorla:acme.insurance", "create_claim"),
("flow:quote-flow", "run"),
("mcp:srv-1", "insurance.quote"),
] {
assert_safe(&wire_tool_name(ext, tool));
}
}
#[test]
fn a_colon_bearing_id_keeps_its_tool_half_readable() {
let name = wire_tool_name("mcp:7f1c9a80-2b4e-4d55-9f1a-6c0d2e3b4a51", "get_quote");
assert!(name.contains("get_quote"), "got: {name}");
}
#[test]
fn an_over_long_pair_is_capped_at_the_provider_limit() {
let name = wire_tool_name(&format!("mcp:{}", "x".repeat(120)), &"long_tool".repeat(9));
assert_safe(&name);
assert_eq!(name.len(), MAX_WIRE_LEN, "the cap should be used in full");
}
#[test]
fn an_all_punctuation_pair_still_yields_a_usable_name() {
assert_safe(&wire_tool_name("...", "///"));
}
#[test]
fn encoding_is_deterministic() {
assert_eq!(
wire_tool_name("mcp:srv-1", "quote"),
wire_tool_name("mcp:srv-1", "quote")
);
}
#[test]
fn the_codec_decodes_every_declared_tool_back_to_its_dispatch_key() {
let tools = vec![
schema("mcp:7f1c9a80-2b4e-4d55-9f1a-6c0d2e3b4a51", "get_quote"),
schema("component:ghcr.io/greentic/demo:1.2.0", "quote"),
schema("sorla:acme.insurance", "create_claim"),
schema("flow:quote-flow", "run"),
schema("greentic.adaptive-cards", "validate_card"),
];
let codec = ToolNameCodec::for_tools(&tools);
for tool in &tools {
let wire = wire_tool_name(&tool.extension_id, &tool.tool_name);
assert_eq!(
codec.decode(&wire),
(tool.extension_id.clone(), tool.tool_name.clone()),
"{wire} must dispatch to the tool the model was shown"
);
}
}
#[test]
fn an_unknown_name_falls_back_to_the_split() {
let codec = ToolNameCodec::default();
assert_eq!(
codec.decode("greentic_DOT_adaptive-cards_FN_validate_card"),
(
"greentic.adaptive-cards".to_string(),
"validate_card".to_string()
)
);
}
#[test]
fn ids_that_slugify_identically_still_get_distinct_names() {
let a = wire_tool_name("mcp:srv-1", "quote");
let b = wire_tool_name("mcp:srv/1", "quote");
assert_ne!(a, b, "slug collision leaked into the wire name");
let codec =
ToolNameCodec::for_tools(&[schema("mcp:srv-1", "quote"), schema("mcp:srv/1", "quote")]);
assert_eq!(codec.decode(&a).0, "mcp:srv-1");
assert_eq!(codec.decode(&b).0, "mcp:srv/1");
}
}