Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

MCP step 3: API agents run MCP tools in an OpenAI-compatible tool loop

Lin (kwant bot)074e93ba8536
diff --git a/docs/mcp-api.md b/docs/mcp-api.md
index 0a061eca..889d70e7 100644
--- a/docs/mcp-api.md
+++ b/docs/mcp-api.md
@@ -119,7 +119,11 @@ Every MCP tool call needs approval through the permission broker, for both agent
3. Unanswered tickets are denied after 300 s, or when the turn is cancelled.
API agents also emit `ToolCallPending {id, name, args}` before running a call and
-`ToolCallCompleted {id, result}` after it.
+`ToolCallCompleted {id, result: {status, content}}` after it (`content` cut to 4000 characters).
+A server that fails to start is skipped for that turn with a `ThinkingDelta` note; tools whose
+namespaced name is not a valid function name (`^[A-Za-z0-9_-]{1,64}$`) are not offered. When the
+model still asks for tools on its last allowed call, those calls are not run and the reply ends
+with a note about the limit.
### Recorded tool calls
diff --git a/src/drivers/api.rs b/src/drivers/api.rs
index dff2a9d9..5e8bfe04 100644
--- a/src/drivers/api.rs
+++ b/src/drivers/api.rs
@@ -1,7 +1,8 @@
use super::{events::RuntimeEvent, Driver, DriverError, TurnInput, TurnOutput};
use async_trait::async_trait;
use reqwest::Client;
-use serde_json::json;
+use crate::mcp::session::{Caller, McpToolSession};
+use serde_json::{json, Value};
use std::time::{Duration, Instant};
use tokio::sync::mpsc;
@@ -21,6 +22,16 @@ async fn api_model_name(target_model: &str, url: &str) -> String {
target_model.to_string()
}
+struct ChatRequest<'a> {
+ url: &'a str,
+ api_key: Option<&'a str>,
+ model: &'a str,
+ temperature: f64,
+ max_tokens: i64,
+ /// Model calls allowed this turn; each round of MCP tool calls costs one.
+ max_calls: usize,
+}
+
#[derive(Clone, Debug)]
pub struct ApiDriver {
client: Client,
@@ -68,6 +79,113 @@ impl ApiDriver {
}
}
+impl ApiDriver {
+ async fn post_chat(&self, request: &ChatRequest<'_>, body: &Value) -> Result<Value, String> {
+ let mut req = self.client.post(request.url).json(body);
+ if let Some(key) = request.api_key {
+ req = req.header("Authorization", format!("Bearer {}", key));
+ }
+ let resp = req.send().await.map_err(|e| format!("connection failed: {e}"))?;
+ if !resp.status().is_success() {
+ return Err(format!("API returned {}", resp.status()));
+ }
+ resp.json::<Value>().await.map_err(|e| format!("invalid response: {e}"))
+ }
+
+ /// Calls the model, running any MCP tool calls it asks for and calling it again with the
+ /// results, up to `max_calls` model calls. Returns the final text and tokens used, or
+ /// `None` when the very first call fails (the caller then falls back to the offline reply).
+ async fn chat_loop(
+ &self,
+ request: &ChatRequest<'_>,
+ mut messages: Vec<Value>,
+ session: Option<&McpToolSession>,
+ caller: &Caller,
+ event_tx: &mpsc::Sender<RuntimeEvent>,
+ ) -> Option<(String, usize)> {
+ let tools = session.map(|s| s.openai_tools()).unwrap_or_default();
+ let max_calls = request.max_calls.max(1);
+ let mut tokens = 0usize;
+ for round in 0..max_calls {
+ let mut body = json!({
+ "model": request.model,
+ "messages": messages,
+ "stream": false,
+ "temperature": request.temperature,
+ "max_tokens": request.max_tokens,
+ });
+ if !tools.is_empty() {
+ body["tools"] = json!(tools);
+ }
+ let reply = match self.post_chat(request, &body).await {
+ Ok(v) => v,
+ Err(e) if round == 0 => {
+ tracing::warn!(error = %e, "API call failed, using arcade emulation");
+ return None;
+ }
+ Err(e) => return Some((format!("⚠️ The model request failed after running tools: {e}"), tokens)),
+ };
+ tokens += reply["usage"]["total_tokens"].as_u64().unwrap_or(45) as usize;
+ let message = &reply["choices"][0]["message"];
+ let content = message["content"]
+ .as_str()
+ .or_else(|| reply["content"][0]["text"].as_str())
+ .map(str::to_string);
+ let calls = message["tool_calls"].as_array().filter(|c| !c.is_empty());
+
+ let (Some(calls), Some(session)) = (calls, session) else {
+ return Some((content.unwrap_or_else(|| "No response content".into()), tokens));
+ };
+ if round + 1 == max_calls {
+ let note = format!("(Stopped: reached the limit of {max_calls} model calls for MCP tools this turn.)");
+ let text = match content.filter(|c| !c.trim().is_empty()) {
+ Some(c) => format!("{c}\n\n{note}"),
+ None => note,
+ };
+ return Some((text, tokens));
+ }
+
+ if let Some(c) = content.as_deref().filter(|c| !c.trim().is_empty()) {
+ let _ = event_tx.send(RuntimeEvent::ThinkingDelta(c.to_string())).await;
+ }
+ let mut assistant = json!({"role": "assistant", "content": content.clone().unwrap_or_default(), "tool_calls": calls});
+ // Some servers return arguments as an object; the API format is a JSON string
+ for call in assistant["tool_calls"].as_array_mut().into_iter().flatten() {
+ if let Some(args) = call["function"].get("arguments").filter(|a| !a.is_string()).cloned() {
+ call["function"]["arguments"] = json!(args.to_string());
+ }
+ if call["id"].as_str().map_or(true, str::is_empty) {
+ call["id"] = json!(format!("call_{}", uuid::Uuid::new_v4().simple()));
+ }
+ }
+ let calls = assistant["tool_calls"].as_array().cloned().unwrap_or_default();
+ messages.push(assistant);
+
+ for call in &calls {
+ let id = call["id"].as_str().unwrap_or_default();
+ let name = call["function"]["name"].as_str().unwrap_or_default();
+ let raw_args = call["function"]["arguments"].as_str().unwrap_or("{}");
+ let shown_args = serde_json::from_str::<Value>(raw_args).unwrap_or_else(|_| json!(raw_args));
+ let _ = event_tx
+ .send(RuntimeEvent::ToolCallPending { id: id.to_string(), name: name.to_string(), args: shown_args })
+ .await;
+ let outcome = session.call(caller, id, name, raw_args).await;
+ let _ = event_tx
+ .send(RuntimeEvent::ToolCallCompleted {
+ id: id.to_string(),
+ result: json!({
+ "status": outcome.status,
+ "content": crate::mcp::truncate_text(&outcome.text, crate::mcp::RECORD_RESULT_MAX_CHARS),
+ }),
+ })
+ .await;
+ messages.push(json!({"role": "tool", "tool_call_id": id, "content": outcome.text}));
+ }
+ }
+ None
+ }
+}
+
#[async_trait]
impl Driver for ApiDriver {
async fn stream_turn(
@@ -107,52 +225,55 @@ impl Driver for ApiDriver {
_ => input.kwant.max_tokens,
};
- let body = json!({
- "model": api_model_name(target_model, &url).await,
- "messages": messages,
- "stream": false, // Non-stream fallback when parsing simple JSON or stream
- "temperature": input.kwant.temperature,
- "max_tokens": max_tokens,
- });
-
- let mut req = self.client.post(&url).json(&body);
- if let Some(key) = api_key {
- req = req.header("Authorization", format!("Bearer {}", key));
+ let model = api_model_name(target_model, &url).await;
+ // The Anthropic Messages API has a different tool format; it is not given MCP tools
+ let mcp = input.mcp.as_ref().filter(|_| !url.ends_with("/v1/messages"));
+ if input.mcp.is_some() && mcp.is_none() {
+ let _ = event_tx
+ .send(RuntimeEvent::ThinkingDelta("MCP tools aren't offered on the Anthropic API endpoint; running without them.".into()))
+ .await;
}
-
- match req.send().await {
- Ok(resp) if resp.status().is_success() => {
- if let Ok(json_body) = resp.json::<serde_json::Value>().await {
- let text = json_body["choices"][0]["message"]["content"]
- .as_str()
- .or_else(|| json_body["content"][0]["text"].as_str())
- .unwrap_or("No response content")
- .to_string();
-
- let tokens = json_body["usage"]["total_tokens"].as_u64().unwrap_or(45) as usize;
-
- let _ = event_tx.send(RuntimeEvent::TextDelta(text.clone())).await;
- let duration = start.elapsed().as_millis() as u64;
- let _ = event_tx
- .send(RuntimeEvent::TurnComplete {
- tokens,
- duration_ms: duration,
- })
- .await;
-
- return Ok(TurnOutput {
- text,
- reasoning: Some(format!("Model: {} [Effort: {}]", target_model, effort)),
- tokens_used: tokens,
- });
+ let session = match mcp {
+ Some(ctx) => {
+ let cwd = input.workspace_dir.as_deref().filter(|d| d.exists());
+ let (session, problems) = McpToolSession::open(ctx, cwd).await;
+ for problem in problems {
+ let _ = event_tx.send(RuntimeEvent::ThinkingDelta(format!("MCP server unavailable: {problem}"))).await;
}
+ Some(session)
}
- Ok(resp) => {
- tracing::warn!(status = %resp.status(), "API returned non-success, using arcade emulation");
- }
- Err(e) => {
- tracing::warn!(error = %e, "API connection failed, using arcade emulation");
- }
+ None => None,
+ };
+ let request = ChatRequest {
+ url: &url,
+ api_key: api_key.as_deref(),
+ model: &model,
+ temperature: input.kwant.temperature,
+ max_tokens,
+ max_calls: mcp.map(|c| c.max_tool_iterations).unwrap_or(1),
+ };
+ let caller = Caller {
+ kwant_id: input.kwant.id.clone(),
+ kwant_name: input.kwant.name.clone(),
+ turn_id: uuid::Uuid::new_v4().to_string(),
+ };
+ let outcome = self.chat_loop(&request, messages, session.as_ref(), &caller, &event_tx).await;
+ if let Some(session) = session {
+ session.shutdown().await;
+ }
+ if let Some((text, tokens)) = outcome {
+ let _ = event_tx.send(RuntimeEvent::TextDelta(text.clone())).await;
+ let _ = event_tx
+ .send(RuntimeEvent::TurnComplete {
+ tokens,
+ duration_ms: start.elapsed().as_millis() as u64,
+ })
+ .await;
+ return Ok(TurnOutput {
+ text,
+ reasoning: Some(format!("Model: {} [Effort: {}]", target_model, effort)),
+ tokens_used: tokens,
+ });
}
}
diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs
index 4ae793a9..88bcaa6d 100644
--- a/src/mcp/mod.rs
+++ b/src/mcp/mod.rs
@@ -4,6 +4,7 @@
pub mod cli_config;
pub mod client;
pub mod echo_server;
+pub mod session;
pub use client::{McpClient, McpError, McpTool};
diff --git a/src/mcp/session.rs b/src/mcp/session.rs
new file mode 100644
index 00000000..88b5a583
--- /dev/null
+++ b/src/mcp/session.rs
@@ -0,0 +1,171 @@
+//! One API-agent turn's MCP connections: offers the servers' tools to the model and runs the
+//! calls it makes, each one approved through the turn's [`ToolApprover`] and recorded.
+
+use super::{
+ client::{McpClient, McpTool},
+ namespaced_tool_name, redact, truncate_text, McpTurnContext, ToolApprovalRequest, RECORD_RESULT_MAX_CHARS,
+};
+use serde_json::{json, Value};
+use std::path::Path;
+use std::time::Instant;
+
+/// OpenAI-compatible APIs reject function names outside `^[a-zA-Z0-9_-]{1,64}$`.
+fn valid_function_name(name: &str) -> bool {
+ !name.is_empty() && name.len() <= 64 && name.chars().all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
+}
+
+struct OfferedTool {
+ name: String,
+ server_index: usize,
+ tool: McpTool,
+}
+
+/// Who is asking, for approval cards.
+#[derive(Debug, Clone)]
+pub struct Caller {
+ pub kwant_id: String,
+ pub kwant_name: String,
+ pub turn_id: String,
+}
+
+pub struct McpToolSession {
+ ctx: McpTurnContext,
+ clients: Vec<(String, McpClient)>,
+ tools: Vec<OfferedTool>,
+ secrets: Vec<String>,
+}
+
+/// The outcome of one call, already redacted; `text` goes back to the model.
+#[derive(Debug, Clone)]
+pub struct CallOutcome {
+ pub text: String,
+ pub status: &'static str,
+ pub record: Value,
+}
+
+impl McpToolSession {
+ /// Connects to every server and lists its tools. Servers that fail are skipped; their
+ /// (redacted) errors are returned so the user can be told.
+ pub async fn open(ctx: &McpTurnContext, cwd: Option<&Path>) -> (Self, Vec<String>) {
+ let secrets = ctx.secret_values();
+ let mut session = Self { ctx: ctx.clone(), clients: Vec::new(), tools: Vec::new(), secrets };
+ let mut problems = Vec::new();
+ let connections = ctx.servers.iter().map(|s| async move {
+ let client = McpClient::connect(s, cwd).await?;
+ match client.list_tools().await {
+ Ok(tools) => Ok((client, tools)),
+ Err(e) => {
+ let mut client = client;
+ client.shutdown().await;
+ Err(e)
+ }
+ }
+ });
+ let results = futures::future::join_all(connections).await;
+ for (server, result) in ctx.servers.iter().zip(results) {
+ match result {
+ Ok((client, tools)) => {
+ let index = session.clients.len();
+ for tool in tools {
+ let name = namespaced_tool_name(&server.name, &tool.name);
+ if valid_function_name(&name) {
+ session.tools.push(OfferedTool { name, server_index: index, tool });
+ } else {
+ tracing::warn!(server = %server.name, tool = %tool.name, "MCP tool name not usable as a function name; skipped");
+ }
+ }
+ session.clients.push((server.name.clone(), client));
+ }
+ Err(e) => problems.push(format!("{}: {}", server.name, redact(&e.to_string(), &session.secrets))),
+ }
+ }
+ (session, problems)
+ }
+
+ /// The `tools` field for an OpenAI-compatible chat completion request.
+ pub fn openai_tools(&self) -> Vec<Value> {
+ self.tools
+ .iter()
+ .map(|t| {
+ let mut parameters = t.tool.input_schema.clone();
+ if !parameters.is_object() {
+ parameters = json!({"type": "object", "properties": {}});
+ }
+ json!({
+ "type": "function",
+ "function": {
+ "name": t.name,
+ "description": t.tool.description.clone().unwrap_or_default(),
+ "parameters": parameters,
+ }
+ })
+ })
+ .collect()
+ }
+
+ /// Runs one model-requested call: approval first, then the MCP call. The record is also
+ /// appended to the turn's `tool_calls`.
+ pub async fn call(&self, caller: &Caller, call_id: &str, name: &str, raw_arguments: &str) -> CallOutcome {
+ let start = Instant::now();
+ let arguments: Value = if raw_arguments.trim().is_empty() {
+ json!({})
+ } else {
+ match serde_json::from_str(raw_arguments) {
+ Ok(v) => v,
+ Err(_) => Value::String(raw_arguments.to_string()),
+ }
+ };
+ let offered = self.tools.iter().find(|t| t.name == name);
+ let (status, text) = match offered {
+ None => ("error", format!("Unknown tool {name}.")),
+ Some(_) if !arguments.is_object() => ("error", "Tool arguments must be a JSON object.".to_string()),
+ Some(t) => {
+ let (server, client) = &self.clients[t.server_index];
+ let approved = self
+ .ctx
+ .approver
+ .approve(ToolApprovalRequest {
+ kwant_id: caller.kwant_id.clone(),
+ kwant_name: caller.kwant_name.clone(),
+ turn_id: caller.turn_id.clone(),
+ tool_name: name.to_string(),
+ server: server.clone(),
+ tool: t.tool.name.clone(),
+ arguments: arguments.clone(),
+ })
+ .await;
+ if !approved {
+ ("denied", "The user denied this tool call.".to_string())
+ } else {
+ match client.call_tool(&t.tool.name, arguments.clone()).await {
+ Ok(r) if r.is_error => ("error", r.text),
+ Ok(r) => ("ok", r.text),
+ Err(e) => ("error", format!("Tool call failed: {e}")),
+ }
+ }
+ }
+ };
+ let text = redact(&text, &self.secrets);
+ let (server, tool) = super::split_tool_name(name).unwrap_or(("", name));
+ let mut record = json!({
+ "id": call_id,
+ "name": name,
+ "server": server,
+ "tool": tool,
+ "arguments": arguments,
+ "status": status,
+ "duration_ms": start.elapsed().as_millis() as u64,
+ });
+ if status != "denied" {
+ record["result"] = json!(truncate_text(&text, RECORD_RESULT_MAX_CHARS));
+ }
+ self.ctx.record(record.clone());
+ CallOutcome { text, status, record }
+ }
+
+ pub async fn shutdown(mut self) {
+ for (_, client) in &mut self.clients {
+ client.shutdown().await;
+ }
+ }
+}
diff --git a/tests/mcp_api_loop_test.rs b/tests/mcp_api_loop_test.rs
new file mode 100644
index 00000000..82635c64
--- /dev/null
+++ b/tests/mcp_api_loop_test.rs
@@ -0,0 +1,252 @@
+//! API-agent MCP tool loop against a local mock OpenAI endpoint and the echo MCP server.
+//! No network and no API keys: the mock listens on 127.0.0.1.
+
+use axum::{extract::State, routing::post, Json, Router};
+use kwnt::{
+ db::models::{Kwant, McpServer},
+ drivers::{events::RuntimeEvent, ApiDriver, Driver, TurnInput, TurnOutput},
+ mcp::{FixedApprover, McpTurnContext, ToolApprover, SECRET_MASK},
+};
+use serde_json::{json, Value};
+use std::collections::BTreeMap;
+use std::sync::{Arc, Mutex};
+
+const KWNT: &str = env!("CARGO_BIN_EXE_kwnt");
+
+#[derive(Clone, Default)]
+struct Mock {
+ /// Replies in order; the last one repeats.
+ replies: Arc<Vec<Value>>,
+ requests: Arc<Mutex<Vec<Value>>>,
+}
+
+async fn completions(State(mock): State<Mock>, Json(body): Json<Value>) -> Json<Value> {
+ let n = {
+ let mut r = mock.requests.lock().unwrap();
+ r.push(body);
+ r.len()
+ };
+ Json(mock.replies[(n - 1).min(mock.replies.len() - 1)].clone())
+}
+
+async fn start_mock(replies: Vec<Value>) -> (String, Mock) {
+ let mock = Mock { replies: Arc::new(replies), ..Default::default() };
+ let app = Router::new().route("/v1/chat/completions", post(completions)).with_state(mock.clone());
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ tokio::spawn(async move { axum::serve(listener, app).await.unwrap() });
+ (format!("http://{addr}/v1/chat/completions"), mock)
+}
+
+fn tool_call(id: &str, name: &str, args: Value) -> Value {
+ json!({"choices": [{"message": {"role": "assistant", "content": null, "tool_calls": [
+ {"id": id, "type": "function", "function": {"name": name, "arguments": args.to_string()}}]}}],
+ "usage": {"total_tokens": 10}})
+}
+
+fn answer(text: &str) -> Value {
+ json!({"choices": [{"message": {"role": "assistant", "content": text}}], "usage": {"total_tokens": 7}})
+}
+
+fn echo_server(timeout_secs: i64) -> McpServer {
+ McpServer {
+ id: "s1".into(),
+ name: "echo".into(),
+ transport: "stdio".into(),
+ command: Some(KWNT.into()),
+ args: vec!["mcp-echo-server".into()],
+ url: None,
+ env: BTreeMap::from([("ECHO_SECRET".to_string(), "hunter2-secret".to_string())]),
+ headers: BTreeMap::new(),
+ enabled: true,
+ timeout_secs,
+ created_at: None,
+ }
+}
+
+fn ctx(approver: Arc<dyn ToolApprover>, timeout_secs: i64, max: usize) -> McpTurnContext {
+ McpTurnContext {
+ servers: vec![echo_server(timeout_secs)],
+ approver,
+ config_dir: std::env::temp_dir(),
+ permission_url: None,
+ max_tool_iterations: max,
+ records: Default::default(),
+ }
+}
+
+fn input(mcp: Option<McpTurnContext>) -> TurnInput {
+ TurnInput {
+ browser_api_url: None,
+ thread_id: "t1".into(),
+ kwant: Kwant {
+ id: "k1".into(),
+ name: "Ada".into(),
+ title: "Lead".into(),
+ persona_prompt: "p".into(),
+ soul: String::new(),
+ avatar_sprite: "s".into(),
+ driver_type: "api".into(),
+ preferred_model: "mock-model".into(),
+ temperature: 0.2,
+ max_tokens: 256,
+ level: 1,
+ turns_completed: 0,
+ created_at: None,
+ },
+ prompt: "use the tool".into(),
+ history: vec![],
+ model_override: None,
+ effort_level: Some("low".into()),
+ team_context: None,
+ workspace_dir: None,
+ sandbox_id: None,
+ teammates: vec![],
+ mcp,
+ }
+}
+
+async fn run(url: String, input: TurnInput) -> (TurnOutput, Vec<RuntimeEvent>) {
+ let driver = ApiDriver::new(Some("test-key-not-real".into()), Some(url));
+ let (tx, mut rx) = tokio::sync::mpsc::channel(256);
+ let collect = tokio::spawn(async move {
+ let mut events = Vec::new();
+ while let Some(e) = rx.recv().await {
+ events.push(e);
+ }
+ events
+ });
+ let out = driver.stream_turn(input, tx).await.unwrap();
+ (out, collect.await.unwrap())
+}
+
+/// The tool message the model received in its second request.
+fn tool_message(mock: &Mock, request: usize) -> Value {
+ let requests = mock.requests.lock().unwrap();
+ requests[request]["messages"].as_array().unwrap().iter().rev().find(|m| m["role"] == "tool").cloned().unwrap()
+}
+
+#[tokio::test]
+async fn model_lists_and_calls_mcp_tools() {
+ let (url, mock) = start_mock(vec![tool_call("call_1", "mcp__echo__echo", json!({"text": "hello"})), answer("The tool said hello.")]).await;
+ let c = ctx(Arc::new(FixedApprover(true)), 10, 8);
+ let (out, events) = run(url, input(Some(c.clone()))).await;
+
+ assert_eq!(out.text, "The tool said hello.");
+ assert_eq!(out.tokens_used, 17);
+ let requests = mock.requests.lock().unwrap().clone();
+ assert_eq!(requests.len(), 2);
+ let names: Vec<_> = requests[0]["tools"].as_array().unwrap().iter().map(|t| t["function"]["name"].as_str().unwrap()).collect();
+ assert_eq!(names, ["mcp__echo__echo", "mcp__echo__add", "mcp__echo__sleep", "mcp__echo__env", "mcp__echo__crash"]);
+ assert_eq!(requests[0]["tools"][0]["function"]["parameters"]["required"], json!(["text"]));
+ // Second request carries the assistant tool call and its result
+ let msgs = requests[1]["messages"].as_array().unwrap();
+ assert_eq!(msgs[msgs.len() - 2]["tool_calls"][0]["id"], "call_1");
+ assert_eq!(msgs[msgs.len() - 1], json!({"role": "tool", "tool_call_id": "call_1", "content": "hello"}));
+
+ assert!(events.iter().any(|e| matches!(e, RuntimeEvent::ToolCallPending { id, name, .. } if id == "call_1" && name == "mcp__echo__echo")));
+ assert!(events.iter().any(|e| matches!(e, RuntimeEvent::ToolCallCompleted { id, result } if id == "call_1" && result["status"] == "ok")));
+ let records = c.take_records();
+ assert_eq!(records.len(), 1);
+ assert_eq!(records[0]["status"], "ok");
+ assert_eq!(records[0]["result"], "hello");
+ assert_eq!(records[0]["server"], "echo");
+ assert_eq!(records[0]["arguments"], json!({"text": "hello"}));
+}
+
+#[tokio::test]
+async fn denied_call_is_not_run_and_model_is_told() {
+ let (url, mock) = start_mock(vec![tool_call("call_1", "mcp__echo__add", json!({"a": 1, "b": 2})), answer("ok, no tool")]).await;
+ let c = ctx(Arc::new(FixedApprover(false)), 10, 8);
+ let (out, _) = run(url, input(Some(c.clone()))).await;
+ assert_eq!(out.text, "ok, no tool");
+ assert_eq!(tool_message(&mock, 1)["content"], "The user denied this tool call.");
+ let records = c.take_records();
+ assert_eq!(records[0]["status"], "denied");
+ assert!(records[0].get("result").is_none());
+}
+
+#[tokio::test]
+async fn server_crash_mid_call_becomes_a_tool_error() {
+ let (url, mock) = start_mock(vec![
+ tool_call("c1", "mcp__echo__crash", json!({})),
+ tool_call("c2", "mcp__echo__echo", json!({"text": "again"})),
+ answer("server is gone"),
+ ])
+ .await;
+ let c = ctx(Arc::new(FixedApprover(true)), 30, 8);
+ let start = std::time::Instant::now();
+ let (out, _) = run(url, input(Some(c.clone()))).await;
+ assert!(start.elapsed() < std::time::Duration::from_secs(10));
+ assert_eq!(out.text, "server is gone");
+ assert!(tool_message(&mock, 1)["content"].as_str().unwrap().contains("failed"));
+ let records = c.take_records();
+ assert_eq!(records[0]["status"], "error");
+ assert_eq!(records[1]["status"], "error", "later calls to a dead server fail fast");
+}
+
+#[tokio::test]
+async fn slow_tool_times_out() {
+ let (url, mock) = start_mock(vec![tool_call("c1", "mcp__echo__sleep", json!({"ms": 10_000})), answer("too slow")]).await;
+ let c = ctx(Arc::new(FixedApprover(true)), 1, 8);
+ let start = std::time::Instant::now();
+ let (out, _) = run(url, input(Some(c.clone()))).await;
+ assert!(start.elapsed() < std::time::Duration::from_secs(6));
+ assert_eq!(out.text, "too slow");
+ assert!(tool_message(&mock, 1)["content"].as_str().unwrap().contains("timed out"), "{}", tool_message(&mock, 1));
+ assert_eq!(c.take_records()[0]["status"], "error");
+}
+
+#[tokio::test]
+async fn secrets_in_tool_output_are_masked() {
+ let (url, mock) = start_mock(vec![tool_call("c1", "mcp__echo__env", json!({"name": "ECHO_SECRET"})), answer("done")]).await;
+ let c = ctx(Arc::new(FixedApprover(true)), 10, 8);
+ let (_, events) = run(url, input(Some(c.clone()))).await;
+ assert_eq!(tool_message(&mock, 1)["content"], SECRET_MASK);
+ let records = c.take_records();
+ assert_eq!(records[0]["result"], SECRET_MASK);
+ let all = format!("{events:?} {records:?} {:?}", mock.requests.lock().unwrap());
+ assert!(!all.contains("hunter2-secret"));
+}
+
+#[tokio::test]
+async fn tool_loop_stops_at_max_iterations() {
+ let (url, mock) = start_mock(vec![tool_call("c", "mcp__echo__add", json!({"a": 1, "b": 1}))]).await;
+ let c = ctx(Arc::new(FixedApprover(true)), 10, 3);
+ let (out, _) = run(url, input(Some(c.clone()))).await;
+ assert_eq!(mock.requests.lock().unwrap().len(), 3);
+ assert!(out.text.contains("limit of 3 model calls"), "{}", out.text);
+ assert_eq!(c.take_records().len(), 2, "the last round's calls are not run");
+}
+
+#[tokio::test]
+async fn unknown_tools_and_bad_arguments_are_errors() {
+ let (url, mock) = start_mock(vec![
+ json!({"choices": [{"message": {"role": "assistant", "content": "", "tool_calls": [
+ {"id": "a", "type": "function", "function": {"name": "mcp__other__x", "arguments": "{}"}},
+ {"id": "b", "type": "function", "function": {"name": "mcp__echo__echo", "arguments": "not json"}},
+ {"id": "c", "type": "function", "function": {"name": "mcp__echo__add", "arguments": {"a": 2, "b": 3}}}]}}]}),
+ answer("fine"),
+ ])
+ .await;
+ let c = ctx(Arc::new(FixedApprover(true)), 10, 8);
+ let (out, _) = run(url, input(Some(c.clone()))).await;
+ assert_eq!(out.text, "fine");
+ let records = c.take_records();
+ let statuses: Vec<_> = records.iter().map(|r| r["status"].as_str().unwrap()).collect();
+ assert_eq!(statuses, ["error", "error", "ok"]);
+ assert_eq!(records[2]["result"], "5", "object-form arguments (Ollama) are accepted");
+ let second = mock.requests.lock().unwrap()[1].clone();
+ let assistant = second["messages"].as_array().unwrap().iter().find(|m| m["role"] == "assistant").unwrap().clone();
+ assert!(assistant["tool_calls"][2]["function"]["arguments"].is_string());
+}
+
+#[tokio::test]
+async fn kwant_without_servers_makes_a_single_plain_call() {
+ let (url, mock) = start_mock(vec![answer("hi there")]).await;
+ let (out, _) = run(url, input(None)).await;
+ assert_eq!(out.text, "hi there");
+ let requests = mock.requests.lock().unwrap();
+ assert_eq!(requests.len(), 1);
+ assert!(requests[0].get("tools").is_none());
+}