From 4683f2e0679213f2785640ef91e9b59c6c04f8f0 Mon Sep 17 00:00:00 2001 From: cflmy Date: Tue, 27 Oct 2026 13:18:55 +0800 Subject: [PATCH] feat(agent): ToolSpec registry with authorize-before-call Add ToolSpecV1 register/search/describe/prepare so CALL and native paths share one schema gate; unauthorized and invalid-arg prepares fail with zero executions. Co-authored-by: Cursor --- ext/ai/agent.mq.md | 107 +++++- plugins/agent/src/lib.rs | 31 +- plugins/agent/src/tools.rs | 705 ++++++++++++++++++++++++++++++++++ src/workbench/capabilities.rs | 6 +- tests/workbench_contracts.rs | 10 +- 5 files changed, 842 insertions(+), 17 deletions(-) create mode 100644 plugins/agent/src/tools.rs diff --git a/ext/ai/agent.mq.md b/ext/ai/agent.mq.md index 525b011..5680c51 100644 --- a/ext/ai/agent.mq.md +++ b/ext/ai/agent.mq.md @@ -181,16 +181,109 @@ Find a human-readable call line: `CALL:` or `调用:` / `调用: agent_tool_allowed tools=`tools` name=`name`** -1. `allowed` - **id = > subtask.spawn fn=`name`** - *> subtask.wait id=`id`* +**p = > plugin.native_path name="agent"** +1. `p` + > plugin.load path=`p` 2. * - **msg = "Tool not allowed:"** - *msg + name* + **_ = 1** + +1. `p` + **prep = > agent_tools_prepare_call tool_id=`name` tools=`tools` arguments=`arguments`** + **pok = > json.get value=`prep` key="ok"** + 1. not `pok` + *prep* + 2. * + **_ = 1** +2. * + **allowed = > agent_tool_allowed tools=`tools` name=`name`** + 1. not `allowed` + **msg = "Tool not allowed:"** + *msg + name* + 2. * + **_ = 1** + +**id = > subtask.spawn fn=`name`** +*> subtask.wait id=`id`* + +## tools_register + + `spec`=None + + `specs`=None + +Register ToolSpecV1 document(s). Unsupported schema keywords are refused. + +**p = > plugin.native_path name="agent"** +1. `p` + > plugin.load path=`p` +2. * + > print text=ext/ai/agent: native agent plugin not found + > sys.exit code=1 + +*> agent_tools_register spec=`spec` specs=`specs`* + +## tools_search + + `query`="" + + `tools`=None + +Search authorized registered tools (summaries only). + +**p = > plugin.native_path name="agent"** +1. `p` + > plugin.load path=`p` +2. * + > print text=ext/ai/agent: native agent plugin not found + > sys.exit code=1 + +*> agent_tools_search query=`query` tools=`tools`* + +## tools_describe + + `id` + + `tools`=None + +Return full ToolSpecV1 for an authorized tool id. + +**p = > plugin.native_path name="agent"** +1. `p` + > plugin.load path=`p` +2. * + > print text=ext/ai/agent: native agent plugin not found + > sys.exit code=1 + +*> agent_tools_describe id=`id` tools=`tools`* + +## tools_register_eng_defaults + +Seed the five engineering tool specs (`tool_find` … `tool_summarize`). + +**p = > plugin.native_path name="agent"** +1. `p` + > plugin.load path=`p` +2. * + > print text=ext/ai/agent: native agent plugin not found + > sys.exit code=1 + +*> agent_tools_register_eng_defaults* + +## tools_prepare_call + + `tool_id` + + `arguments`=None + + `tools`=None + + `call_id`=None + +Validate schema + authorize; returns ToolCallV1 or ToolResultV1 error (no side effects). + +**p = > plugin.native_path name="agent"** +1. `p` + > plugin.load path=`p` +2. * + > print text=ext/ai/agent: native agent plugin not found + > sys.exit code=1 + +*> agent_tools_prepare_call tool_id=`tool_id` arguments=`arguments` tools=`tools` call_id=`call_id`* ## render_workbook_skeleton + `goal` diff --git a/plugins/agent/src/lib.rs b/plugins/agent/src/lib.rs index d618acf..48d2fce 100644 --- a/plugins/agent/src/lib.rs +++ b/plugins/agent/src/lib.rs @@ -10,6 +10,7 @@ mod memory; mod resume; mod route; mod sandbox; +mod tools; use std::collections::HashMap; use std::ffi::CString; @@ -668,7 +669,7 @@ unsafe extern "C" fn agent_marqdo_skill( } } -fn tool_names(tools: &serde_json::Value) -> Vec { +pub(crate) fn tool_names(tools: &serde_json::Value) -> Vec { let mut out = Vec::new(); let rows = match tools { serde_json::Value::Array(a) => a.as_slice(), @@ -832,6 +833,22 @@ kb_ffi!(agent_resume_clear, resume::resume_clear, "agent_resume_clear"); kb_ffi!(agent_resume_list, resume::resume_list, "agent_resume_list"); kb_ffi!(agent_error_make, error::make_error, "agent_error_make"); kb_ffi!(agent_error_decide_retry, error::decide_retry, "agent_error_decide_retry"); +kb_ffi!(agent_tools_register, tools::tools_register, "agent_tools_register"); +kb_ffi!(agent_tools_clear, tools::tools_clear, "agent_tools_clear"); +kb_ffi!(agent_tools_search, tools::tools_search, "agent_tools_search"); +kb_ffi!(agent_tools_describe, tools::tools_describe, "agent_tools_describe"); +kb_ffi!(agent_tools_prepare_call, tools::tools_prepare_call, "agent_tools_prepare_call"); +kb_ffi!(agent_tools_wrap_result, tools::tools_wrap_result, "agent_tools_wrap_result"); +kb_ffi!( + agent_tools_register_eng_defaults, + tools::tools_register_eng_defaults, + "agent_tools_register_eng_defaults" +); +kb_ffi!( + agent_tools_seed_allowlist, + tools::seed_from_allowlist_args, + "agent_tools_seed_allowlist" +); kb_ffi!(agent_eng_preflight, eng::eng_preflight, "agent_eng_preflight"); kb_ffi!(agent_eng_reuse, eng::eng_reuse, "agent_eng_reuse"); kb_ffi!(agent_eng_bind_execute, eng::eng_bind_execute, "agent_eng_bind_execute"); @@ -883,6 +900,18 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int ("agent_resume_list", "resume_dir", agent_resume_list), ("agent_error_make", "code,message,category", agent_error_make), ("agent_error_decide_retry", "error,attempts,effect_class", agent_error_decide_retry), + ("agent_tools_register", "spec,specs", agent_tools_register), + ("agent_tools_clear", "", agent_tools_clear), + ("agent_tools_search", "query,tools", agent_tools_search), + ("agent_tools_describe", "id,tools", agent_tools_describe), + ("agent_tools_prepare_call", "tool_id,arguments,tools", agent_tools_prepare_call), + ("agent_tools_wrap_result", "ok,status,summary", agent_tools_wrap_result), + ( + "agent_tools_register_eng_defaults", + "", + agent_tools_register_eng_defaults, + ), + ("agent_tools_seed_allowlist", "tools", agent_tools_seed_allowlist), ("agent_kb_add_alias", "kb_dir,slug,alias", agent_kb_add_alias), ("agent_kb_promote", "kb_dir,goal,workbook", agent_kb_promote), ("agent_kb_quarantine", "kb_dir,slug", agent_kb_quarantine), diff --git a/plugins/agent/src/tools.rs b/plugins/agent/src/tools.rs new file mode 100644 index 0000000..49f1b00 --- /dev/null +++ b/plugins/agent/src/tools.rs @@ -0,0 +1,705 @@ +//! ToolSpecV1 registry + call validation (M-A2). +//! Discovery → schema validate → authorize. Execution of Marqdo `##` stays in subtask; +//! this module never evals model-supplied code. + +use std::collections::HashMap; +use std::sync::{Mutex, OnceLock}; + +use serde_json::{json, Map, Value}; + +fn registry() -> &'static Mutex> { + static REG: OnceLock>> = OnceLock::new(); + REG.get_or_init(|| Mutex::new(HashMap::new())) +} + +fn opt_text<'a>(args: &'a Value, key: &str) -> Option<&'a str> { + args.get(key) + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) +} + +fn arg_text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> { + opt_text(args, key).ok_or_else(|| format!("missing text `{key}`")) +} + +/// Supported JSON Schema subset for tool input (reject unsupported constructs). +fn validate_schema_subset(schema: &Value) -> Result<(), String> { + let obj = schema + .as_object() + .ok_or_else(|| "input_schema must be object".to_string())?; + let ty = obj + .get("type") + .and_then(|v| v.as_str()) + .unwrap_or("object"); + if ty != "object" { + return Err(format!("unsupported root type={ty}; only object")); + } + if let Some(props) = obj.get("properties") { + let props = props + .as_object() + .ok_or_else(|| "properties must be object".to_string())?; + for (name, prop) in props { + let p = prop + .as_object() + .ok_or_else(|| format!("property {name} must be object"))?; + let pty = p.get("type").and_then(|v| v.as_str()).unwrap_or("string"); + match pty { + "string" | "integer" | "number" | "boolean" | "array" | "object" => {} + other => { + return Err(format!( + "unsupported property type {other} for {name}; refuse register" + )) + } + } + // Reject constructs we do not implement. + for banned in ["$ref", "oneOf", "anyOf", "allOf", "not", "if", "then", "else"] { + if p.contains_key(banned) { + return Err(format!( + "unsupported schema keyword {banned} on {name}; refuse register" + )); + } + } + } + } + for banned in ["$ref", "oneOf", "anyOf", "allOf", "not", "if", "then", "else"] { + if obj.contains_key(banned) { + return Err(format!( + "unsupported schema keyword {banned}; refuse register" + )); + } + } + Ok(()) +} + +fn normalize_spec(mut spec: Value) -> Result { + let obj = spec + .as_object_mut() + .ok_or_else(|| "spec must be object".to_string())?; + obj.insert("schema".into(), json!("ToolSpecV1")); + obj.entry("schema_version".to_string()) + .or_insert(json!(1)); + let id = obj + .get("id") + .and_then(|v| v.as_str()) + .filter(|s| !s.is_empty()) + .ok_or_else(|| "ToolSpecV1 requires id".to_string())? + .to_string(); + obj.entry("version".to_string()).or_insert(json!("1")); + obj.entry("description".to_string()) + .or_insert(json!("")); + let input = obj + .get("input_schema") + .cloned() + .unwrap_or_else(|| json!({"type": "object", "properties": {}, "additionalProperties": false})); + validate_schema_subset(&input)?; + obj.insert("input_schema".into(), input); + obj.entry("effect".to_string()).or_insert(json!("read")); + let effect = obj.get("effect").and_then(|v| v.as_str()).unwrap_or("read"); + if !matches!(effect, "read" | "write" | "execute" | "external_write") { + return Err(format!("invalid effect={effect}")); + } + obj.entry("scopes".to_string()).or_insert(json!([])); + obj.entry("timeout_ms".to_string()).or_insert(json!(10_000)); + obj.entry("max_result_bytes".to_string()) + .or_insert(json!(65_536)); + obj.entry("idempotency".to_string()) + .or_insert(json!("safe")); + obj.entry("availability".to_string()) + .or_insert(json!("ready")); + let _ = id; + Ok(spec) +} + +fn validate_args_against_schema(schema: &Value, arguments: &Value) -> Result<(), String> { + let args = arguments + .as_object() + .ok_or_else(|| "arguments must be object".to_string())?; + let sch = schema.as_object().ok_or_else(|| "input_schema invalid".to_string())?; + let props = sch + .get("properties") + .and_then(|v| v.as_object()) + .cloned() + .unwrap_or_default(); + let additional = sch + .get("additionalProperties") + .and_then(|v| v.as_bool()) + .unwrap_or(true); + if !additional { + for key in args.keys() { + if !props.contains_key(key) { + return Err(format!("unknown argument `{key}`")); + } + } + } + if let Some(req) = sch.get("required").and_then(|v| v.as_array()) { + for r in req { + let name = r.as_str().unwrap_or(""); + if name.is_empty() { + continue; + } + if !args.contains_key(name) || args.get(name).map(|v| v.is_null()).unwrap_or(true) { + return Err(format!("missing required argument `{name}`")); + } + } + } + for (key, val) in args { + if let Some(prop) = props.get(key) { + if let Some(pty) = prop.get("type").and_then(|v| v.as_str()) { + let ok = match pty { + "string" => val.is_string(), + "integer" => val.as_i64().is_some() || val.as_u64().is_some(), + "number" => val.as_f64().is_some(), + "boolean" => val.is_boolean(), + "array" => val.is_array(), + "object" => val.is_object(), + _ => true, + }; + if !ok { + return Err(format!("argument `{key}` type mismatch (want {pty})")); + } + } + if let Some(min) = prop.get("minimum").and_then(|v| v.as_f64()) { + if let Some(n) = val.as_f64() { + if n < min { + return Err(format!("argument `{key}` below minimum {min}")); + } + } + } + if let Some(max) = prop.get("maximum").and_then(|v| v.as_f64()) { + if let Some(n) = val.as_f64() { + if n > max { + return Err(format!("argument `{key}` above maximum {max}")); + } + } + } + } + } + Ok(()) +} + +fn authorized(allowlist: Option<&Value>, tool_id: &str) -> bool { + match allowlist { + None => true, // registry-only call sites may omit; still need registered spec + Some(tools) => crate::tool_names(tools).iter().any(|n| n == tool_id), + } +} + +/// Register one ToolSpecV1 (or list). Host/trusted only — model cannot invent principal/root. +pub fn tools_register(args: &Value) -> Result { + let specs = if let Some(arr) = args.get("specs").and_then(|v| v.as_array()) { + arr.clone() + } else if args.get("spec").is_some() || args.get("id").is_some() { + let raw = args.get("spec").cloned().unwrap_or_else(|| args.clone()); + vec![raw] + } else { + return Err("tools.register requires spec or specs[]".into()); + }; + let mut registered = Vec::new(); + let mut guard = registry() + .lock() + .map_err(|_| "tools registry lock poisoned".to_string())?; + for raw in specs { + let spec = normalize_spec(raw)?; + let id = spec + .get("id") + .and_then(|v| v.as_str()) + .unwrap() + .to_string(); + guard.insert(id.clone(), spec); + registered.push(id); + } + Ok(json!({ + "ok": true, + "registered": registered, + "count": registered.len(), + })) +} + +pub fn tools_clear(args: &Value) -> Result { + let _ = args; + let mut guard = registry() + .lock() + .map_err(|_| "tools registry lock poisoned".to_string())?; + let n = guard.len(); + guard.clear(); + Ok(json!({"ok": true, "cleared": n})) +} + +pub fn tools_search(args: &Value) -> Result { + let query = opt_text(args, "query").unwrap_or("").to_ascii_lowercase(); + let allow = args.get("tools"); + let guard = registry() + .lock() + .map_err(|_| "tools registry lock poisoned".to_string())?; + let mut items = Vec::new(); + for (id, spec) in guard.iter() { + let avail = spec + .get("availability") + .and_then(|v| v.as_str()) + .unwrap_or("ready"); + let auth = authorized(allow, id); + if !auth { + // Do not leak unauthorized private connector names in search hits. + continue; + } + if !query.is_empty() { + let desc = spec + .get("description") + .and_then(|v| v.as_str()) + .unwrap_or(""); + if !id.to_ascii_lowercase().contains(&query) + && !desc.to_ascii_lowercase().contains(&query) + { + continue; + } + } + items.push(json!({ + "id": id, + "version": spec.get("version").cloned().unwrap_or(json!("1")), + "description": spec.get("description").cloned().unwrap_or(json!("")), + "effect": spec.get("effect").cloned().unwrap_or(json!("read")), + "availability": avail, + "authorized": true, + })); + } + items.sort_by(|a, b| { + let ai = a.get("id").and_then(|v| v.as_str()).unwrap_or(""); + let bi = b.get("id").and_then(|v| v.as_str()).unwrap_or(""); + ai.cmp(bi) + }); + Ok(json!({ + "ok": true, + "schema": "ToolSearchResultV1", + "schema_version": 1, + "items": items, + "count": items.len(), + })) +} + +pub fn tools_describe(args: &Value) -> Result { + let id = arg_text(args, "id")?; + let allow = args.get("tools"); + if !authorized(allow, id) { + return Ok(json!({ + "ok": false, + "found": false, + "authorized": false, + "error": { + "schema": "AgentErrorV1", + "schema_version": 1, + "code": "tool.forbidden", + "category": "forbidden", + "stage": "tool", + "message": format!("tool `{id}` not in allowlist"), + "retryable": false, + "effect_state": "none", + "recovery_action": "needs_input", + } + })); + } + let guard = registry() + .lock() + .map_err(|_| "tools registry lock poisoned".to_string())?; + match guard.get(id) { + Some(spec) => Ok(json!({ + "ok": true, + "found": true, + "authorized": true, + "spec": spec, + })), + None => Ok(json!({ + "ok": false, + "found": false, + "authorized": true, + "error": { + "schema": "AgentErrorV1", + "schema_version": 1, + "code": "tool.not_found", + "category": "capability_unavailable", + "stage": "tool", + "message": format!("tool `{id}` not registered"), + "retryable": false, + "effect_state": "none", + "recovery_action": "stop", + } + })), + } +} + +/// Validate + authorize a ToolCallV1. Does not execute side effects. +pub fn tools_prepare_call(args: &Value) -> Result { + let tool_id = arg_text(args, "tool_id") + .or_else(|_| arg_text(args, "id")) + .or_else(|_| arg_text(args, "name"))?; + let allow = args.get("tools"); + if !authorized(allow, tool_id) { + return Ok(tool_result_err( + "tool.forbidden", + "forbidden", + format!("unauthorized call to `{tool_id}`"), + false, + )); + } + let guard = registry() + .lock() + .map_err(|_| "tools registry lock poisoned".to_string())?; + let spec = match guard.get(tool_id) { + Some(s) => s.clone(), + None => { + return Ok(tool_result_err( + "tool.not_found", + "capability_unavailable", + format!("tool `{tool_id}` not registered"), + false, + )); + } + }; + drop(guard); + + let avail = spec + .get("availability") + .and_then(|v| v.as_str()) + .unwrap_or("ready"); + if avail != "ready" { + return Ok(tool_result_err( + "tool.unavailable", + "capability_unavailable", + format!("tool `{tool_id}` availability={avail}"), + false, + )); + } + + let arguments = args + .get("arguments") + .cloned() + .unwrap_or_else(|| json!({})); + let schema = spec + .get("input_schema") + .cloned() + .unwrap_or_else(|| json!({"type":"object"})); + if let Err(e) = validate_args_against_schema(&schema, &arguments) { + return Ok(tool_result_err( + "tool.invalid_arguments", + "invalid_arguments", + e, + true, + )); + } + + let call_id = opt_text(args, "call_id") + .map(|s| s.to_string()) + .unwrap_or_else(|| format!("call_{}", std::process::id())); + let operation_id = opt_text(args, "operation_id") + .map(|s| s.to_string()) + .unwrap_or_else(|| format!("op_{tool_id}_{call_id}")); + let version = spec + .get("version") + .and_then(|v| v.as_str()) + .unwrap_or("1"); + + let call = json!({ + "schema": "ToolCallV1", + "schema_version": 1, + "call_id": call_id, + "tool_id": tool_id, + "tool_version": version, + "arguments": arguments, + "operation_id": operation_id, + "parent_span_id": args.get("parent_span_id").cloned().unwrap_or(Value::Null), + }); + + Ok(json!({ + "ok": true, + "status": "prepared", + "call": call, + "spec": { + "id": tool_id, + "effect": spec.get("effect").cloned().unwrap_or(json!("read")), + "timeout_ms": spec.get("timeout_ms").cloned().unwrap_or(json!(10000)), + "max_result_bytes": spec.get("max_result_bytes").cloned().unwrap_or(json!(65536)), + }, + "summary": format!("prepared authorized call to `{tool_id}`"), + })) +} + +/// Wrap a successful / failed tool execution into ToolResultV1. +pub fn tools_wrap_result(args: &Value) -> Result { + let ok = args.get("ok").and_then(|v| v.as_bool()).unwrap_or(false); + let status = opt_text(args, "status").unwrap_or(if ok { "succeeded" } else { "failed" }); + let summary = opt_text(args, "summary").unwrap_or(""); + let mut out = json!({ + "schema": "ToolResultV1", + "schema_version": 1, + "ok": ok, + "status": status, + "summary": summary, + "structured_content": args.get("structured_content").cloned().unwrap_or(Value::Null), + "resources": args.get("resources").cloned().unwrap_or_else(|| json!([])), + "citations": args.get("citations").cloned().unwrap_or_else(|| json!([])), + "error": args.get("error").cloned().unwrap_or(Value::Null), + "usage": args.get("usage").cloned().unwrap_or(Value::Null), + "truncated": args.get("truncated").and_then(|v| v.as_bool()).unwrap_or(false), + "next_cursor": args.get("next_cursor").cloned().unwrap_or(Value::Null), + "effect_receipt_ref": args.get("effect_receipt_ref").cloned().unwrap_or(Value::Null), + }); + // Truncate oversized summary into artifact hint (do not dump MB into prompt). + let max_bytes = args + .get("max_result_bytes") + .and_then(|v| v.as_u64()) + .unwrap_or(65_536) as usize; + if summary.len() > max_bytes { + if let Some(obj) = out.as_object_mut() { + obj.insert("truncated".into(), json!(true)); + obj.insert( + "summary".into(), + json!(format!( + "{}… [truncated; use resource handle]", + &summary[..max_bytes.min(summary.len())] + )), + ); + } + } + Ok(out) +} + +/// Seed the five engineering tools used by qdagent (aliases remain CALL:tool_*). +pub fn tools_register_eng_defaults(args: &Value) -> Result { + let _ = args; + let specs = eng_default_specs(); + tools_register(&json!({"specs": specs})) +} + +fn eng_default_specs() -> Vec { + vec![ + json!({ + "id": "tool_find", + "version": "1", + "description": "Engineering find via EKC (read-only)", + "input_schema": { + "type": "object", + "properties": {"query": {"type": "string"}}, + "required": ["query"], + "additionalProperties": false + }, + "effect": "read", + "scopes": ["knowledge:read"], + "availability": "ready" + }), + json!({ + "id": "tool_reuse", + "version": "1", + "description": "Engineering reuse / preflight discovery (read-only)", + "input_schema": { + "type": "object", + "properties": {"task": {"type": "string"}}, + "required": ["task"], + "additionalProperties": false + }, + "effect": "read", + "scopes": ["knowledge:read"], + "availability": "ready" + }), + json!({ + "id": "tool_bind", + "version": "1", + "description": "Bind and execute a verified knowledge artifact", + "input_schema": { + "type": "object", + "properties": { + "query": {"type": "string"}, + "policy": {"type": "string"}, + "project": {"type": "string"} + }, + "required": ["query"], + "additionalProperties": false + }, + "effect": "execute", + "scopes": ["knowledge:execute"], + "availability": "ready" + }), + json!({ + "id": "tool_verify", + "version": "1", + "description": "Run L3 knowledge verification checks", + "input_schema": { + "type": "object", + "properties": {}, + "additionalProperties": false + }, + "effect": "read", + "scopes": ["knowledge:verify"], + "availability": "ready" + }), + json!({ + "id": "tool_summarize", + "version": "1", + "description": "Summarize a Context Pack / preflight map", + "input_schema": { + "type": "object", + "properties": {"preflight": {"type": "object"}}, + "required": ["preflight"], + "additionalProperties": false + }, + "effect": "read", + "scopes": ["knowledge:read"], + "availability": "ready" + }), + ] +} + +fn tool_result_err(code: &str, category: &str, message: String, retryable: bool) -> Value { + let recovery = if category == "invalid_arguments" { + "repair_args" + } else if category == "forbidden" { + "needs_input" + } else { + "stop" + }; + json!({ + "ok": false, + "status": "failed", + "summary": message, + "schema": "ToolResultV1", + "schema_version": 1, + "structured_content": null, + "resources": [], + "citations": [], + "error": { + "schema": "AgentErrorV1", + "schema_version": 1, + "code": code, + "category": category, + "stage": "tool", + "message": message, + "retryable": retryable, + "retry_after_ms": null, + "effect_state": "none", + "recovery_action": recovery, + }, + "usage": null, + "truncated": false, + "next_cursor": null, + "effect_receipt_ref": null, + }) +} + +/// Seed stub specs from a CALL allowlist (args.tools). +pub fn seed_from_allowlist_args(args: &Value) -> Result { + let tools = args + .get("tools") + .ok_or_else(|| "tools.seed_allowlist requires tools".to_string())?; + seed_from_allowlist(tools) +} + +fn seed_from_allowlist(tools: &Value) -> Result { + let names = crate::tool_names(tools); + let mut specs = Vec::new(); + for name in names { + // Minimal stub if not already registered — CALL whitelist compatibility. + let already = { + let guard = registry() + .lock() + .map_err(|_| "tools registry lock poisoned".to_string())?; + guard.contains_key(&name) + }; + if already { + continue; + } + let mut m = Map::new(); + m.insert("id".into(), json!(name)); + m.insert("version".into(), json!("1")); + m.insert( + "description".into(), + json!(format!("Allowlist-derived tool `{name}`")), + ); + m.insert( + "input_schema".into(), + json!({"type":"object","properties":{},"additionalProperties":true}), + ); + m.insert("effect".into(), json!("execute")); + m.insert("scopes".into(), json!(["call:allowlist"])); + m.insert("availability".into(), json!("ready")); + specs.push(Value::Object(m)); + } + if specs.is_empty() { + return Ok(json!({"ok": true, "registered": [], "count": 0})); + } + tools_register(&json!({"specs": specs})) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn register_search_describe_and_forbid() { + let _ = tools_clear(&json!({})); + let reg = tools_register_eng_defaults(&json!({})).unwrap(); + assert_eq!(reg["count"], 5); + + let allow = json!(["tool_find", "tool_reuse"]); + let search = tools_search(&json!({"tools": allow, "query": "find"})).unwrap(); + assert_eq!(search["count"], 1); + assert_eq!(search["items"][0]["id"], "tool_find"); + + // Unauthorized tool must not appear. + let search2 = tools_search(&json!({"tools": allow, "query": "bind"})).unwrap(); + assert_eq!(search2["count"], 0); + + let denied = tools_describe(&json!({"id": "tool_bind", "tools": allow})).unwrap(); + assert_eq!(denied["authorized"], false); + assert_eq!(denied["ok"], false); + + let ok = tools_describe(&json!({"id": "tool_find", "tools": allow})).unwrap(); + assert_eq!(ok["found"], true); + assert_eq!(ok["spec"]["schema"], "ToolSpecV1"); + } + + #[test] + fn prepare_rejects_bad_args_and_unauthorized() { + let _ = tools_clear(&json!({})); + tools_register_eng_defaults(&json!({})).unwrap(); + let allow = json!(["tool_find"]); + + let bad = tools_prepare_call(&json!({ + "tool_id": "tool_find", + "tools": allow, + "arguments": {} + })) + .unwrap(); + assert_eq!(bad["ok"], false); + assert_eq!(bad["error"]["category"], "invalid_arguments"); + + let unauth = tools_prepare_call(&json!({ + "tool_id": "tool_bind", + "tools": allow, + "arguments": {"query": "x"} + })) + .unwrap(); + assert_eq!(unauth["ok"], false); + assert_eq!(unauth["error"]["category"], "forbidden"); + + let good = tools_prepare_call(&json!({ + "tool_id": "tool_find", + "tools": allow, + "arguments": {"query": "foo"}, + "call_id": "c1" + })) + .unwrap(); + assert_eq!(good["ok"], true); + assert_eq!(good["call"]["schema"], "ToolCallV1"); + assert_eq!(good["call"]["tool_id"], "tool_find"); + } + + #[test] + fn refuse_unsupported_schema_keywords() { + let err = tools_register(&json!({ + "id": "bad", + "input_schema": { + "type": "object", + "oneOf": [{"type": "object"}] + } + })); + assert!(err.is_err()); + } +} diff --git a/src/workbench/capabilities.rs b/src/workbench/capabilities.rs index 4c1a766..5736cb4 100644 --- a/src/workbench/capabilities.rs +++ b/src/workbench/capabilities.rs @@ -117,11 +117,11 @@ pub fn probe_capabilities(params: &Value) -> Value { features.insert("view.document".into(), json!(0)); features.insert("view.reference_resolve".into(), json!(0)); } - // M-A0/M-A1/M-A3: protocol capability bits. error/checkpoint open after emitters land. + // M-A0–M-A3: protocol capability bits (tool_schema after M-A2 registry). features.insert("agent.error_v1".into(), json!(1)); features.insert("agent.checkpoint_v2".into(), json!(1)); + features.insert("agent.tool_schema_v1".into(), json!(1)); for (k, v) in [ - ("agent.tool_schema_v1", 0), ("agent.output_channels_v1", 0), ("agent.context_pack_v2", 0), ] { @@ -249,7 +249,7 @@ mod tests { assert_eq!(caps["features"]["llm.messages"], 0); assert_eq!(caps["features"]["agent.error_v1"], 1); assert_eq!(caps["features"]["agent.checkpoint_v2"], 1); - assert_eq!(caps["features"]["agent.tool_schema_v1"], 0); + assert_eq!(caps["features"]["agent.tool_schema_v1"], 1); assert_eq!(caps["features"]["agent.output_channels_v1"], 0); assert_eq!(caps["features"]["agent.context_pack_v2"], 0); #[cfg(feature = "view")] diff --git a/tests/workbench_contracts.rs b/tests/workbench_contracts.rs index 9324171..573031e 100644 --- a/tests/workbench_contracts.rs +++ b/tests/workbench_contracts.rs @@ -182,16 +182,13 @@ fn ma0_agent_reliability_protocol_freeze() { let caps = mlsp("capabilities", serde_json::json!({})); assert_eq!(caps["ok"], true, "{caps}"); let features = &caps["result"]["features"]; - for bit in [ - "agent.tool_schema_v1", - "agent.output_channels_v1", - "agent.context_pack_v2", - ] { + for bit in ["agent.output_channels_v1", "agent.context_pack_v2"] { assert_eq!(features[bit], 0, "{bit} must stay 0 until emitters land"); } - // M-A1/M-A3: error + checkpoint + resource view emitters are live. + // M-A1–M-A3: error + checkpoint + tool schema + resource view emitters are live. assert_eq!(features["agent.error_v1"], 1); assert_eq!(features["agent.checkpoint_v2"], 1); + assert_eq!(features["agent.tool_schema_v1"], 1); assert_eq!(features["resource.view_v1"], 1); let formats = caps["result"]["extract_formats"] @@ -222,6 +219,7 @@ fn ma0_agent_reliability_protocol_freeze() { ); assert_eq!(down["result"]["features"]["agent.error_v1"], 1); assert_eq!(down["result"]["features"]["agent.checkpoint_v2"], 1); + assert_eq!(down["result"]["features"]["agent.tool_schema_v1"], 1); assert_eq!(down["result"]["features"]["resource.view_v1"], 1); }