use std::cell::RefCell;
use std::collections::{BTreeMap, HashSet};
use std::sync::{Mutex, OnceLock};
use serde_json::{Value, json};
#[cfg(feature = "http-server")]
use super::compress::{bare_tool_name, expand_tool_name};
const MAX_TRACKED: usize = 4096;
const EXPAND_TOOL_NAME: &str = "ctx_expand";
fn active_sessions() -> &'static Mutex<HashSet<u64>> {
static SESSIONS: OnceLock<Mutex<HashSet<u64>>> = OnceLock::new();
SESSIONS.get_or_init(|| Mutex::new(HashSet::new()))
}
pub fn mark_ccr_active(conv_id: u64) {
if let Ok(mut guard) = active_sessions().lock() {
if guard.len() >= MAX_TRACKED
&& !guard.contains(&conv_id)
&& let Some(&oldest) = guard.iter().next()
{
guard.remove(&oldest);
}
guard.insert(conv_id);
}
}
pub fn is_ccr_active(conv_id: u64) -> bool {
active_sessions().lock().is_ok_and(|g| g.contains(&conv_id))
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(crate) struct HandleUse {
expand: Option<String>,
list_read: bool,
correlation: Option<Correlation>,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
struct Correlation {
listed: Vec<String>,
by_call: BTreeMap<String, String>,
}
#[cfg(feature = "http-server")]
impl Correlation {
fn of(listed: Vec<String>, doc: Option<&Value>) -> Self {
let by_call = doc
.map(producing_calls)
.unwrap_or_default()
.into_iter()
.filter_map(|(call_id, producer)| {
Some((call_id.to_owned(), expand_of_producer(producer?, &listed)?))
})
.collect();
Self { listed, by_call }
}
}
#[cfg(feature = "http-server")]
fn producing_calls(doc: &Value) -> BTreeMap<&str, Option<&str>> {
fn note<'doc>(
calls: &mut BTreeMap<&'doc str, Option<&'doc str>>,
call_id: Option<&'doc Value>,
name: Option<&'doc Value>,
) {
let (Some(call_id), Some(name)) = (
call_id.and_then(Value::as_str),
name.and_then(Value::as_str),
) else {
return;
};
calls
.entry(call_id)
.and_modify(|known| {
if *known != Some(name) {
*known = None;
}
})
.or_insert(Some(name));
}
fn items<'doc>(doc: &'doc Value, key: &str) -> &'doc [Value] {
doc.get(key)
.and_then(Value::as_array)
.map_or(&[][..], Vec::as_slice)
}
let mut calls = BTreeMap::new();
for message in items(doc, "messages") {
let blocks = message.get("content").and_then(Value::as_array);
for block in blocks.into_iter().flatten() {
if block.get("type").and_then(Value::as_str) == Some("tool_use") {
note(&mut calls, block.get("id"), block.get("name"));
}
}
let tool_calls = message.get("tool_calls").and_then(Value::as_array);
for call in tool_calls.into_iter().flatten() {
let name = call
.get("function")
.and_then(|function| function.get("name"));
note(&mut calls, call.get("id"), name);
}
}
for item in items(doc, "input") {
if item.get("type").and_then(Value::as_str) == Some("function_call") {
note(&mut calls, item.get("call_id"), item.get("name"));
}
}
calls
}
#[cfg(feature = "http-server")]
const WRAPPER_TOOL: &str = "ctx_call";
#[cfg(feature = "http-server")]
fn expand_of_producer(producer: &str, listed: &[String]) -> Option<String> {
let bare = bare_tool_name(producer);
if !bare.starts_with("ctx_") || bare == WRAPPER_TOOL {
return None;
}
let prefix = producer.strip_suffix(bare)?;
listed
.iter()
.find(|tool| tool.strip_suffix(EXPAND_TOOL_NAME) == Some(prefix))
.cloned()
}
#[cfg(feature = "http-server")]
impl HandleUse {
pub(crate) fn for_request(doc: Option<&Value>, route_can_follow: bool) -> Self {
let listed = doc
.filter(|doc| route_can_follow && can_carry(doc))
.and_then(|doc| {
Shape::ALL
.iter()
.map(|shape| shape.listed_expand(doc))
.find(|listed| !listed.is_empty())
})
.unwrap_or_default();
Self::knowing(listed, doc)
}
fn knowing(listed: Vec<String>, doc: Option<&Value>) -> Self {
let protected = super::compress::protected();
let Some(first) = listed
.first()
.cloned()
.filter(|_| !protected || super::store_binding::host_store_bound())
else {
return Self {
list_read: true,
..Self::default()
};
};
Self {
expand: Some(first),
list_read: true,
correlation: protected.then(|| Correlation::of(listed, doc)),
}
}
pub(crate) fn follows(&self, doc: &Value) -> bool {
let Some(name) = self.expand.as_deref() else {
return false;
};
can_carry(doc)
&& Shape::ALL
.iter()
.any(|shape| match self.correlation.as_ref() {
Some(correlation) => shape.listed_expand(doc) == correlation.listed,
None => shape.registered_expand(doc).as_deref() == Some(name),
})
}
}
#[cfg(feature = "http-server")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Shape {
Messages,
Chat,
Responses,
Gemini,
}
#[cfg(feature = "http-server")]
impl Shape {
const ALL: [Self; 4] = [Self::Messages, Self::Chat, Self::Responses, Self::Gemini];
fn registered_expand(self, doc: &Value) -> Option<String> {
self.listed_expand(doc).into_iter().next()
}
fn listed_expand(self, doc: &Value) -> Vec<String> {
let mut listed: Vec<String> = Vec::new();
let tools = doc.get("tools").and_then(Value::as_array);
for tool in tools.into_iter().flatten() {
if tool.get("defer_loading").and_then(Value::as_bool) == Some(true) {
continue;
}
let names: Vec<String> = match self {
Self::Messages | Self::Responses => expand_name_of(tool).into_iter().collect(),
Self::Chat => tool
.get("function")
.and_then(expand_name_of)
.into_iter()
.collect(),
Self::Gemini => GEMINI_DECLARATIONS
.iter()
.filter_map(|key| tool.get(*key)?.as_array())
.flatten()
.filter_map(expand_name_of)
.collect(),
};
for name in names {
if !listed.contains(&name) {
listed.push(name);
}
}
}
listed
}
}
#[cfg(feature = "http-server")]
fn expand_name_of(entry: &Value) -> Option<String> {
entry
.get("name")
.and_then(Value::as_str)
.filter(|name| expand_tool_name(name))
.map(str::to_owned)
}
#[cfg(feature = "http-server")]
const GEMINI_DECLARATIONS: [&str; 2] = ["functionDeclarations", "function_declarations"];
#[cfg(feature = "http-server")]
fn can_carry(doc: &Value) -> bool {
let named = |value: Option<&Value>, name: &str| {
value
.and_then(Value::as_str)
.is_some_and(|given| given.eq_ignore_ascii_case(name))
};
let choice = doc.get("tool_choice");
let choice_type = choice.and_then(|choice| choice.get("type"));
let calling = doc
.get("toolConfig")
.or_else(|| doc.get("tool_config"))
.and_then(|config| {
config
.get("functionCallingConfig")
.or_else(|| config.get("function_calling_config"))
});
let narrowed = calling
.and_then(|calling| {
calling
.get("allowedFunctionNames")
.or_else(|| calling.get("allowed_function_names"))
})
.and_then(Value::as_array)
.is_some_and(|names| !names.is_empty());
let forbidden = named(choice, "none")
|| named(choice_type, "none")
|| named(choice_type, "allowed_tools")
|| named(calling.and_then(|calling| calling.get("mode")), "none")
|| narrowed
|| [
"functions",
"function_call",
"cachedContent",
"cached_content",
]
.iter()
.any(|key| doc.get(*key).is_some_and(|value| !value.is_null()));
if forbidden {
return false;
}
match doc.get("tools") {
None => true,
Some(Value::Array(tools)) => {
doc.get("contents").is_none()
|| tools.is_empty()
|| tools.iter().any(|tool| {
GEMINI_DECLARATIONS
.iter()
.any(|key| tool.get(*key).is_some())
})
}
Some(_) => false,
}
}
thread_local! {
static PASS: RefCell<Option<HandleUse>> = const { RefCell::new(None) };
}
pub(crate) fn within<T>(so_far: HandleUse, pass: impl FnOnce() -> T) -> (T, HandleUse) {
struct Restore(Option<HandleUse>);
impl Drop for Restore {
fn drop(&mut self) {
let outer = self.0.take();
PASS.with(|slot| *slot.borrow_mut() = outer);
}
}
let restore = Restore(PASS.with(|slot| slot.replace(Some(so_far))));
let result = pass();
let known = PASS
.with(|slot| slot.borrow_mut().take())
.unwrap_or_default();
drop(restore);
(result, known)
}
pub(crate) fn in_pass<T>(pass: impl FnOnce() -> T) -> T {
if PASS.with(|slot| slot.borrow().is_some()) {
pass()
} else {
within(HandleUse::default(), pass).0
}
}
#[cfg(feature = "http-server")]
fn update(change: impl FnOnce(&mut HandleUse)) {
PASS.with(|slot| {
if let Some(known) = slot.borrow_mut().as_mut() {
change(known);
}
});
}
#[cfg(feature = "http-server")]
pub(crate) fn begin(shape: Shape, doc: &Value) {
update(|known| {
let listed = if can_carry(doc) {
shape.listed_expand(doc)
} else {
Vec::new()
};
if !known.list_read {
*known = HandleUse::knowing(listed, Some(doc));
return;
}
let unchanged = match known.correlation.as_ref() {
Some(correlation) => correlation.listed == listed,
None => known.expand.as_ref() == listed.first(),
};
if !unchanged {
known.expand = None;
known.correlation = None;
}
});
}
thread_local! {
static BLOCK: RefCell<Option<String>> = const { RefCell::new(None) };
}
#[must_use = "the block ends where this is dropped"]
pub(crate) struct BlockScope {
outer: Option<String>,
}
impl Drop for BlockScope {
fn drop(&mut self) {
let outer = self.outer.take();
BLOCK.with(|slot| *slot.borrow_mut() = outer);
}
}
pub(crate) fn block(call_id: Option<&str>) -> BlockScope {
let call_id = call_id.map(str::to_owned);
BlockScope {
outer: BLOCK.with(|slot| slot.replace(call_id)),
}
}
fn expand_tool() -> Option<String> {
PASS.with(|slot| {
let slot = slot.borrow();
let Some(known) = slot.as_ref() else {
return Some(EXPAND_TOOL_NAME.to_owned());
};
let first = known.expand.as_ref()?;
match known.correlation.as_ref() {
Some(correlation) => BLOCK.with(|block| {
let call_id = block.borrow();
correlation.by_call.get(call_id.as_deref()?).cloned()
}),
None if super::compress::protected() => None,
None => Some(first.clone()),
}
})
}
pub(crate) fn expand_tool_for(original: &str) -> Option<String> {
let tool = expand_tool()?;
let correlated = PASS.with(|slot| {
slot.borrow()
.as_ref()
.is_some_and(|known| known.correlation.is_some())
});
if !correlated {
return Some(tool);
}
let call_id = BLOCK.with(|slot| slot.borrow().clone())?;
super::store_binding::delivered_for_call(original, &call_id).then_some(tool)
}
fn expand_tool_definition() -> Value {
json!({
"name": EXPAND_TOOL_NAME,
"description": "Retrieve the original uncompressed content of a compressed tool result by its tee handle or hash.",
"input_schema": {
"type": "object",
"properties": {
"id": {
"type": "string",
"description": "The tee path or hash handle from the compressed output."
}
},
"required": ["id"]
}
})
}
pub fn ensure_tool_present(conv_id: u64, doc: &mut Value) -> bool {
if !is_ccr_active(conv_id) {
return false;
}
let tools = match doc.get_mut("tools") {
Some(Value::Array(arr)) => arr,
Some(_) => return false,
None => {
doc["tools"] = Value::Array(Vec::new());
doc["tools"]
.as_array_mut()
.expect("tools just initialized as array")
}
};
let already_present = tools.iter().any(|t| {
t.get("name")
.and_then(Value::as_str)
.is_some_and(|n| n == EXPAND_TOOL_NAME)
});
if already_present {
return false;
}
tools.push(expand_tool_definition());
true
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
const NO_CCR: u64 = 0xAA01;
const INJECT: u64 = 0xAA02;
const DEDUP: u64 = 0xAA03;
const STABLE: u64 = 0xAA04;
const STICKY: u64 = 0xAA05;
#[test]
fn tool_not_injected_without_ccr() {
let mut doc = json!({"tools": [], "messages": []});
assert!(!ensure_tool_present(NO_CCR, &mut doc));
{
let found = &doc["tools"].as_array().unwrap();
assert!(found.is_empty(), "{found:?}");
}
}
#[test]
fn tool_injected_after_ccr_activation() {
mark_ccr_active(INJECT);
assert!(is_ccr_active(INJECT));
let mut doc = json!({"tools": [], "messages": []});
assert!(ensure_tool_present(INJECT, &mut doc));
assert_eq!(doc["tools"].as_array().unwrap().len(), 1);
assert_eq!(doc["tools"][0]["name"], "ctx_expand");
}
#[test]
fn tool_not_duplicated() {
mark_ccr_active(DEDUP);
let mut doc = json!({"tools": [expand_tool_definition()], "messages": []});
assert!(!ensure_tool_present(DEDUP, &mut doc));
assert_eq!(doc["tools"].as_array().unwrap().len(), 1);
}
#[test]
fn tools_array_stays_stable_after_ccr_activation() {
mark_ccr_active(STABLE);
let existing = json!({"name": "other_tool", "description": "test"});
let mut doc1 = json!({"tools": [existing.clone()], "messages": []});
ensure_tool_present(STABLE, &mut doc1);
let snap1 = serde_json::to_string(&doc1["tools"]).unwrap();
let mut doc2 = json!({"tools": [existing], "messages": []});
ensure_tool_present(STABLE, &mut doc2);
let snap2 = serde_json::to_string(&doc2["tools"]).unwrap();
assert_eq!(
snap1, snap2,
"tool list must be byte-identical across turns"
);
}
#[test]
fn sticky_survives_turn_without_markers() {
mark_ccr_active(STICKY);
assert!(is_ccr_active(STICKY));
let mut doc = json!({"tools": [], "messages": []});
assert!(ensure_tool_present(STICKY, &mut doc));
}
#[test]
fn max_tracked_does_not_panic() {
for i in 0..(MAX_TRACKED + 100) {
mark_ccr_active(i as u64);
}
assert!(active_sessions().lock().unwrap().len() <= MAX_TRACKED);
}
#[cfg(feature = "http-server")]
fn developer_mode() {
assert!(!crate::compress::protected(), "developer mode");
}
#[cfg(feature = "http-server")]
fn governed_project(root: &std::path::Path) {
let config = lean_ctx::core::paths::config_dir_read_only().expect("config directory");
std::fs::create_dir_all(&config).expect("config directory");
std::fs::write(
config.join("config.toml"),
format!(
"[context_gateway]\nmode = \"governed\"\n\n[proxy]\nproject_root = '{}'\n",
root.display()
),
)
.expect("gateway config");
assert!(crate::compress::protected(), "governed mode");
}
#[cfg(feature = "http-server")]
#[test]
fn passes_of_a_request_carry_the_expand_tool_and_nest() {
let _data = lean_ctx::core::data_dir::isolated_data_dir();
let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
developer_mode();
let prefixed = "mcp__lean-ctx__ctx_expand";
let doc = json!({"tools": [{"name": prefixed}]});
let known = HandleUse::for_request(Some(&doc), true);
let (first, known) = within(known, expand_tool);
assert_eq!(first.as_deref(), Some(prefixed));
let (later, known) = within(known, expand_tool);
assert_eq!(later.as_deref(), Some(prefixed));
assert_eq!(known, HandleUse::for_request(Some(&doc), true));
let (joined, known) = within(known, || {
in_pass(|| {
begin(Shape::Messages, &doc);
expand_tool()
})
});
assert_eq!(joined.as_deref(), Some(prefixed));
assert_eq!(known.expand.as_deref(), Some(prefixed));
let alone = in_pass(|| {
begin(Shape::Messages, &json!({"tools": [{"name": "bash"}]}));
expand_tool()
});
assert_eq!(alone, None);
assert_eq!(expand_tool().as_deref(), Some("ctx_expand"), "no pass");
let ((), outer) = within(known, || {
let (inner, _) = within(HandleUse::for_request(None, true), expand_tool);
assert_eq!(inner, None);
assert_eq!(expand_tool().as_deref(), Some(prefixed), "outer pass again");
});
assert_eq!(outer.expand.as_deref(), Some(prefixed));
}
#[cfg(feature = "http-server")]
#[test]
fn under_protection_a_listed_tool_is_named_only_for_a_correlated_block() {
use std::net::{IpAddr, Ipv4Addr};
use crate::store_binding::{bound_host, engine_delivers, listening_on};
let _data = lean_ctx::core::data_dir::isolated_data_dir();
let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
let directory = tempfile::tempdir().expect("project");
let root = directory.path().canonicalize().expect("canonical root");
governed_project(&root);
let prefixed = "mcp__lean-ctx__ctx_expand";
let other = "mcp__other__ctx_expand";
let use_of = |id: &str, name: &str| json!({"type": "tool_use", "id": id, "name": name});
let doc = json!({"tools": [{"name": prefixed}, {"name": other}], "messages": [
{"role": "assistant", "content": [
use_of("toolu_X", "mcp__lean-ctx__ctx_read"),
use_of("toolu_O", "mcp__other__ctx_shell"),
use_of("toolu_B", "Bash"),
use_of("toolu_W", "mcp__lean-ctx__ctx_call"),
use_of("toolu_T", "mcp__third__ctx_read"),
use_of("toolu_D", "mcp__lean-ctx__ctx_read"),
use_of("toolu_D", "mcp__other__ctx_read"),
]},
]});
let alone = || {
in_pass(|| {
begin(Shape::Messages, &doc);
expand_tool()
})
};
let named = |known: &HandleUse, id: Option<&str>| {
within(known.clone(), || {
let _block = block(id);
expand_tool()
})
.0
};
let unbound = HandleUse::for_request(Some(&doc), true);
assert_eq!(unbound.expand, None);
assert_eq!(named(&unbound, Some("toolu_X")), None);
assert_eq!(alone(), None);
{
let _loopback = listening_on(IpAddr::V4(Ipv4Addr::LOCALHOST));
assert_eq!(HandleUse::for_request(Some(&doc), true).expand, None);
assert_eq!(alone(), None);
}
{
let _bound = bound_host(&root);
let known = HandleUse::for_request(Some(&doc), true);
assert_eq!(known.expand.as_deref(), Some(prefixed));
assert!(known.follows(&doc));
assert!(
!known.follows(&json!({"tools": [{"name": prefixed}]})),
"a stub may name either listed tool: both have to leave listed"
);
assert_eq!(alone(), None, "no block, no name");
assert_eq!(named(&known, None), None);
assert_eq!(named(&known, Some("toolu_X")).as_deref(), Some(prefixed));
assert_eq!(named(&known, Some("toolu_O")).as_deref(), Some(other));
assert_eq!(named(&known, Some("toolu_B")), None, "a native tool");
assert_eq!(named(&known, Some("toolu_W")), None, "the wrapper");
assert_eq!(named(&known, Some("toolu_T")), None, "prefix not listed");
assert_eq!(named(&known, Some("toolu_D")), None, "one id, two tools");
assert_eq!(named(&known, Some("toolu_unknown")), None);
let ((), _) = within(known.clone(), || {
let outer = block(Some("toolu_X"));
{
let _inner = block(Some("toolu_O"));
assert_eq!(expand_tool().as_deref(), Some(other));
}
assert_eq!(expand_tool().as_deref(), Some(prefixed));
drop(outer);
assert_eq!(expand_tool(), None);
});
let text = "pub fn kept() {}\n";
let decided = |id: &str, text: &str| {
within(known.clone(), || {
let _block = block(Some(id));
expand_tool_for(text)
})
.0
};
assert_eq!(decided("toolu_X", text), None, "nothing on record");
engine_delivers(&root, "other.rs", text, text, None);
assert_eq!(decided("toolu_X", text), None, "a digest hit alone");
engine_delivers(&root, "kept.rs", text, text, Some("toolu_X"));
assert_eq!(decided("toolu_X", text).as_deref(), Some(prefixed));
assert_eq!(decided("toolu_X", "other bytes"), None);
assert_eq!(decided("toolu_O", text), None, "another call");
assert_eq!(decided("toolu_B", text), None, "a native tool");
let (narrowed, _) = within(known.clone(), || {
begin(Shape::Messages, &json!({"tools": [{"name": prefixed}]}));
let _block = block(Some("toolu_X"));
expand_tool_for(text)
});
assert_eq!(narrowed, None);
let unprotected = HandleUse {
correlation: None,
..known.clone()
};
assert_eq!(named(&unprotected, Some("toolu_X")), None);
}
{
let _reachable = listening_on(IpAddr::V4(Ipv4Addr::UNSPECIFIED));
let known = HandleUse::for_request(Some(&doc), true);
assert_eq!(known.expand, None);
assert_eq!(named(&known, Some("toolu_X")), None);
assert_eq!(alone(), None);
}
assert_eq!(HandleUse::for_request(Some(&doc), true).expand, None);
}
#[cfg(feature = "http-server")]
#[test]
fn the_producing_call_and_its_servers_expand_tool_are_read_per_shape() {
let messages = json!({"messages": [
{"role": "user", "content": "go"},
{"role": "assistant", "content": [
{"type": "text", "text": "reading"},
{"type": "tool_use", "id": "toolu_1", "name": "mcp__a__ctx_read"},
]},
]});
let chat = json!({"messages": [
{"role": "assistant", "tool_calls": [
{"id": "call_1", "type": "function", "function": {"name": "a.ctx_read"}},
{"id": "call_2", "type": "function", "function": {}},
]},
]});
let responses = json!({"input": [
{"type": "function_call", "call_id": "c1", "name": "ctx_read"},
{"type": "function_call_output", "call_id": "c1", "output": "text"},
{"type": "message", "call_id": "c2", "name": "ctx_read"},
]});
let gemini = json!({"contents": [
{"role": "model", "parts": [{"functionCall": {"id": "g1", "name": "ctx_read"}}]},
]});
assert_eq!(
producing_calls(&messages),
BTreeMap::from([("toolu_1", Some("mcp__a__ctx_read"))])
);
assert_eq!(
producing_calls(&chat),
BTreeMap::from([("call_1", Some("a.ctx_read"))])
);
assert_eq!(
producing_calls(&responses),
BTreeMap::from([("c1", Some("ctx_read"))])
);
assert!(producing_calls(&gemini).is_empty(), "no call id is read");
assert!(producing_calls(&json!({"messages": "none"})).is_empty());
let listed = [
"mcp__a__ctx_expand".to_owned(),
"a.ctx_expand".to_owned(),
"ctx_expand".to_owned(),
];
for (producer, expand) in [
("mcp__a__ctx_read", Some("mcp__a__ctx_expand")),
("mcp__a__ctx_expand", Some("mcp__a__ctx_expand")),
("a.ctx_shell", Some("a.ctx_expand")),
("ctx_read", Some("ctx_expand")),
("mcp__b__ctx_read", None),
("b.ctx_read", None),
("mcp__a__ctx_call", None),
("ctx_call", None),
("ctx", None),
("Bash", None),
("mcp__a__read", None),
("mcp__a__", None),
("", None),
] {
assert_eq!(
expand_of_producer(producer, &listed).as_deref(),
expand,
"{producer}"
);
}
assert_eq!(expand_of_producer("ctx_read", &listed[..2]), None);
let doc = json!({"tools": [
{"name": "bash"},
{"name": "mcp__a__ctx_expand"},
{"name": "mcp__b__ctx_expand", "defer_loading": true},
{"name": "mcp__c__ctx_expand"},
{"name": "mcp__a__ctx_expand"},
]});
assert_eq!(
Shape::Messages.listed_expand(&doc),
["mcp__a__ctx_expand", "mcp__c__ctx_expand"]
);
assert_eq!(
Shape::Messages.registered_expand(&doc).as_deref(),
Some("mcp__a__ctx_expand")
);
}
#[cfg(feature = "http-server")]
#[test]
fn the_expand_tool_is_only_what_the_hosts_own_list_names() {
let _data = lean_ctx::core::data_dir::isolated_data_dir();
let _community = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
developer_mode();
let prefixed = "mcp__lean-ctx__ctx_expand";
let listed = [
(Shape::Messages, json!({"tools": [{"name": prefixed}]})),
(
Shape::Chat,
json!({"tools": [{"type": "function", "function": {"name": prefixed}}]}),
),
(
Shape::Responses,
json!({"tools": [{"type": "function", "name": prefixed}]}),
),
(
Shape::Gemini,
json!({"contents": [], "tools": [{"functionDeclarations": [{"name": prefixed}]}]}),
),
(
Shape::Gemini,
json!({"contents": [], "tools": [{"function_declarations": [{"name": prefixed}]}]}),
),
];
for (shape, doc) in &listed {
assert_eq!(shape.registered_expand(doc).as_deref(), Some(prefixed));
let known = HandleUse::for_request(Some(doc), true);
assert_eq!(known.expand.as_deref(), Some(prefixed), "{doc}");
assert!(known.follows(doc));
assert!(!known.follows(&json!({"tools": []})), "no longer listed");
assert_eq!(
HandleUse::for_request(Some(doc), false).expand,
None,
"a route whose body is not read"
);
let ((), confirmed) = within(known, || begin(*shape, doc));
assert_eq!(confirmed.expand.as_deref(), Some(prefixed));
assert_eq!(
in_pass(|| {
begin(*shape, doc);
expand_tool()
})
.as_deref(),
Some(prefixed)
);
}
assert_eq!(Shape::Chat.registered_expand(&listed[0].1), None);
assert_eq!(Shape::Messages.registered_expand(&listed[1].1), None);
for name in [
"ctx_expand",
"lean-ctx:ctx_expand",
"lean-ctx/ctx_expand",
"a.ctx_expand",
] {
let doc = json!({"tools": [{"name": "other"}, {"name": name}]});
assert_eq!(
Shape::Messages.registered_expand(&doc).as_deref(),
Some(name)
);
}
let long = format!("{}__ctx_expand", "a".repeat(128));
for doc in [
json!({"messages": []}),
json!({"tools": []}),
json!({"tools": [{"name": "ctx_call"}, {"name": "ctx"}, {"name": "ctx_expander"}]}),
json!({"tools": [{"name": "mcp__lean ctx__ctx_expand"}]}),
json!({"tools": [{"name": "x]\n__ctx_expand"}]}),
json!({"tools": [{"name": long}]}),
json!({"tools": [{"name": prefixed, "defer_loading": true}]}),
json!({"tools": [{"type": "mcp", "server_label": "lean-ctx"}]}),
json!({"tools": [{"name": prefixed}], "tool_choice": {"type": "none"}}),
json!({"tools": [{"name": prefixed}], "tool_choice": "none"}),
json!({"tools": {"name": prefixed}}),
] {
let known = HandleUse::for_request(Some(&doc), true);
assert_eq!(known.expand, None, "{doc}");
assert!(!known.follows(&doc));
let (tool, _) = within(known, || {
begin(Shape::Messages, &doc);
expand_tool()
});
assert_eq!(tool, None, "{doc}");
}
assert_eq!(HandleUse::for_request(None, true).expand, None);
let ((), narrowed) = within(HandleUse::for_request(Some(&listed[0].1), true), || {
begin(Shape::Messages, &json!({"tools": [{"name": "ctx_expand"}]}));
});
assert_eq!(narrowed.expand, None);
assert_eq!(expand_tool().as_deref(), Some("ctx_expand"));
}
}