diff --git a/Cargo.lock b/Cargo.lock
index df18f7c5e..bf49239bc 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -694,7 +694,7 @@ checksum = "1c133bc6a41be0d194c306b5506d15e6feeea7b1d6604bd3f8310dfb2ca96486"
[[package]]
name = "cli"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"anyhow",
"api",
@@ -1366,7 +1366,7 @@ dependencies = [
[[package]]
name = "environment-daemon"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"anyhow",
"clap",
@@ -1421,7 +1421,7 @@ dependencies = [
[[package]]
name = "environment-provider-incus"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"anyhow",
"async-trait",
@@ -2719,10 +2719,12 @@ dependencies = [
"async-trait",
"base64 0.23.1",
"harness",
+ "hex",
"image",
"llm-clients",
"serde",
"serde_json",
+ "sha2 0.11.0",
"test-support",
"thiserror 2.0.21",
"tokio",
@@ -4251,7 +4253,7 @@ dependencies = [
[[package]]
name = "release-info"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"tempfile",
]
@@ -5326,7 +5328,7 @@ dependencies = [
[[package]]
name = "temporal-runtime"
-version = "0.11.0"
+version = "0.12.0"
dependencies = [
"anyhow",
"api",
diff --git a/Cargo.toml b/Cargo.toml
index 002eea697..db3a22a21 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -29,4 +29,4 @@ members = [
resolver = "2"
[workspace.package]
-version = "0.11.0"
+version = "0.12.0"
diff --git a/clients/python/pyproject.toml b/clients/python/pyproject.toml
index cfcb5b48a..fd88baf1c 100644
--- a/clients/python/pyproject.toml
+++ b/clients/python/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "lightspeed-ai"
-version = "0.11.0"
+version = "0.12.0"
description = "Async Python SDK for the Lightspeed HTTP API"
readme = "README.md"
requires-python = ">=3.12"
diff --git a/clients/python/uv.lock b/clients/python/uv.lock
index 835895b2a..4e418edb0 100644
--- a/clients/python/uv.lock
+++ b/clients/python/uv.lock
@@ -334,7 +334,7 @@ wheels = [
[[package]]
name = "lightspeed-ai"
-version = "0.11.0"
+version = "0.12.0"
source = { editable = "." }
dependencies = [
{ name = "httpx" },
diff --git a/crates/api-projection/src/lib.rs b/crates/api-projection/src/lib.rs
index 97e45cd50..df1bbe3fe 100644
--- a/crates/api-projection/src/lib.rs
+++ b/crates/api-projection/src/lib.rs
@@ -1288,12 +1288,16 @@ impl<'a> CoreAgentProjector<'a> {
try_join_all(calls.iter().map(|call| async move {
let arguments = self.read_blob_text(&call.arguments_ref).await?;
Ok(ToolCallEventView {
- tool_id: call.tool_id.as_ref().map(|id| id.as_str().to_owned()),
+ tool_id: call.tool_id().map(|id| id.as_str().to_owned()),
call_id: call.call_id.as_str().to_owned(),
tool_name: call.tool_name.as_str().to_owned(),
arguments_ref: call.arguments_ref.as_str().to_owned(),
arguments: Some(truncate_utf8(&arguments, MAX_INLINE_TEXT_BYTES)),
- display: tool_call_display(call.tool_name.as_str(), &arguments),
+ display: tool_call_display(
+ call.target.as_ref(),
+ call.tool_name.as_str(),
+ &arguments,
+ ),
})
}))
.await
@@ -1328,7 +1332,7 @@ impl<'a> CoreAgentProjector<'a> {
let result = result_by_call.get(call.call_id.as_str());
let arguments = self.read_blob_text(&call.arguments_ref).await?;
Ok(ToolCallView {
- tool_id: call.tool_id.as_ref().map(|id| id.as_str().to_owned()),
+ tool_id: call.tool_id().map(|id| id.as_str().to_owned()),
call_id: call.call_id.as_str().to_owned(),
tool_name: call.tool_name.as_str().to_owned(),
arguments_ref: call.arguments_ref.as_str().to_owned(),
@@ -1344,7 +1348,7 @@ impl<'a> CoreAgentProjector<'a> {
// A call that names no tool never starts. Any other is
// only requested until its start commits.
status: result.map(|result| result.status).unwrap_or(
- if call.tool_id.is_some() {
+ if call.target.is_some() {
ToolItemStatus::Requested
} else {
ToolItemStatus::Unavailable
@@ -1358,7 +1362,11 @@ impl<'a> CoreAgentProjector<'a> {
.get(call.call_id.as_str())
.cloned()
.unwrap_or_default(),
- display: tool_call_display(call.tool_name.as_str(), &arguments),
+ display: tool_call_display(
+ call.target.as_ref(),
+ call.tool_name.as_str(),
+ &arguments,
+ ),
started_at_ms: None,
finished_at_ms: None,
duration_ms: None,
@@ -2995,8 +3003,25 @@ fn json_field_text(value: &Value, field: &str) -> Option {
(!text.is_empty()).then_some(text)
}
-fn tool_call_display(tool_name: &str, arguments: &str) -> Option {
+fn tool_call_display(
+ target: Option<&harness::ResolvedToolTarget>,
+ tool_name: &str,
+ arguments: &str,
+) -> Option {
let json = serde_json::from_str::(arguments).ok();
+ if let Some(harness::ResolvedToolTarget::Mcp {
+ server_label,
+ remote_name,
+ ..
+ }) = target
+ {
+ return Some(ToolCallDisplayView {
+ group: ToolCallDisplayGroup::Mcp,
+ verb: server_label.clone(),
+ target: Some(remote_name.clone()),
+ detail: json.as_ref().and_then(first_scalar_text),
+ });
+ }
let normalized = tool_name.to_ascii_lowercase();
let view = match normalized.as_str() {
"code_execute" => ToolCallDisplayView {
@@ -3345,19 +3370,6 @@ fn tool_call_display(tool_name: &str, arguments: &str) -> Option
- {
- let (server, tool) = tool_name.strip_prefix("mcp_")?.split_once("__")?;
- ToolCallDisplayView {
- group: ToolCallDisplayGroup::Mcp,
- verb: server.to_owned(),
- target: Some(tool.to_owned()),
- detail: json.as_ref().and_then(first_scalar_text),
- }
- }
_ => ToolCallDisplayView {
group: ToolCallDisplayGroup::Other,
verb: tool_name.to_owned(),
@@ -3678,20 +3690,20 @@ mod tests {
#[test]
fn code_display_summarizes_source_without_exposing_it_in_the_row() {
- let display = tool_call_display("code_execute", r#"{"code":"const result = await tools.vfs_read_file({path:'/notes'});\ntext(result);\n"}"#).unwrap();
+ let display = tool_call_display(None, "code_execute", r#"{"code":"const result = await tools.vfs_read_file({path:'/notes'});\ntext(result);\n"}"#).unwrap();
assert_eq!(display.group, ToolCallDisplayGroup::Code);
assert_eq!(display.verb, "Run code");
assert_eq!(display.target.as_deref(), Some("JavaScript"));
assert_eq!(display.detail.as_deref(), Some("2 lines"));
assert_eq!(
- tool_call_display("code_execute", r#"{"code":"return 1"}"#)
+ tool_call_display(None, "code_execute", r#"{"code":"return 1"}"#)
.unwrap()
.detail
.as_deref(),
Some("1 line")
);
for arguments in ["{", "{}", r#"{"code":" "}"#] {
- let display = tool_call_display("code_execute", arguments).unwrap();
+ let display = tool_call_display(None, "code_execute", arguments).unwrap();
assert_eq!(display.group, ToolCallDisplayGroup::Code);
assert_eq!(display.detail, None);
}
@@ -3751,7 +3763,7 @@ mod tests {
),
] {
for name in names {
- let display = tool_call_display(name, args).unwrap();
+ let display = tool_call_display(None, name, args).unwrap();
assert_eq!(display.group, group, "{name}");
assert_eq!(display.verb, verb, "{name}");
assert_eq!(display.target.as_deref(), Some(target), "{name}");
@@ -3847,7 +3859,7 @@ mod tests {
"process1",
),
] {
- let display = tool_call_display(name, args).unwrap();
+ let display = tool_call_display(None, name, args).unwrap();
assert_eq!(display.group, group, "{name}");
assert_eq!(display.verb, verb, "{name}");
assert_eq!(display.target.as_deref(), Some(target), "{name}");
@@ -3859,13 +3871,32 @@ mod tests {
#[test]
fn injected_mcp_display_preserves_names_and_unknown_tools_stay_generic() {
- let display = tool_call_display("mcp_docs__Search", r#"{"query":"QuickJS"}"#).unwrap();
+ let binding = harness::ResolvedToolTarget::Mcp {
+ server_tool_id: harness::ToolId::new("mcp_docs__internal"),
+ server_label: "docs__internal".into(),
+ remote_name: "search_by_document_metadata".into(),
+ };
+ let display = tool_call_display(
+ Some(&binding),
+ "mcp_docs__search_hash_metadata",
+ r#"{"query":"QuickJS"}"#,
+ )
+ .unwrap();
assert_eq!(display.group, ToolCallDisplayGroup::Mcp);
- assert_eq!(display.verb, "docs");
- assert_eq!(display.target.as_deref(), Some("Search"));
+ assert_eq!(display.verb, "docs__internal");
+ assert_eq!(
+ display.target.as_deref(),
+ Some("search_by_document_metadata")
+ );
assert_eq!(display.detail.as_deref(), Some("QuickJS"));
- for name in ["custom_tool", "mcp_unknown", "mcp___", "mcp_docs__"] {
- let display = tool_call_display(name, "{}").unwrap();
+ for name in [
+ "mcp_docs__Search",
+ "custom_tool",
+ "mcp_unknown",
+ "mcp___",
+ "mcp_docs__",
+ ] {
+ let display = tool_call_display(None, name, "{}").unwrap();
assert_eq!(display.group, ToolCallDisplayGroup::Other);
assert_eq!(display.verb, name);
}
@@ -3874,6 +3905,7 @@ mod tests {
#[test]
fn runtime_mcp_search_call_displays_the_resolved_server_and_tool() {
let display = tool_call_display(
+ None,
"mcp_call",
r#"{"server":"configurator","tool":"lightspeed_models_list","arguments":{}}"#,
)
@@ -3884,6 +3916,7 @@ mod tests {
assert_eq!(display.detail, None);
let display = tool_call_display(
+ None,
"mcp_call",
r#"{"server":"stripe","tool":"retrieve_subscription","arguments":{"id":"sub_1R0aB3"}}"#,
)
@@ -3912,6 +3945,7 @@ mod tests {
#[test]
fn subagent_calls_display_the_profile_and_the_brief() {
let display = tool_call_display(
+ None,
"agent_run",
r#"{"agent":"reviewer","input":"Review the diff on skills2.\n\nFocus on tests."}"#,
)
@@ -3925,6 +3959,7 @@ mod tests {
);
let display = tool_call_display(
+ None,
"agent_spawn",
r#"{"agent":"researcher","input":"Find prior art","label":"Prior art"}"#,
)
@@ -3933,6 +3968,7 @@ mod tests {
assert_eq!(display.detail.as_deref(), Some("Prior art"));
let display = tool_call_display(
+ None,
"await",
r#"{"promises":["promise_3","promise_4"],"mode":"any"}"#,
)
@@ -3946,6 +3982,7 @@ mod tests {
#[test]
fn bot_emit_distinguishes_self_from_addressed_peers() {
let display = tool_call_display(
+ None,
"bot_emit",
r#"{"kind":"bug.confirmed","summary":"Duplicates on page boundary","to":"escalations","reply":true}"#,
)
@@ -3959,6 +3996,7 @@ mod tests {
);
let display = tool_call_display(
+ None,
"bot_emit",
r#"{"kind":"research.followup","summary":"Nightly","sessionKey":"nightly"}"#,
)
@@ -3982,6 +4020,7 @@ mod tests {
#[test]
fn runtime_mcp_detail_display_names_the_requested_tools() {
let display = tool_call_display(
+ None,
"mcp_find_tools",
r#"{"server":"configurator","names":["models_list","sessions_read"]}"#,
)
@@ -4077,7 +4116,7 @@ mod tests {
let batch_id = harness::ToolBatchId::new(1);
let call = |id: &str, tool_id: Option<&str>| harness::ObservedToolCall {
call_id: harness::ToolCallId::new(id),
- tool_id: tool_id.map(harness::ToolId::new),
+ target: tool_id.map(harness::ToolId::new).map(Into::into),
tool_name: harness::ToolName::new("read_file"),
provider_kind: None,
arguments_ref: arguments_ref.clone(),
@@ -5775,7 +5814,7 @@ mod tests {
toolset_revision: 0,
calls: vec![harness::ObservedToolCall {
call_id: call_id.clone(),
- tool_id: None,
+ target: None,
tool_name: harness::ToolName::new("mcp_echo__hello"),
provider_kind: None,
arguments_ref: arguments_ref.clone(),
diff --git a/crates/harness/src/core/components/code_tool.rs b/crates/harness/src/core/components/code_tool.rs
index 471b9d29f..a9bff4079 100644
--- a/crates/harness/src/core/components/code_tool.rs
+++ b/crates/harness/src/core/components/code_tool.rs
@@ -72,7 +72,8 @@ pub(crate) fn interrupt_code_tools_for_run(state: &mut CoreAgentState, run_id: c
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CodeToolBinding {
- pub tool_id: ToolId,
+ #[serde(alias = "tool_id")]
+ pub target: crate::ResolvedToolTarget,
pub tool_name: ToolName,
}
@@ -334,13 +335,13 @@ fn validate_scope(state: &CoreAgentState, scope: &CodeToolScopeSpec) -> Result<(
.ok_or_else(|| invalid("code tool parent binding is missing"))?;
for (binding_id, binding) in &scope.bindings {
validate_id("binding_id", binding_id)?;
- let tool_id = &binding.tool_id;
+ let tool_id = binding.target.tool_id();
let tool = state
.tooling
.tools
.get(tool_id)
.ok_or_else(|| invalid(format!("code tool {tool_id} is not granted")))?;
- if !tool.invokes_client_effect() || tool_id == &parent_tool.definition.tool.id {
+ if !tool.admits_call(&binding.target) || tool_id == &parent_tool.definition.tool.id {
return Err(invalid(format!(
"tool {tool_id} is not available for code tool execution"
)));
@@ -375,7 +376,7 @@ fn validate_recorded_call<'a>(
.bindings
.get(&call.binding_id)
.is_some_and(|binding| {
- binding.tool_id == call.tool_id && binding.tool_name == call.tool_name
+ binding.target.tool_id() == &call.tool_id && binding.tool_name == call.tool_name
})
{
return Err(invalid("code tool is outside the execution grant"));
@@ -826,6 +827,11 @@ pub fn code_tool_request(
"code tool request session does not match its parent",
));
}
+ let binding = scope
+ .spec
+ .bindings
+ .get(&call.spec.binding_id)
+ .ok_or_else(|| invalid("code tool binding is absent from its scope"))?;
let mut request = crate::core::drive::tool_invocation_request(
state,
session_id,
@@ -835,8 +841,8 @@ pub fn code_tool_request(
call.promise_id_base,
std::slice::from_ref(&crate::ObservedToolCall {
call_id: call.call_id.clone(),
- tool_id: Some(call.spec.tool_id.clone()),
- tool_name: call.spec.tool_name.clone(),
+ target: Some(binding.target.clone()),
+ tool_name: binding.tool_name.clone(),
provider_kind: None,
arguments_ref: call.spec.arguments_ref.clone(),
native_call_ref: None,
diff --git a/crates/harness/src/core/components/ids.rs b/crates/harness/src/core/components/ids.rs
index 3a1ca42e8..afbe6d2ed 100644
--- a/crates/harness/src/core/components/ids.rs
+++ b/crates/harness/src/core/components/ids.rs
@@ -4,7 +4,8 @@ use std::fmt;
pub use crate::session::{EventSeq, SessionId, StringIdError, validate_general_string_id};
-const TOOL_NAME_MAX_LEN: usize = 64;
+/// Shared wire-name budget across provider adapters. OpenAI function names allow 64 ASCII characters.
+pub const TOOL_NAME_MAX_LEN: usize = 64;
macro_rules! numeric_id {
($name:ident) => {
diff --git a/crates/harness/src/core/components/mod.rs b/crates/harness/src/core/components/mod.rs
index a6729e39a..349ea932b 100644
--- a/crates/harness/src/core/components/mod.rs
+++ b/crates/harness/src/core/components/mod.rs
@@ -79,13 +79,14 @@ pub use tooling::{
FAILED_WITHOUT_DETAIL_CONTENT, FunctionToolSpec, ObservedToolCall,
PROMISE_DEADLINE_EXCEEDED_CONTENT, ProviderNativeToolExecution, ProviderNativeToolSpec,
RECEIVER_CANCELLED_CONTENT, RemoteMcpApprovalPolicy, RemoteMcpExecution, RemoteMcpExposure,
- RemoteMcpToolSpec, TOOL_RUNTIME_BOUNDARY_FAILURE_CONTENT, ToolCallResult, ToolCallState,
- ToolCallStatus, ToolChoice, ToolConfigEvent, ToolEvent, ToolExecutionClass, ToolExecutionSpec,
- ToolKind, ToolParallelism, ToolPatch, ToolSpec, ToolingState, UNAVAILABLE_TOOL_RESULT_CONTENT,
- await_batch_conflict_ref, await_rejected_ref, cancelled_tool_result_ref, empty_success_ref,
- failed_without_detail_ref, promise_deadline_exceeded_ref, receiver_cancelled_ref,
- remote_mcp_call_runtime, tool_runtime_boundary_failure_ref, tools_frozen,
- unavailable_tool_result_ref, validate_tool_map,
+ RemoteMcpToolSpec, ResolvedToolTarget, TOOL_RUNTIME_BOUNDARY_FAILURE_CONTENT, ToolCallResult,
+ ToolCallState, ToolCallStatus, ToolChoice, ToolConfigEvent, ToolEvent, ToolExecutionClass,
+ ToolExecutionSpec, ToolKind, ToolParallelism, ToolPatch, ToolSpec, ToolingState,
+ UNAVAILABLE_TOOL_RESULT_CONTENT, await_batch_conflict_ref, await_rejected_ref,
+ cancelled_tool_result_ref, empty_success_ref, failed_without_detail_ref,
+ promise_deadline_exceeded_ref, receiver_cancelled_ref, remote_mcp_call_runtime,
+ tool_runtime_boundary_failure_ref, tools_frozen, unavailable_tool_result_ref,
+ validate_tool_map,
};
pub use turn::{
LlmFinish, LlmGenerationFacts, LlmGenerationStatus, LlmUsage, PlannedRequestState, TurnEvent,
diff --git a/crates/harness/src/core/components/tooling.rs b/crates/harness/src/core/components/tooling.rs
index dcdc15a66..713115b03 100644
--- a/crates/harness/src/core/components/tooling.rs
+++ b/crates/harness/src/core/components/tooling.rs
@@ -221,7 +221,6 @@ pub fn validate_tool_map(tools: &BTreeMap) -> Result<(), Domai
}
validate_unique_remote_mcp_server_labels(tools)?;
- validate_unique_runtime_mcp_prefixes(tools)?;
for tool in tools.values() {
tool.validate()?;
@@ -230,33 +229,6 @@ pub fn validate_tool_map(tools: &BTreeMap) -> Result<(), Domai
Ok(())
}
-fn validate_unique_runtime_mcp_prefixes(
- tools: &BTreeMap,
-) -> Result<(), DomainError> {
- let prefixes = tools
- .values()
- .filter_map(|tool| match &tool.kind {
- ToolKind::RemoteMcp(spec)
- if spec.execution == RemoteMcpExecution::Runtime
- && spec.exposure == RemoteMcpExposure::Inject =>
- {
- Some((format!("{}__", tool.id), &tool.id))
- }
- _ => None,
- })
- .collect::>();
- for (index, (prefix, name)) in prefixes.iter().enumerate() {
- for (other_prefix, other_name) in prefixes.iter().skip(index + 1) {
- if prefix.starts_with(other_prefix) || other_prefix.starts_with(prefix) {
- return Err(DomainError::InvariantViolation(format!(
- "runtime MCP tool prefixes for {name} and {other_name} are ambiguous"
- )));
- }
- }
- }
- Ok(())
-}
-
fn validate_unique_remote_mcp_server_labels(
tools: &BTreeMap,
) -> Result<(), DomainError> {
@@ -410,6 +382,31 @@ impl ToolSpec {
}
}
+ pub(crate) fn admits_call(&self, target: &ResolvedToolTarget) -> bool {
+ match (&self.kind, target) {
+ (
+ ToolKind::RemoteMcp(spec),
+ ResolvedToolTarget::Mcp {
+ server_label,
+ remote_name,
+ ..
+ },
+ ) => {
+ spec.execution == RemoteMcpExecution::Runtime
+ && spec.exposure == RemoteMcpExposure::Inject
+ && server_label == &spec.server_label
+ && spec
+ .allowed_tools
+ .as_ref()
+ .is_none_or(|allowed| allowed.contains(remote_name))
+ && validate_remote_mcp_allowed_tool_name(remote_name).is_ok()
+ }
+ (ToolKind::RemoteMcp(_), _) => false,
+ (_, ResolvedToolTarget::Registered(_)) => self.invokes_client_effect(),
+ _ => false,
+ }
+ }
+
pub fn invokes_client_effect(&self) -> bool {
match &self.kind {
ToolKind::Builtin(_) | ToolKind::Function(_) => true,
@@ -622,18 +619,54 @@ pub enum ToolParallelism {
ParallelSafe,
}
+/// Execution identity resolved from the advertised name in a model request or script scope.
+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
+#[serde(rename_all = "snake_case")]
+pub enum ResolvedToolTarget {
+ Mcp {
+ server_tool_id: ToolId,
+ server_label: String,
+ remote_name: String,
+ },
+ #[serde(untagged)]
+ Registered(ToolId),
+}
+
+impl ResolvedToolTarget {
+ pub fn tool_id(&self) -> &ToolId {
+ match self {
+ Self::Registered(id)
+ | Self::Mcp {
+ server_tool_id: id, ..
+ } => id,
+ }
+ }
+}
+
+impl From for ResolvedToolTarget {
+ fn from(id: ToolId) -> Self {
+ Self::Registered(id)
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ObservedToolCall {
pub call_id: ToolCallId,
- /// Admitted registry identity resolved by the response adapter. Absent for
- /// an unadvertised name. The original name remains transcript data below.
- pub tool_id: Option,
+ /// Absent for an unadvertised name. The name itself remains transcript data.
+ #[serde(default, alias = "tool_id", skip_serializing_if = "Option::is_none")]
+ pub target: Option,
pub tool_name: ToolName,
pub provider_kind: Option,
pub arguments_ref: BlobRef,
pub native_call_ref: Option,
}
+impl ObservedToolCall {
+ pub fn tool_id(&self) -> Option<&ToolId> {
+ self.target.as_ref().map(ResolvedToolTarget::tool_id)
+ }
+}
+
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct ActiveToolBatch {
pub batch_id: ToolBatchId,
@@ -1235,11 +1268,10 @@ fn initial_tool_call_state(
turn_id: TurnId,
call: &ObservedToolCall,
) -> ToolCallState {
- let invokes_client_effect = call
- .tool_id
- .as_ref()
- .and_then(|tool_id| planned_tool_for_turn(state, turn_id, tool_id))
- .is_some_and(|tool| tool.invokes_client_effect());
+ let invokes_client_effect = call.target.as_ref().is_some_and(|target| {
+ planned_tool_for_turn(state, turn_id, target.tool_id())
+ .is_some_and(|tool| tool.admits_call(target))
+ });
if invokes_client_effect {
ToolCallState {
call: call.clone(),
@@ -1260,7 +1292,8 @@ pub fn remote_mcp_call_runtime(
batch_id: ToolBatchId,
call: &ObservedToolCall,
) -> Option {
- let tool_id = call.tool_id.as_ref()?;
+ let target = call.target.as_ref()?;
+ let tool_id = target.tool_id();
let call_id = &call.call_id;
let approval_decision = state
.runs
@@ -1286,12 +1319,17 @@ pub fn remote_mcp_call_runtime(
})
.flatten();
- if let Some((spec, remote_tool_name)) =
- resolve_injected_runtime_mcp(state, tool_id, &call.tool_name)
- {
+ if let ResolvedToolTarget::Mcp { remote_name, .. } = target {
+ let tool = state.tooling.tools.get(tool_id)?;
+ let ToolKind::RemoteMcp(spec) = &tool.kind else {
+ return None;
+ };
+ if !tool.admits_call(target) {
+ return None;
+ }
return Some(crate::RemoteMcpCallRuntime::Injected {
target: remote_mcp_target(spec),
- remote_tool_name,
+ remote_tool_name: remote_name.clone(),
approval_decision,
});
}
@@ -1321,32 +1359,6 @@ pub fn remote_mcp_call_runtime(
})
}
-fn resolve_injected_runtime_mcp<'a>(
- state: &'a CoreAgentState,
- tool_id: &ToolId,
- exposed_name: &ToolName,
-) -> Option<(&'a RemoteMcpToolSpec, String)> {
- let tool = state.tooling.tools.get(tool_id)?;
- let ToolKind::RemoteMcp(spec) = &tool.kind else {
- return None;
- };
- if spec.execution != RemoteMcpExecution::Runtime || spec.exposure != RemoteMcpExposure::Inject {
- return None;
- }
- let prefix = format!("{tool_id}__");
- let remote_name = exposed_name.as_str().strip_prefix(&prefix)?;
- if remote_name.is_empty()
- || spec
- .allowed_tools
- .as_ref()
- .is_some_and(|allowed| !allowed.iter().any(|name| name == remote_name))
- {
- return None;
- }
- validate_remote_mcp_allowed_tool_name(remote_name).ok()?;
- Some((spec, remote_name.to_owned()))
-}
-
fn remote_mcp_target(spec: &RemoteMcpToolSpec) -> crate::RemoteMcpCallTarget {
crate::RemoteMcpCallTarget {
server_id: spec.server_id.clone(),
@@ -2165,7 +2177,7 @@ mod tests {
fn unavailable_tool_results_reference_the_well_known_constant_blob() {
let call = ObservedToolCall {
call_id: crate::ToolCallId::new("call_1"),
- tool_id: Some(ToolId::new("missing_tool")),
+ target: Some(ToolId::new("missing_tool").into()),
tool_name: ToolName::new("missing_tool"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(b"{}"),
diff --git a/crates/harness/src/core/components/workflow_tool.rs b/crates/harness/src/core/components/workflow_tool.rs
index 49c557720..9156468cf 100644
--- a/crates/harness/src/core/components/workflow_tool.rs
+++ b/crates/harness/src/core/components/workflow_tool.rs
@@ -1328,7 +1328,7 @@ pub(crate) fn validate_invoke_effect(
"workflow tool invoke effect references missing tool call {expected_call_id}"
))
})?;
- if call.call.tool_id.as_ref() != Some(&binding.definition.tool.id)
+ if call.call.tool_id() != Some(&binding.definition.tool.id)
|| call.call.arguments_ref != invocation.arguments_ref
{
return Err(DomainError::InvariantViolation(
@@ -1590,7 +1590,7 @@ fn validate_recorded_invocation(
invocation.tool_call_id
))
})?;
- if call.call.tool_id.as_ref() != Some(&binding.definition.tool.id)
+ if call.call.tool_id() != Some(&binding.definition.tool.id)
|| call.call.arguments_ref != invocation.arguments_ref
{
return Err(DomainError::InvariantViolation(
@@ -2789,7 +2789,7 @@ mod tests {
.iter()
.map(|call_id| ObservedToolCall {
call_id: ToolCallId::new(*call_id),
- tool_id: Some(definition.tool.id.clone()),
+ target: Some(definition.tool.id.clone().into()),
tool_name: ToolName::new("work_report"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(call_id.as_bytes()),
diff --git a/crates/harness/src/core/drive.rs b/crates/harness/src/core/drive.rs
index 628962422..6afe66f2e 100644
--- a/crates/harness/src/core/drive.rs
+++ b/crates/harness/src/core/drive.rs
@@ -958,8 +958,7 @@ pub(crate) fn tool_invocation_request(
.iter()
.map(|call| {
let workflow_tool = call
- .tool_id
- .as_ref()
+ .tool_id()
.and_then(|id| state.workflow_tools.binding_for_tool_id(id))
.map(|binding| {
crate::WorkflowToolCallRuntime::v1(
@@ -976,8 +975,7 @@ pub(crate) fn tool_invocation_request(
let remote_mcp = crate::remote_mcp_call_runtime(state, batch_id, call);
ToolInvocationRequest {
builtin: call
- .tool_id
- .as_ref()
+ .tool_id()
.and_then(|id| state.tooling.tools.get(id))
.and_then(|tool| match &tool.kind {
crate::ToolKind::Builtin(spec) => Some(crate::BuiltinToolCallRuntime {
@@ -998,7 +996,7 @@ pub(crate) fn tool_invocation_request(
_ => None,
}),
call_id: call.call_id.clone(),
- tool_id: call.tool_id.clone(),
+ tool_id: call.tool_id().cloned(),
tool_name: call.tool_name.clone(),
arguments_ref: call.arguments_ref.clone(),
workflow_tool,
@@ -1190,8 +1188,7 @@ pub fn tool_batch_parked_proposals(
call_state.status == ToolCallStatus::Pending
&& call_state
.call
- .tool_id
- .as_ref()
+ .tool_id()
.is_some_and(|id| id.as_str() == AWAIT_TOOL_ID)
})
.map(|call_state| call_state.call.call_id.clone())
@@ -1280,8 +1277,7 @@ pub fn tool_batch_parked_proposals(
call_state.call.call_id == call_id
&& call_state
.call
- .tool_id
- .as_ref()
+ .tool_id()
.is_some_and(|id| id.as_str() == AWAIT_TOOL_ID)
}) {
return Err(DomainError::InvariantViolation(format!(
@@ -2755,7 +2751,7 @@ mod tests {
) -> ToolInvocationBatchRequest {
let tool_call = ObservedToolCall {
call_id: crate::ToolCallId::new("call_wait"),
- tool_id: Some(test_tool_id(tool_name)),
+ target: Some(test_tool_id(tool_name).into()),
tool_name: ToolName::new(tool_name),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(br#"{"wait":true}"#),
@@ -4938,7 +4934,7 @@ mod tests {
request,
vec![ObservedToolCall {
call_id: crate::ToolCallId::new("read-skill"),
- tool_id: Some(ToolId::new("vfs.read_file")),
+ target: Some(ToolId::new("vfs.read_file").into()),
tool_name: ToolName::new("vfs_read_file"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(br#"{"path":"/skills/review/SKILL.md"}"#),
@@ -6658,7 +6654,7 @@ mod tests {
usage: None,
tool_calls: vec![ObservedToolCall {
call_id: crate::ToolCallId::new("call_wait"),
- tool_id: Some(ToolId::new("concurrency.await")),
+ target: Some(ToolId::new("concurrency.await").into()),
tool_name: ToolName::new("await"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(br#"{"wait":true}"#),
@@ -6867,7 +6863,7 @@ mod tests {
usage: None,
tool_calls: vec![ObservedToolCall {
call_id: crate::ToolCallId::new("call_a"),
- tool_id: Some(ToolId::new("fn_a")),
+ target: Some(ToolId::new("fn_a").into()),
tool_name: ToolName::new("fn_a"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(b"{}"),
@@ -6938,7 +6934,7 @@ mod tests {
usage: None,
tool_calls: vec![ObservedToolCall {
call_id: crate::ToolCallId::new(format!("call_{}", request.turn_id)),
- tool_id: Some(ToolId::new("fn_a")),
+ target: Some(ToolId::new("fn_a").into()),
tool_name: ToolName::new("fn_a"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(b"{}"),
@@ -9710,7 +9706,7 @@ mod tests {
let observed_calls = vec![
ObservedToolCall {
call_id: ToolCallId::new("call-send-1"),
- tool_id: Some(ToolId::new("message_send")),
+ target: Some(ToolId::new("message_send").into()),
tool_name: ToolName::new("message_send"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(br#"{"text":"one"}"#),
@@ -9718,7 +9714,7 @@ mod tests {
},
ObservedToolCall {
call_id: ToolCallId::new("call-echo"),
- tool_id: Some(ToolId::new("local_echo")),
+ target: Some(ToolId::new("local_echo").into()),
tool_name: ToolName::new("local_echo"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(br#"{"text":"echo"}"#),
@@ -9726,7 +9722,7 @@ mod tests {
},
ObservedToolCall {
call_id: ToolCallId::new("call-send-2"),
- tool_id: Some(ToolId::new("message_send")),
+ target: Some(ToolId::new("message_send").into()),
tool_name: ToolName::new("message_send"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(br#"{"text":"two"}"#),
@@ -9952,7 +9948,7 @@ mod tests {
vec![
ObservedToolCall {
call_id: ToolCallId::new("call-send"),
- tool_id: Some(ToolId::new("message_send")),
+ target: Some(ToolId::new("message_send").into()),
tool_name: ToolName::new("message_send"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(br#"{"text":"one"}"#),
@@ -9960,7 +9956,7 @@ mod tests {
},
ObservedToolCall {
call_id: ToolCallId::new("call-await"),
- tool_id: Some(ToolId::new(AWAIT_TOOL_ID)),
+ target: Some(ToolId::new(AWAIT_TOOL_ID).into()),
tool_name: ToolName::new("await"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(br#"{"promises":["other"]}"#),
@@ -10921,7 +10917,7 @@ mod tests {
let run_id = generation.run_id;
let observed = |tool: &str| ObservedToolCall {
call_id: crate::ToolCallId::new(format!("call_{tool}")),
- tool_id: Some(test_tool_id(tool)),
+ target: Some(test_tool_id(tool).into()),
tool_name: ToolName::new(tool),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(tool.as_bytes()),
@@ -11322,7 +11318,7 @@ mod tests {
vec![
ObservedToolCall {
call_id: crate::ToolCallId::new("call_a"),
- tool_id: Some(ToolId::new("tool_a")),
+ target: Some(ToolId::new("tool_a").into()),
tool_name: ToolName::new("tool_a"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(br#"{"a":true}"#),
@@ -11330,7 +11326,7 @@ mod tests {
},
ObservedToolCall {
call_id: crate::ToolCallId::new("call_b"),
- tool_id: Some(ToolId::new("tool_b")),
+ target: Some(ToolId::new("tool_b").into()),
tool_name: ToolName::new("tool_b"),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(br#"{"b":true}"#),
@@ -11586,9 +11582,19 @@ mod tests {
}
fn observed_call(call_id: &str, tool_name: &str) -> ObservedToolCall {
+ let tool_id = test_tool_id(tool_name);
+ let target = if tool_name == "mcp_echo__hello" {
+ crate::ResolvedToolTarget::Mcp {
+ server_tool_id: tool_id,
+ server_label: "echo".into(),
+ remote_name: "hello".into(),
+ }
+ } else {
+ tool_id.into()
+ };
ObservedToolCall {
call_id: crate::ToolCallId::new(call_id),
- tool_id: Some(test_tool_id(tool_name)),
+ target: Some(target),
tool_name: ToolName::new(tool_name),
provider_kind: None,
arguments_ref: BlobRef::from_bytes(b"{}"),
@@ -11887,7 +11893,7 @@ mod tests {
);
let call = ObservedToolCall {
call_id: crate::ToolCallId::new("call-bash"),
- tool_id: Some(ToolId::new("env.run_process")),
+ target: Some(ToolId::new("env.run_process").into()),
tool_name: ToolName::new("Bash"),
provider_kind: Some("tool_use".into()),
arguments_ref: BlobRef::from_bytes(br#"{"command":"echo hello"}"#),
@@ -11896,7 +11902,7 @@ mod tests {
let mut unknown = call.clone();
unknown.call_id = crate::ToolCallId::new("unknown-alias");
unknown.tool_name = ToolName::new("exec_command");
- unknown.tool_id = None;
+ unknown.target = None;
let action = drive
.resume_generation(
LlmGenerationResult {
@@ -11942,7 +11948,7 @@ mod tests {
}
};
assert_eq!(request.calls.len(), 1, "unknown aliases do not execute");
- assert_eq!(request.calls[0].tool_id, call.tool_id);
+ assert_eq!(request.calls[0].tool_id.as_ref(), call.tool_id());
assert_eq!(request.calls[0].tool_name.as_str(), "Bash");
assert_eq!(
request.calls[0].builtin,
@@ -12053,6 +12059,10 @@ mod tests {
]
.into_iter()
.map(test_tool_spec)
+ .chain([runtime_inject_mcp_tool(
+ "mcp_echo",
+ crate::RemoteMcpApprovalPolicy::Never,
+ )])
.map(|tool| (tool.id.clone(), tool))
.collect();
let action = drive
@@ -12137,7 +12147,7 @@ mod tests {
(
name.to_owned(),
crate::CodeToolBinding {
- tool_id: test_tool_id(name),
+ target: test_tool_id(name).into(),
tool_name: ToolName::new(name),
},
)
@@ -12169,6 +12179,34 @@ mod tests {
commit_action(drive, action)
}
+ #[test]
+ fn code_tool_uses_the_remote_identity_from_its_pinned_scope() {
+ let (mut drive, parent) = code_tool_fixture();
+ let mut scope = code_tool_scope(parent);
+ let mut call = code_tool_spec("1", "local_echo");
+ call.tool_id = ToolId::new("mcp_echo");
+ call.tool_name = ToolName::new("shortened_alias");
+ scope.bindings.insert(
+ call.binding_id.clone(),
+ crate::CodeToolBinding {
+ tool_name: call.tool_name.clone(),
+ target: crate::ResolvedToolTarget::Mcp {
+ server_tool_id: call.tool_id.clone(),
+ server_label: "echo".into(),
+ remote_name: "hello".into(),
+ },
+ },
+ );
+ code_tool_commit(&mut drive, CoreAgentCommand::OpenCodeToolScope { scope });
+ code_tool_commit(&mut drive, CoreAgentCommand::AdmitCodeToolCall { call });
+ let request =
+ crate::code_tool_request(drive.session_id(), drive.state(), "execution-1", "1")
+ .unwrap();
+ assert!(
+ matches!(&request.calls[0].remote_mcp, Some(crate::RemoteMcpCallRuntime::Injected {remote_tool_name, ..}) if remote_tool_name == "hello")
+ );
+ }
+
#[test]
fn code_tool_parallel_calls_reserve_promises_deduplicate_and_replay_without_touching_outer_batch()
{
@@ -12725,7 +12763,7 @@ mod tests {
recursive.bindings.insert(
"code_execute".into(),
crate::CodeToolBinding {
- tool_id: ToolId::new("code_execute"),
+ target: ToolId::new("code_execute").into(),
tool_name: ToolName::new("code_execute"),
},
);
diff --git a/crates/harness/src/core/state_shape.rs b/crates/harness/src/core/state_shape.rs
index 455ce40a3..30c31cff0 100644
--- a/crates/harness/src/core/state_shape.rs
+++ b/crates/harness/src/core/state_shape.rs
@@ -206,8 +206,12 @@ fn notify() -> RunTerminalNotifyIntent {
fn observed_call(id: &str) -> ObservedToolCall {
ObservedToolCall {
call_id: ToolCallId::new(id),
- tool_id: Some(ToolId::new("read_file")),
- tool_name: ToolName::new("read_file"),
+ target: Some(ResolvedToolTarget::Mcp {
+ server_tool_id: ToolId::new("mcp_server"),
+ server_label: "Server".into(),
+ remote_name: "search".into(),
+ }),
+ tool_name: ToolName::new("mcp_server__search"),
provider_kind: Some("openai.responses.function_call".to_owned()),
arguments_ref: blob("arguments"),
native_call_ref: Some(blob("native call")),
@@ -665,7 +669,7 @@ fn tooling_state() -> ToolingState {
description_ref: Some(blob("server description")),
allowed_tools: Some(vec!["search".to_owned()]),
execution: RemoteMcpExecution::Runtime,
- exposure: RemoteMcpExposure::Search,
+ exposure: RemoteMcpExposure::Inject,
approval: RemoteMcpApprovalPolicy::Always,
defer_loading: Some(true),
}),
@@ -859,8 +863,8 @@ fn code_call(request_id: &str, status: CodeToolCallStatus) -> (String, CodeToolC
request_id: request_id.to_owned(),
},
binding_id: "read".to_owned(),
- tool_id: ToolId::new("read_file"),
- tool_name: ToolName::new("read_file"),
+ tool_id: ToolId::new("mcp_server"),
+ tool_name: ToolName::new("mcp_server__search"),
arguments_ref: blob("code arguments"),
},
call_id: ToolCallId::new(format!("code_{request_id}")),
@@ -913,8 +917,12 @@ fn code_tool_state() -> CodeToolState {
bindings: BTreeMap::from([(
"read".to_owned(),
CodeToolBinding {
- tool_id: ToolId::new("read_file"),
- tool_name: ToolName::new("read_file"),
+ target: ResolvedToolTarget::Mcp {
+ server_tool_id: ToolId::new("mcp_server"),
+ server_label: "Server".into(),
+ remote_name: "search".into(),
+ },
+ tool_name: ToolName::new("mcp_server__search"),
},
)]),
max_calls: 10,
diff --git a/crates/harness/tests/fixtures/checkpoint_state.json b/crates/harness/tests/fixtures/checkpoint_state.json
index efb7a08e7..3f261b849 100644
--- a/crates/harness/tests/fixtures/checkpoint_state.json
+++ b/crates/harness/tests/fixtures/checkpoint_state.json
@@ -15,8 +15,8 @@
"execution_id": "execution",
"request_id": "completed"
},
- "tool_id": "read_file",
- "tool_name": "read_file"
+ "tool_id": "mcp_server",
+ "tool_name": "mcp_server__search"
},
"status": {
"kind": "completed",
@@ -67,8 +67,8 @@
"execution_id": "execution",
"request_id": "pending"
},
- "tool_id": "read_file",
- "tool_name": "read_file"
+ "tool_id": "mcp_server",
+ "tool_name": "mcp_server__search"
},
"status": {
"kind": "pending"
@@ -84,8 +84,8 @@
"execution_id": "execution",
"request_id": "waiting"
},
- "tool_id": "read_file",
- "tool_name": "read_file"
+ "tool_id": "mcp_server",
+ "tool_name": "mcp_server__search"
},
"status": {
"kind": "waiting",
@@ -113,8 +113,14 @@
"spec": {
"bindings": {
"read": {
- "tool_id": "read_file",
- "tool_name": "read_file"
+ "target": {
+ "mcp": {
+ "remote_name": "search",
+ "server_label": "Server",
+ "server_tool_id": "mcp_server"
+ }
+ },
+ "tool_name": "mcp_server__search"
}
},
"execution_id": "execution",
@@ -868,8 +874,14 @@
"call_id": "call_pending",
"native_call_ref": "sha256:6224eea874e5e831a0e1d5d06fb97fc2c3849241073ff98d2503f8d5627aa825",
"provider_kind": "openai.responses.function_call",
- "tool_id": "read_file",
- "tool_name": "read_file"
+ "target": {
+ "mcp": {
+ "remote_name": "search",
+ "server_label": "Server",
+ "server_tool_id": "mcp_server"
+ }
+ },
+ "tool_name": "mcp_server__search"
},
"result": {
"attachments": [
@@ -978,8 +990,14 @@
"call_id": "call_observed",
"native_call_ref": "sha256:6224eea874e5e831a0e1d5d06fb97fc2c3849241073ff98d2503f8d5627aa825",
"provider_kind": "openai.responses.function_call",
- "tool_id": "read_file",
- "tool_name": "read_file"
+ "target": {
+ "mcp": {
+ "remote_name": "search",
+ "server_label": "Server",
+ "server_tool_id": "mcp_server"
+ }
+ },
+ "tool_name": "mcp_server__search"
}
],
"usage": {
@@ -1042,8 +1060,14 @@
"call_id": "call_observed",
"native_call_ref": "sha256:6224eea874e5e831a0e1d5d06fb97fc2c3849241073ff98d2503f8d5627aa825",
"provider_kind": "openai.responses.function_call",
- "tool_id": "read_file",
- "tool_name": "read_file"
+ "target": {
+ "mcp": {
+ "remote_name": "search",
+ "server_label": "Server",
+ "server_tool_id": "mcp_server"
+ }
+ },
+ "tool_name": "mcp_server__search"
}
],
"usage": {
@@ -1098,8 +1122,14 @@
"call_id": "call_observed",
"native_call_ref": "sha256:6224eea874e5e831a0e1d5d06fb97fc2c3849241073ff98d2503f8d5627aa825",
"provider_kind": "openai.responses.function_call",
- "tool_id": "read_file",
- "tool_name": "read_file"
+ "target": {
+ "mcp": {
+ "remote_name": "search",
+ "server_label": "Server",
+ "server_tool_id": "mcp_server"
+ }
+ },
+ "tool_name": "mcp_server__search"
}
],
"usage": {
@@ -1158,8 +1188,14 @@
"call_id": "call_observed",
"native_call_ref": "sha256:6224eea874e5e831a0e1d5d06fb97fc2c3849241073ff98d2503f8d5627aa825",
"provider_kind": "openai.responses.function_call",
- "tool_id": "read_file",
- "tool_name": "read_file"
+ "target": {
+ "mcp": {
+ "remote_name": "search",
+ "server_label": "Server",
+ "server_tool_id": "mcp_server"
+ }
+ },
+ "tool_name": "mcp_server__search"
}
],
"usage": {
@@ -1214,8 +1250,14 @@
"call_id": "call_observed",
"native_call_ref": "sha256:6224eea874e5e831a0e1d5d06fb97fc2c3849241073ff98d2503f8d5627aa825",
"provider_kind": "openai.responses.function_call",
- "tool_id": "read_file",
- "tool_name": "read_file"
+ "target": {
+ "mcp": {
+ "remote_name": "search",
+ "server_label": "Server",
+ "server_tool_id": "mcp_server"
+ }
+ },
+ "tool_name": "mcp_server__search"
}
],
"usage": {
@@ -1274,8 +1316,14 @@
"call_id": "call_observed",
"native_call_ref": "sha256:6224eea874e5e831a0e1d5d06fb97fc2c3849241073ff98d2503f8d5627aa825",
"provider_kind": "openai.responses.function_call",
- "tool_id": "read_file",
- "tool_name": "read_file"
+ "target": {
+ "mcp": {
+ "remote_name": "search",
+ "server_label": "Server",
+ "server_tool_id": "mcp_server"
+ }
+ },
+ "tool_name": "mcp_server__search"
}
],
"usage": {
@@ -1334,8 +1382,14 @@
"call_id": "call_observed",
"native_call_ref": "sha256:6224eea874e5e831a0e1d5d06fb97fc2c3849241073ff98d2503f8d5627aa825",
"provider_kind": "openai.responses.function_call",
- "tool_id": "read_file",
- "tool_name": "read_file"
+ "target": {
+ "mcp": {
+ "remote_name": "search",
+ "server_label": "Server",
+ "server_tool_id": "mcp_server"
+ }
+ },
+ "tool_name": "mcp_server__search"
}
],
"usage": {
@@ -1508,7 +1562,7 @@
"defer_loading": true,
"description_ref": "sha256:ed969f4dee41b8e5e02d2c6b61999776a7bb6aeeefb501ab70a355859b16d6c6",
"execution": "runtime",
- "exposure": "search",
+ "exposure": "inject",
"record_revision": 4,
"server_id": "server",
"server_label": "Server"
diff --git a/crates/harness/tests/state_bounds.rs b/crates/harness/tests/state_bounds.rs
index 1ca1b6324..c88742d30 100644
--- a/crates/harness/tests/state_bounds.rs
+++ b/crates/harness/tests/state_bounds.rs
@@ -305,7 +305,7 @@ fn call_of(request: &LlmGenerationRequest, tool: &str) -> ObservedToolCall {
let call = format!("call_{:020}", request.turn_id.as_u64());
ObservedToolCall {
call_id: ToolCallId::new(&call),
- tool_id: Some(ToolId::new(tool)),
+ target: Some(ToolId::new(tool).into()),
tool_name: ToolName::new(tool),
provider_kind: Some("openai.responses.function_call".to_owned()),
arguments_ref: blob(format!("args-{call}")),
@@ -895,7 +895,7 @@ impl Session {
bindings: BTreeMap::from([(
"read_file".to_owned(),
CodeToolBinding {
- tool_id: ToolId::new("read_file"),
+ target: ToolId::new("read_file").into(),
tool_name: ToolName::new("read_file"),
},
)]),
diff --git a/crates/llm-runtime/Cargo.toml b/crates/llm-runtime/Cargo.toml
index 4fb2b39f2..978503c51 100644
--- a/crates/llm-runtime/Cargo.toml
+++ b/crates/llm-runtime/Cargo.toml
@@ -7,10 +7,12 @@ edition = "2024"
async-trait = "0.1"
base64 = "0.23"
harness = { path = "../harness" }
+hex = "0.4"
image = { version = "0.25", default-features = false, features = ["gif", "jpeg", "png", "webp"] }
llm-clients = { path = "../llm-clients" }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
+sha2 = "0.11"
thiserror = "2"
tokio = { version = "1", features = ["rt"] }
tracing = "0.1"
diff --git a/crates/llm-runtime/src/anthropic_messages.rs b/crates/llm-runtime/src/anthropic_messages.rs
index d5b27f87a..d067ea83c 100644
--- a/crates/llm-runtime/src/anthropic_messages.rs
+++ b/crates/llm-runtime/src/anthropic_messages.rs
@@ -18,7 +18,7 @@ use harness::{
LlmGenerationRequest, LlmGenerationResult, LlmGenerationStatus, LlmRequest, LlmUsage,
ObservedToolCall, ProviderApiKind, ProviderNativeToolExecution, RemoteMcpApprovalPolicy,
RemoteMcpExecution, RemoteMcpExposure, RemoteMcpToolSpec, TokenEstimate, TokenEstimateQuality,
- ToolCallId, ToolId, ToolKind, ToolName, ToolSpec, storage::BlobStore,
+ ToolCallId, ToolKind, ToolName, ToolSpec, storage::BlobStore,
};
use llm_clients::content::{
ANTHROPIC_MESSAGES_MCP_TOOL_RESULT_PROVIDER_KIND,
@@ -225,25 +225,33 @@ impl LlmGenerationAdapter for AnthropicMessagesLlmAdapter {
});
}
+ let mcp = crate::mcp::RequestMcp::new(self.inventory.as_ref(), Some(self.secrets.as_ref()));
let mut catalog = crate::tool_catalog::ToolCatalog::resolve_for_request(
self.blobs.as_ref(),
&request.request,
)
.await?;
- let provider_request = materialize_request_with_catalog(
+ let mut provider_request = materialize_request_with_catalog(
self.blobs.as_ref(),
- self.inventory.as_ref(),
+ &mcp,
&request.request,
&mut catalog,
self.thinking_prefix_mismatch,
)
.await?;
- let (mut send_request, mut redacted_request) = inject_remote_mcp_auth(
- self.secrets.as_ref(),
- &request.request.tools,
- provider_request,
- )
- .await?;
+ let notice = mcp
+ .notice(self.blobs.as_ref(), &request.request.context)
+ .await?;
+ if let Some((text, _)) = ¬ice {
+ push_block(
+ &mut provider_request.messages,
+ am::MessageRole::User,
+ am::ContentBlockParam::text(text),
+ )?;
+ }
+
+ let (mut send_request, mut redacted_request) =
+ inject_remote_mcp_auth(&mcp, &request.request.tools, provider_request)?;
let provider =
resolve_model_provider(self.provider_keys.as_ref(), &request.request.model).await?;
let mut request_dumps = Vec::new();
@@ -306,6 +314,9 @@ impl LlmGenerationAdapter for AnthropicMessagesLlmAdapter {
fail_on_invalid_response(parsed, self.blobs.as_ref(), &request, response_id, usage)
.await?;
catalog.normalize(&mut result);
+ if let Some((_, entry)) = notice {
+ result.context_entries.insert(0, entry);
+ }
let request_dump = match request_dumps.len() {
0 => None,
1 => request_dumps.pop(),
@@ -395,15 +406,16 @@ impl LlmCompactionAdapter for AnthropicMessagesLlmAdapter {
),
});
}
- let provider_request = self.materialize_compact_request(&request.request).await?;
+ let mcp = crate::mcp::RequestMcp::new(self.inventory.as_ref(), Some(self.secrets.as_ref()));
+ let provider_request = materialize_compact_request_with_binding(
+ self.blobs.as_ref(),
+ &mcp,
+ &request.request,
+ self.thinking_prefix_mismatch,
+ )
+ .await?;
let provider_request = if supports_native_compaction(&request.request.model.model) {
- inject_remote_mcp_auth(
- self.secrets.as_ref(),
- &request.request.tools,
- provider_request,
- )
- .await?
- .0
+ inject_remote_mcp_auth(&mcp, &request.request.tools, provider_request)?.0
} else {
provider_request
};
@@ -1163,9 +1175,10 @@ async fn materialize_tools(
)
.await?;
for (name, runtime_tool) in runtime_tools {
- catalog
- .names
- .insert(ToolName::new(name.clone()), Some(tool.id.clone()))?;
+ catalog.names.insert(
+ ToolName::new(name.clone()),
+ Some(runtime_tool.target(&tool.id, remote_mcp)),
+ )?;
let description =
catalog.runtime_mcp_description(&tool.id, &name, &runtime_tool);
materialized.push(am::Tool::Custom(am::ToolDefinition {
@@ -1280,8 +1293,8 @@ fn anthropic_tool_search_model_support(model: &str) -> Option {
/// `authorization_token` resolved at the last moment, and the redacted request
/// that is persisted to blobs, preserving only the fact that auth was
/// configured.
-async fn inject_remote_mcp_auth(
- secrets: &dyn SecretResolver,
+fn inject_remote_mcp_auth(
+ mcp: &crate::mcp::RequestMcp,
tools: &[ToolSpec],
materialized: am::CreateMessageRequest,
) -> LlmAdapterResult<(am::CreateMessageRequest, am::CreateMessageRequest)> {
@@ -1309,12 +1322,7 @@ async fn inject_remote_mcp_auth(
else {
continue;
};
- let token = crate::secrets::resolve_mcp_bearer(secrets, &remote_mcp.server_id, &server_url)
- .await
- .map_err(|error| LlmAdapterError::SecretResolution {
- tool: tool.id.to_string(),
- message: error.to_string(),
- })?;
+ let token = mcp.token(remote_mcp.server_id.clone(), server_url)?;
let Some(token) = token else {
continue;
};
@@ -1892,7 +1900,7 @@ async fn tool_use_context(
};
let tool_call = ObservedToolCall {
call_id,
- tool_id: Some(ToolId::new(tool_name.as_str())),
+ target: None,
tool_name,
provider_kind: Some(PROVIDER_KIND_TOOL_USE.to_owned()),
arguments_ref,
@@ -2096,7 +2104,7 @@ async fn has_signed_compaction(
#[cfg(test)]
mod tests {
- use harness::ToolChoice;
+ use harness::{ToolChoice, ToolId};
use std::collections::{BTreeMap, VecDeque};
use std::sync::{Arc, Mutex};
@@ -3563,37 +3571,48 @@ mod tests {
}
#[tokio::test(flavor = "current_thread")]
- async fn generate_does_not_treat_a_missing_credential_resource_as_absent() {
- let blobs = Arc::new(InMemoryBlobStore::new());
- let api = fake_api(completed_text_response_json());
- let adapter = AnthropicMessagesLlmAdapter::new(api.clone(), blobs)
- .with_secret_resolver(Arc::new(crate::secrets::StaticSecretResolver::new()))
- .with_mcp_inventory_resolver(Arc::new(StaticMcpInventory));
-
- let error = LlmGenerationAdapter::generate(&adapter, mcp_auth_generation_request())
- .await
- .expect_err("missing optional MCP server must not silently downgrade");
-
- assert!(matches!(error, LlmAdapterError::SecretResolution { .. }));
- assert!(api.seen.lock().expect("lock").is_empty());
- }
-
- #[tokio::test(flavor = "current_thread")]
- async fn generate_fails_before_provider_io_when_the_credential_cannot_be_resolved() {
+ async fn a_broken_credential_omits_only_its_server_and_reports_the_cause() {
let blobs = Arc::new(InMemoryBlobStore::new());
let api = fake_api(completed_text_response_json());
let adapter = AnthropicMessagesLlmAdapter::new(api.clone(), blobs.clone())
+ .with_secret_resolver(Arc::new(crate::StaticSecretResolver::new().with_secret(
+ crate::SECRET_NAMESPACE_MCP_SERVER,
+ "healthy",
+ "healthy-token",
+ )))
.with_mcp_inventory_resolver(Arc::new(StaticMcpInventory));
-
- let error = LlmGenerationAdapter::generate(&adapter, mcp_auth_generation_request())
- .await
- .expect_err("an unresolvable credential must fail generation");
-
- assert!(matches!(error, LlmAdapterError::SecretResolution { .. }));
+ let mut request = mcp_auth_generation_request();
+ let mut other = request.request.tools[0].clone();
+ other.id = ToolId::try_new("mcp_healthy").unwrap();
+ let ToolKind::RemoteMcp(spec) = &mut other.kind else {
+ unreachable!()
+ };
+ spec.server_label = "healthy".into();
+ spec.server_id = "healthy".into();
+ request.request.tools.push(other);
+ let execution = adapter.generate(request).await.unwrap();
+ let wire = serde_json::to_value(&api.seen.lock().unwrap()[0]).unwrap();
+ assert_eq!(wire["mcp_servers"].as_array().unwrap().len(), 1);
+ assert_eq!(wire["mcp_servers"][0]["name"], "healthy");
+ assert_eq!(
+ wire["mcp_servers"][0]["authorization_token"],
+ "healthy-token"
+ );
assert!(
- api.seen.lock().expect("lock").is_empty(),
- "no provider call may happen when auth resolution fails"
+ !wire["tools"]
+ .to_string()
+ .contains(r#""mcp_server_name":"echo""#)
);
+ let entry = &execution.result.context_entries[0];
+ assert!(
+ matches!(&entry.kind, ContextEntryKind::Catalog {title} if title == "Unavailable MCP servers")
+ );
+ let body = crate::blob_io::read_text(blobs.as_ref(), &entry.content.content_ref)
+ .await
+ .unwrap();
+ assert!(body.contains("credential was not found"));
+ assert!(wire.to_string().contains("credential was not found"));
+ assert!(!body.contains("healthy-token"));
}
fn generation_request() -> LlmGenerationRequest {
@@ -3880,7 +3899,7 @@ mod tests {
);
assert_eq!(result.facts.tool_calls.len(), 1);
assert_eq!(
- result.facts.tool_calls[0].tool_id,
+ result.facts.tool_calls[0].tool_id().cloned(),
Some(ToolId::new("env.read_file"))
);
assert_eq!(
diff --git a/crates/llm-runtime/src/lib.rs b/crates/llm-runtime/src/lib.rs
index b1e7288a6..26f5490e6 100644
--- a/crates/llm-runtime/src/lib.rs
+++ b/crates/llm-runtime/src/lib.rs
@@ -27,7 +27,10 @@ pub use anthropic_messages::{
};
pub use error::{LlmAdapterError, LlmAdapterResult};
pub use executor::{LlmAdapterRegistry, LlmCompactionAdapter, LlmGenerationAdapter, LlmRuntime};
-pub use mcp::{McpInventoryError, McpInventoryResolver, RuntimeMcpTool, injected_runtime_tools};
+pub use mcp::{
+ McpInventoryError, McpInventoryResolver, RuntimeMcpTool, injected_runtime_tools,
+ injected_tool_name,
+};
pub use openai_completions::{OpenAiCompletionsApi, OpenAiCompletionsLlmAdapter};
pub use openai_responses::{OpenAiResponsesApi, OpenAiResponsesLlmAdapter};
pub use params::{
diff --git a/crates/llm-runtime/src/mcp.rs b/crates/llm-runtime/src/mcp.rs
index ab1026d86..672c1aaa7 100644
--- a/crates/llm-runtime/src/mcp.rs
+++ b/crates/llm-runtime/src/mcp.rs
@@ -1,5 +1,7 @@
+use std::{collections::BTreeMap, sync::Mutex};
+
use async_trait::async_trait;
-use harness::{RemoteMcpToolSpec, ToolName};
+use harness::{RemoteMcpToolSpec, ResolvedToolTarget, ToolId, ToolName};
use serde_json::Value;
use crate::{LlmAdapterError, LlmAdapterResult};
@@ -19,6 +21,17 @@ pub struct RuntimeMcpTool {
pub annotations: Option,
}
+impl RuntimeMcpTool {
+ /// Pin this inventory entry to the server registration that advertised it.
+ pub fn target(&self, server_tool_id: &ToolId, spec: &RemoteMcpToolSpec) -> ResolvedToolTarget {
+ ResolvedToolTarget::Mcp {
+ server_tool_id: server_tool_id.clone(),
+ server_label: spec.server_label.clone(),
+ remote_name: self.remote_name.clone(),
+ }
+ }
+}
+
#[derive(Clone, Debug, thiserror::Error)]
#[error("{message}")]
pub struct McpInventoryError {
@@ -52,11 +65,189 @@ pub trait McpInventoryResolver: Send + Sync {
spec: &RemoteMcpToolSpec,
) -> Result, McpInventoryError>;
+ /// The last usable tools and any failure observed refreshing them.
+ async fn list_tools_with_status(
+ &self,
+ spec: &RemoteMcpToolSpec,
+ ) -> Result {
+ Ok(McpListing {
+ tools: self.list_tools(spec).await?,
+ warning: None,
+ })
+ }
+
/// The URL a provider should connect to, or `None` when the server's record
/// is gone, switched off or no longer provider-hosted.
async fn server_url(&self, server_id: &str) -> Result
-