The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(server): handle missing tool parameters gracefully
Steven Enamakel94f48a7d18d2
diff --git a/crates/openhuman-core/src/mcp/server/tools/params.rs b/crates/openhuman-core/src/mcp/server/tools/params.rsindex e57a5d733d..51501162df 100644--- a/crates/openhuman-core/src/mcp/server/tools/params.rs+++ b/crates/openhuman-core/src/mcp/server/tools/params.rs@@ -1,9 +1,16 @@use serde_json::{Map, Value};+use tinymcp::server::args::{+ object_arguments, optional_i64, optional_non_empty_string, optional_positive_u64,+ optional_string_array, optional_u64, positive_u64_or_default, reject_unexpected_arguments,+ required_non_empty_string, required_non_empty_string_array,+};+use tinymcp::ToolCallError;+use crate::core::all;use super::types::{- McpToolSpec, ToolCallError, DEFAULT_LIMIT, MAX_LIMIT, MEMORY_NOTE_ARGUMENTS,+ McpToolSpec, DEFAULT_LIMIT, MAX_LIMIT, MEMORY_NOTE_ARGUMENTS,MEMORY_STORE_ARGUMENTS, QUERY_ARGUMENTS, SEARCH_MAX_RESULTS, SEARXNG_SEARCH_ARGUMENTS,SUBAGENT_RUN_ARGUMENTS, TREE_BROWSE_ARGUMENTS, TREE_LIST_SOURCES_ARGUMENTS,TREE_READ_CHUNK_ARGUMENTS, TREE_TAG_ARGUMENTS, TREE_TAG_MAX_TAGS, TREE_TAG_MAX_TAG_LENGTH,@@ -33,7 +40,7 @@ pub fn build_rpc_params("memory.search" | "memory.recall" => {reject_unexpected_arguments(&args, QUERY_ARGUMENTS)?;let query = required_non_empty_string(&args, "query")?;- let limit = optional_limit(&args)?;+ let limit = positive_u64_or_default(&args, "k", DEFAULT_LIMIT, MAX_LIMIT)?;Ok(Map::from_iter([("query".to_string(), Value::String(query)),("k".to_string(), Value::from(limit)),@@ -49,7 +56,7 @@ pub fn build_rpc_params(let query = required_non_empty_string(&args, "query")?;let mut params = Map::new();params.insert("query".to_string(), Value::String(query));- if let Some(max_results) = optional_max_results(&args, "max_results")? {+ if let Some(max_results) = optional_positive_u64(&args, "max_results", SEARCH_MAX_RESULTS as u64)? {params.insert("max_results".to_string(), Value::from(max_results));}if let Some(provider) = optional_non_empty_string(&args, "provider")? {@@ -88,7 +95,7 @@ pub fn build_rpc_params(// controller itself accepts up to 1000, but the MCP layer keeps// the surface narrow so the LLM doesn't waste tokens pulling a// huge page.- params.insert("limit".to_string(), Value::from(optional_limit(&args)?));+ params.insert("limit".to_string(), Value::from(positive_u64_or_default(&args, "k", DEFAULT_LIMIT, MAX_LIMIT)?));if let Some(values) = optional_string_array(&args, "source_kinds")? {params.insert("source_kinds".to_string(), Value::from(values));}@@ -117,7 +124,7 @@ pub fn build_rpc_params(// The controller's `limit` is required; default + cap at the MCP// layer so the LLM doesn't have to know the underlying contract.let mut params = Map::new();- params.insert("limit".to_string(), Value::from(optional_limit(&args)?));+ params.insert("limit".to_string(), Value::from(positive_u64_or_default(&args, "k", DEFAULT_LIMIT, MAX_LIMIT)?));if let Some(value) = optional_non_empty_string(&args, "kind")? {params.insert("kind".to_string(), Value::String(value));}@@ -239,224 +246,6 @@ pub fn build_rpc_params(}}-pub fn reject_unexpected_arguments(- args: &Map<String, Value>,- allowed: &[&str],-) -> Result<(), ToolCallError> {- let mut unexpected = args- .keys()- .filter(|key| !allowed.contains(&key.as_str()))- .cloned()- .collect::<Vec<_>>();- if unexpected.is_empty() {- return Ok(());- }- unexpected.sort();- Err(ToolCallError::InvalidParams(format!(- "unexpected argument `{}`",- unexpected.join("`, `")- )))-}--pub fn object_arguments(arguments: Value) -> Result<Map<String, Value>, ToolCallError> {- match arguments {- Value::Null => Ok(Map::new()),- Value::Object(map) => Ok(map),- other => Err(ToolCallError::InvalidParams(format!(- "tools/call arguments must be an object, got {}",- json_type_name(&other)- ))),- }-}--pub fn required_non_empty_string(- args: &Map<String, Value>,- key: &str,-) -> Result<String, ToolCallError> {- let raw = args.get(key).and_then(Value::as_str).ok_or_else(|| {- ToolCallError::InvalidParams(format!("missing required argument `{key}`"))- })?;- let trimmed = raw.trim();- if trimmed.is_empty() {- return Err(ToolCallError::InvalidParams(format!(- "argument `{key}` must not be empty"- )));- }- Ok(trimmed.to_string())-}--pub fn optional_non_empty_string(- args: &Map<String, Value>,- key: &str,-) -> Result<Option<String>, ToolCallError> {- let Some(value) = args.get(key) else {- return Ok(None);- };- if value.is_null() {- return Ok(None);- }- let Some(raw) = value.as_str() else {- return Err(ToolCallError::InvalidParams(format!(- "argument `{key}` must be a string"- )));- };- let trimmed = raw.trim();- if trimmed.is_empty() {- // Distinguish "absent" (Ok(None)) from "present but blank" — the- // latter is a client bug worth surfacing so the LLM can drop the- // field entirely on the next call instead of resending whitespace.- return Err(ToolCallError::InvalidParams(format!(- "argument `{key}` must not be empty when provided"- )));- }- Ok(Some(trimmed.to_string()))-}--pub fn optional_string_array(- args: &Map<String, Value>,- key: &str,-) -> Result<Option<Vec<String>>, ToolCallError> {- let Some(value) = args.get(key) else {- return Ok(None);- };- if value.is_null() {- return Ok(None);- }- let Some(items) = value.as_array() else {- return Err(ToolCallError::InvalidParams(format!(- "argument `{key}` must be an array of strings, got {}",- json_type_name(value)- )));- };- let mut out = Vec::with_capacity(items.len());- let mut dropped_blank = 0usize;- for item in items {- let Some(s) = item.as_str() else {- return Err(ToolCallError::InvalidParams(format!(- "argument `{key}` must contain only strings, got {} entry",- json_type_name(item)- )));- };- let trimmed = s.trim();- if trimmed.is_empty() {- dropped_blank += 1;- continue;- }- out.push(trimmed.to_string());- }- if dropped_blank > 0 {- // Visibility for the silent-drop behaviour: callers don't see how many- // entries were skipped, and a downstream "the filter didn't match"- // bug is much faster to triage when this trace is in the log.- log::trace!(- "[mcp_server] optional_string_array key={key} dropped_blank_entries={dropped_blank}"- );- }- Ok(Some(out))-}--/// Variant of [`optional_string_array`] that errors when the field is-/// absent, null, or resolves to an empty list after blank-trim.-///-/// Used by tools where supplying an empty `tags: []` is a no-op the-/// caller almost certainly didn't mean (e.g. `tree.tag`). The MCP layer-/// rejects it up-front instead of letting it through to the document-/// RPC where the failure mode is silent.-pub fn required_non_empty_string_array(- args: &Map<String, Value>,- key: &str,-) -> Result<Vec<String>, ToolCallError> {- let trimmed = optional_string_array(args, key)?.ok_or_else(|| {- ToolCallError::InvalidParams(format!("missing required argument `{key}`"))- })?;- if trimmed.is_empty() {- return Err(ToolCallError::InvalidParams(format!(- "argument `{key}` must contain at least one non-empty string"- )));- }- Ok(trimmed)-}--pub fn optional_i64(args: &Map<String, Value>, key: &str) -> Result<Option<i64>, ToolCallError> {- let Some(value) = args.get(key) else {- return Ok(None);- };- if value.is_null() {- return Ok(None);- }- value.as_i64().map(Some).ok_or_else(|| {- ToolCallError::InvalidParams(format!(- "argument `{key}` must be an integer in the i64 range"- ))- })-}--pub fn optional_u64(args: &Map<String, Value>, key: &str) -> Result<Option<u64>, ToolCallError> {- let Some(value) = args.get(key) else {- return Ok(None);- };- if value.is_null() {- return Ok(None);- }- value.as_u64().map(Some).ok_or_else(|| {- ToolCallError::InvalidParams(format!("argument `{key}` must be a non-negative integer"))- })-}--pub fn optional_limit(args: &Map<String, Value>) -> Result<u64, ToolCallError> {- let Some(value) = args.get("k") else {- return Ok(DEFAULT_LIMIT);- };- let Some(limit) = value.as_u64() else {- return Err(ToolCallError::InvalidParams(- "argument `k` must be a positive integer".to_string(),- ));- };- if limit == 0 {- return Err(ToolCallError::InvalidParams(- "argument `k` must be greater than zero".to_string(),- ));- }- if limit > MAX_LIMIT {- // Reject explicitly instead of silently clamping. The schema advertises- // `maximum: MAX_LIMIT`, so a higher value is a client bug; surfacing it- // lets the LLM self-correct on the next call instead of believing it- // received the page size it asked for.- return Err(ToolCallError::InvalidParams(format!(- "argument `k` must not exceed {MAX_LIMIT} (got {limit})"- )));- }- Ok(limit)-}--pub fn optional_max_results(- args: &Map<String, Value>,- key: &str,-) -> Result<Option<u64>, ToolCallError> {- let Some(value) = args.get(key) else {- return Ok(None);- };- if value.is_null() {- return Ok(None);- }- let Some(limit) = value.as_u64() else {- return Err(ToolCallError::InvalidParams(format!(- "argument `{key}` must be a positive integer"- )));- };- if limit == 0 {- return Err(ToolCallError::InvalidParams(format!(- "argument `{key}` must be greater than zero"- )));- }- if limit > SEARCH_MAX_RESULTS as u64 {- return Err(ToolCallError::InvalidParams(format!(- "argument `{key}` must not exceed {SEARCH_MAX_RESULTS} (got {limit})"- )));- }- Ok(Some(limit))-}-pub fn validate_controller_params(spec: &McpToolSpec,params: &Map<String, Value>,@@ -524,14 +313,3 @@ pub fn slug_from(title: &str) -> String {}result}--pub fn json_type_name(value: &Value) -> &'static str {- match value {- Value::Null => "null",- Value::Bool(_) => "bool",- Value::Number(_) => "number",- Value::String(_) => "string",- Value::Array(_) => "array",- Value::Object(_) => "object",- }-}diff --git a/crates/openhuman-core/src/mcp/server/tools/types.rs b/crates/openhuman-core/src/mcp/server/tools/types.rsindex da492086c6..6c8df5aff1 100644--- a/crates/openhuman-core/src/mcp/server/tools/types.rs+++ b/crates/openhuman-core/src/mcp/server/tools/types.rs@@ -52,40 +52,3 @@ pub struct McpToolSpec {/// only when `readOnlyHint == false`, so read-only tools omit them.pub annotations: Value,}--#[derive(Debug, Clone, PartialEq, Eq)]-pub enum ToolCallError {- /// Client-side problem: malformed arguments, unknown tool, validation- /// failure. Maps to JSON-RPC `-32602 Invalid params`.- InvalidParams(String),- /// Server-side problem outside the caller's control: config load failure,- /// missing platform resources. Maps to JSON-RPC `-32603 Internal error`.- /// Kept distinct from `InvalidParams` so MCP clients don't display- /// internal failures as if the user supplied bad arguments.- Internal(String),-}--impl ToolCallError {- pub fn message(&self) -> &str {- match self {- Self::InvalidParams(message) | Self::Internal(message) => message,- }- }-- /// JSON-RPC error code corresponding to this variant.- pub fn code(&self) -> i64 {- match self {- Self::InvalidParams(_) => -32602,- Self::Internal(_) => -32603,- }- }-- /// JSON-RPC error `message` field (short, spec-canonical phrase). The- /// human-readable detail belongs in the response's `data` field.- pub fn jsonrpc_message(&self) -> &'static str {- match self {- Self::InvalidParams(_) => "Invalid params",- Self::Internal(_) => "Internal error",- }- }-}