diff --git a/crates/ox-acp/src/lib.rs b/crates/ox-acp/src/lib.rs index efc0c3efe..330a1ab0b 100644 --- a/crates/ox-acp/src/lib.rs +++ b/crates/ox-acp/src/lib.rs @@ -79,6 +79,46 @@ mod tests { } } + struct DropNotifier(Option>); + + impl Drop for DropNotifier { + fn drop(&mut self) { + if let Some(tx) = self.0.take() { + _ = tx.send(()); + } + } + } + + struct BlockingTool { + started: std::sync::Mutex>>, + dropped: std::sync::Mutex>>, + } + + #[async_trait] + impl ox_core::tools::Tool for BlockingTool { + fn spec(&self) -> ox_core::message::ToolSpec { + ox_core::message::ToolSpec { + name: "block_forever".into(), + description: "Blocks until cancelled.".into(), + input_schema: json!({ "type": "object" }), + deferred: false, + } + } + + async fn execute( + &self, + _ctx: &ToolContext, + _args: Value, + ) -> std::result::Result { + if let Some(tx) = self.started.lock().unwrap().take() { + _ = tx.send(()); + } + let _guard = DropNotifier(self.dropped.lock().unwrap().take()); + std::future::pending::<()>().await; + Ok(ox_core::tools::ToolOutput::ok("unreachable")) + } + } + fn make_agent(wire: Arc, cwd: PathBuf) -> Agent { Agent::new( wire, @@ -292,6 +332,89 @@ mod tests { harness.finish().await } + #[tokio::test] + async fn multimodal_prompt_blocks_convert_and_reject_invalid_inputs() -> Result<()> { + let dir = TempDir::new()?; + let png_path = dir.path().join("chart.png"); + std::fs::write(&png_path, b"\x89PNG\r\n\x1a\nfake")?; + + let wire = scripted_wire(vec![Ok(vec![ + ResponseEvent::TextDelta("seen".to_owned()), + ResponseEvent::Done(StopReason::EndTurn), + ])]); + let mut harness = TestHarness::spawn_with_wire( + Arc::clone(&wire) as Arc, + dir.path().to_path_buf(), + ); + + harness.send_rpc(1, "initialize", None).await?; + let init = harness.read().await?; + let caps = &init["result"]["capabilities"]["promptCapabilities"]; + assert_eq!(caps["embeddedContext"], true); + assert_eq!(caps["image"], true); + assert_eq!(caps["audio"], true); + + let session_id = harness.new_session(2).await?; + + // Invalid embedded resource, non-file://, and remote-host resource_link return + // INVALID_PARAMS. + for (id, block) in [ + ( + 3, + json!({ "type": "resource", "resource": { "uri": "file:///a.txt" } }), + ), + ( + 4, + json!({ "type": "resource_link", "uri": "https://example.com/a.png" }), + ), + ( + 5, + json!({ "type": "resource_link", "uri": "file://remotehost/a.png" }), + ), + ] { + harness + .send_rpc( + id, + "session/prompt", + Some(json!({ "sessionId": session_id, "prompt": [block] })), + ) + .await?; + let err_resp = harness.read().await?; + assert_eq!(err_resp["error"]["code"], INVALID_PARAMS); + } + + // Valid multimodal prompt with all five block kinds succeeds with clean history. + let file_uri = format!("file://{}", png_path.display()); + harness + .send_rpc( + 6, + "session/prompt", + Some(json!({ + "sessionId": session_id, + "prompt": [ + { "type": "text", "text": "inspect" }, + { "type": "image", "data": "aW1n", "mimeType": "image/png" }, + { "type": "audio", "data": "YXVk", "mimeType": "audio/wav" }, + { "type": "resource", "resource": { "uri": "file:///note.md", "text": "ctx" } }, + { "type": "resource", "resource": { "uri": "file:///doc.pdf", "mimeType": "application/pdf", "blob": "cGRm" } }, + { "type": "resource_link", "uri": file_uri }, + ], + })), + ) + .await?; + _ = harness.read().await?; + let ok_resp = harness.read().await?; + assert_eq!(ok_resp["id"], 6); + assert_eq!(ok_resp["result"]["stopReason"], "end_turn"); + + let recorded = wire.recorded_requests(); + assert_eq!(recorded.len(), 1); + assert_eq!(recorded[0].messages.len(), 1); + assert_eq!(recorded[0].messages[0].content.len(), 6); + + harness.finish().await + } + #[tokio::test] async fn handles_jsonrpc_and_agent_errors() -> Result<()> { let mut harness = TestHarness::spawn_with_factory(|_cwd| Err(anyhow!("boom"))); @@ -370,6 +493,30 @@ mod tests { harness.finish().await } + #[tokio::test] + async fn prompt_agent_error_emits_internal_error() -> Result<()> { + let dir = TempDir::new()?; + let wire = scripted_wire(vec![Err(ClientError::StreamParse( + "upstream boom".to_owned(), + ))]); + let mut harness = TestHarness::spawn_with_wire(wire, dir.path().to_path_buf()); + + let session_id = harness.new_session(1).await?; + + harness + .send_rpc( + 2, + "session/prompt", + Some(json!({ "sessionId": session_id, "prompt": "fail" })), + ) + .await?; + let err_resp = harness.read().await?; + assert_eq!(err_resp["id"], 2); + assert_eq!(err_resp["error"]["code"], INTERNAL_ERROR); + + harness.finish().await + } + #[tokio::test] async fn suppresses_errors_for_notifications_and_handles_mid_prompt_shutdown() -> Result<()> { let dir = TempDir::new()?; @@ -468,30 +615,6 @@ mod tests { harness.finish().await } - #[tokio::test] - async fn prompt_agent_error_emits_internal_error() -> Result<()> { - let dir = TempDir::new()?; - let wire = scripted_wire(vec![Err(ClientError::StreamParse( - "upstream boom".to_owned(), - ))]); - let mut harness = TestHarness::spawn_with_wire(wire, dir.path().to_path_buf()); - - let session_id = harness.new_session(1).await?; - - harness - .send_rpc( - 2, - "session/prompt", - Some(json!({ "sessionId": session_id, "prompt": "fail" })), - ) - .await?; - let err_resp = harness.read().await?; - assert_eq!(err_resp["id"], 2); - assert_eq!(err_resp["error"]["code"], INTERNAL_ERROR); - - harness.finish().await - } - #[tokio::test] async fn stdin_eof_mid_prompt_cancels_and_ignores_in_flight_blank_lines() -> Result<()> { let dir = TempDir::new()?; @@ -518,46 +641,6 @@ mod tests { harness.finish().await } - struct DropNotifier(Option>); - - impl Drop for DropNotifier { - fn drop(&mut self) { - if let Some(tx) = self.0.take() { - _ = tx.send(()); - } - } - } - - struct BlockingTool { - started: std::sync::Mutex>>, - dropped: std::sync::Mutex>>, - } - - #[async_trait] - impl ox_core::tools::Tool for BlockingTool { - fn spec(&self) -> ox_core::message::ToolSpec { - ox_core::message::ToolSpec { - name: "block_forever".into(), - description: "Blocks until cancelled.".into(), - input_schema: json!({ "type": "object" }), - deferred: false, - } - } - - async fn execute( - &self, - _ctx: &ToolContext, - _args: Value, - ) -> std::result::Result { - if let Some(tx) = self.started.lock().unwrap().take() { - _ = tx.send(()); - } - let _guard = DropNotifier(self.dropped.lock().unwrap().take()); - std::future::pending::<()>().await; - Ok(ox_core::tools::ToolOutput::ok("unreachable")) - } - } - #[tokio::test] async fn session_cancel_cancels_in_flight_tool_execution() -> Result<()> { let dir = TempDir::new()?; @@ -626,87 +709,4 @@ mod tests { harness.finish().await } - - #[tokio::test] - async fn multimodal_prompt_blocks_convert_and_reject_invalid_inputs() -> Result<()> { - let dir = TempDir::new()?; - let png_path = dir.path().join("chart.png"); - std::fs::write(&png_path, b"\x89PNG\r\n\x1a\nfake")?; - - let wire = scripted_wire(vec![Ok(vec![ - ResponseEvent::TextDelta("seen".to_owned()), - ResponseEvent::Done(StopReason::EndTurn), - ])]); - let mut harness = TestHarness::spawn_with_wire( - Arc::clone(&wire) as Arc, - dir.path().to_path_buf(), - ); - - harness.send_rpc(1, "initialize", None).await?; - let init = harness.read().await?; - let caps = &init["result"]["capabilities"]["promptCapabilities"]; - assert_eq!(caps["embeddedContext"], true); - assert_eq!(caps["image"], true); - assert_eq!(caps["audio"], true); - - let session_id = harness.new_session(2).await?; - - // Invalid embedded resource, non-file://, and remote-host resource_link return - // INVALID_PARAMS. - for (id, block) in [ - ( - 3, - json!({ "type": "resource", "resource": { "uri": "file:///a.txt" } }), - ), - ( - 4, - json!({ "type": "resource_link", "uri": "https://example.com/a.png" }), - ), - ( - 5, - json!({ "type": "resource_link", "uri": "file://remotehost/a.png" }), - ), - ] { - harness - .send_rpc( - id, - "session/prompt", - Some(json!({ "sessionId": session_id, "prompt": [block] })), - ) - .await?; - let err_resp = harness.read().await?; - assert_eq!(err_resp["error"]["code"], INVALID_PARAMS); - } - - // Valid multimodal prompt with all five block kinds succeeds with clean history. - let file_uri = format!("file://{}", png_path.display()); - harness - .send_rpc( - 6, - "session/prompt", - Some(json!({ - "sessionId": session_id, - "prompt": [ - { "type": "text", "text": "inspect" }, - { "type": "image", "data": "aW1n", "mimeType": "image/png" }, - { "type": "audio", "data": "YXVk", "mimeType": "audio/wav" }, - { "type": "resource", "resource": { "uri": "file:///note.md", "text": "ctx" } }, - { "type": "resource", "resource": { "uri": "file:///doc.pdf", "mimeType": "application/pdf", "blob": "cGRm" } }, - { "type": "resource_link", "uri": file_uri }, - ], - })), - ) - .await?; - _ = harness.read().await?; - let ok_resp = harness.read().await?; - assert_eq!(ok_resp["id"], 6); - assert_eq!(ok_resp["result"]["stopReason"], "end_turn"); - - let recorded = wire.recorded_requests(); - assert_eq!(recorded.len(), 1); - assert_eq!(recorded[0].messages.len(), 1); - assert_eq!(recorded[0].messages[0].content.len(), 6); - - harness.finish().await - } } diff --git a/crates/ox-acp/src/prompt.rs b/crates/ox-acp/src/prompt.rs index c60d8f05a..995ea821a 100644 --- a/crates/ox-acp/src/prompt.rs +++ b/crates/ox-acp/src/prompt.rs @@ -118,6 +118,15 @@ impl PromptBlock { } } +fn filename_from_uri(uri: &str) -> Option { + let trimmed = uri.trim_end_matches('/'); + let segment = trimmed.split('/').next_back()?; + if segment.is_empty() { + return None; + } + percent_decode_uri(segment).or_else(|| Some(segment.to_owned())) +} + fn parse_file_uri(uri: &str) -> Result { let Some(rest) = uri.strip_prefix("file://") else { return Err(format!( @@ -138,15 +147,6 @@ fn parse_file_uri(uri: &str) -> Result { Ok(PathBuf::from(decoded)) } -fn filename_from_uri(uri: &str) -> Option { - let trimmed = uri.trim_end_matches('/'); - let segment = trimmed.split('/').next_back()?; - if segment.is_empty() { - return None; - } - percent_decode_uri(segment).or_else(|| Some(segment.to_owned())) -} - fn percent_decode_uri(input: &str) -> Option { let bytes = input.as_bytes(); let mut out = Vec::with_capacity(bytes.len()); diff --git a/plugins/ox-plugin-compaction/src/lib.rs b/plugins/ox-plugin-compaction/src/lib.rs index dc407c82a..5f7db2abb 100644 --- a/plugins/ox-plugin-compaction/src/lib.rs +++ b/plugins/ox-plugin-compaction/src/lib.rs @@ -106,6 +106,85 @@ struct HostCompleteResult { content: String, } +/// Serves NDJSON-RPC 2.0 plugin requests from `reader` and writes responses to `writer`. +pub async fn serve(reader: R, mut writer: W) -> Result<()> +where + R: AsyncRead + Unpin, + W: AsyncWrite + Unpin, +{ + let mut lines = BufReader::new(reader); + let mut max_tokens: Option = None; + let mut next_callback_id: u64 = 1; + + while let Some(line) = read_line(&mut lines) + .await + .context("failed to read JSON-RPC line")? + { + let req = match parse_request(&line) { + Ok(req) => req, + Err(err_resp) => { + write_message(&mut writer, &err_resp) + .await + .context("failed to write JSON-RPC error response")?; + continue; + } + }; + + let Some(id) = req.id else { + continue; + }; + + let params = req.params.unwrap_or(Value::Null); + let response = match req.method.as_str() { + "initialize" => match parse_initialize_params(params) { + Ok(parsed) => { + max_tokens = parsed.config.max_tokens; + Response::ok(id, plugin_manifest_json()) + } + Err(err) => Response::err(id, err), + }, + + "compaction/compact" => { + match handle_compaction( + params, + max_tokens, + &mut lines, + &mut writer, + &mut next_callback_id, + ) + .await + { + Ok(value) => Response::ok(id, value), + Err(err) => Response::err(id, err), + } + } + + "shutdown" => { + write_message(&mut writer, &Response::ok(id, json!({}))) + .await + .context("failed to write shutdown response")?; + break; + } + + other => Response::err(id, RpcError::method_not_found(other)), + }; + + write_message(&mut writer, &response) + .await + .context("failed to write JSON-RPC response")?; + } + + Ok(()) +} + +fn parse_initialize_params(params: Value) -> std::result::Result { + if params.is_null() { + return Ok(InitializeParams::default()); + } + serde_json::from_value(params) + .map_err(|err| RpcError::invalid_params(format!("invalid initialize params: {err}"))) +} + fn plugin_manifest_json() -> Value { json!({ "name": PLUGIN_NAME, @@ -116,6 +195,47 @@ fn plugin_manifest_json() -> Value { }) } +async fn handle_compaction( + params: Value, + max_tokens: Option, + lines: &mut R, + writer: &mut W, + next_callback_id: &mut u64, +) -> std::result::Result +where + R: AsyncBufRead + Unpin, + W: AsyncWrite + Unpin, +{ + let compact: CompactionParams = serde_json::from_value(params).map_err(|err| { + RpcError::invalid_params(format!("invalid compaction/compact params: {err}")) + })?; + + let is_incremental = compact.previous_summary.is_some(); + let system = default_compaction_prompt(is_incremental); + let prompt = format_transcript( + &compact.messages, + compact.focus.as_deref(), + compact.hook_guidance.as_deref(), + ); + + let callback_id = *next_callback_id; + *next_callback_id = next_callback_id.saturating_add(1); + + let completed = request_host_complete( + lines, + writer, + callback_id, + HostCompleteParams { + prompt, + system: Some(system), + max_tokens, + }, + ) + .await?; + + Ok(json!({ "summary": completed.content })) +} + fn default_compaction_prompt(is_incremental: bool) -> String { if is_incremental { formatdoc! {" @@ -136,14 +256,6 @@ fn default_compaction_prompt(is_incremental: bool) -> String { } } -fn truncate_chars(text: &str, max_chars: usize) -> String { - if text.chars().count() <= max_chars { - return text.to_owned(); - } - let prefix: String = text.chars().take(max_chars).collect(); - format!("{prefix}\n[truncated]") -} - fn format_transcript( messages: &[WireMessage], focus: Option<&str>, @@ -200,12 +312,12 @@ fn format_transcript( out } -fn parse_initialize_params(params: Value) -> std::result::Result { - if params.is_null() { - return Ok(InitializeParams::default()); +fn truncate_chars(text: &str, max_chars: usize) -> String { + if text.chars().count() <= max_chars { + return text.to_owned(); } - serde_json::from_value(params) - .map_err(|err| RpcError::invalid_params(format!("invalid initialize params: {err}"))) + let prefix: String = text.chars().take(max_chars).collect(); + format!("{prefix}\n[truncated]") } async fn request_host_complete( @@ -259,118 +371,6 @@ where } } -async fn handle_compaction( - params: Value, - max_tokens: Option, - lines: &mut R, - writer: &mut W, - next_callback_id: &mut u64, -) -> std::result::Result -where - R: AsyncBufRead + Unpin, - W: AsyncWrite + Unpin, -{ - let compact: CompactionParams = serde_json::from_value(params).map_err(|err| { - RpcError::invalid_params(format!("invalid compaction/compact params: {err}")) - })?; - - let is_incremental = compact.previous_summary.is_some(); - let system = default_compaction_prompt(is_incremental); - let prompt = format_transcript( - &compact.messages, - compact.focus.as_deref(), - compact.hook_guidance.as_deref(), - ); - - let callback_id = *next_callback_id; - *next_callback_id = next_callback_id.saturating_add(1); - - let completed = request_host_complete( - lines, - writer, - callback_id, - HostCompleteParams { - prompt, - system: Some(system), - max_tokens, - }, - ) - .await?; - - Ok(json!({ "summary": completed.content })) -} - -/// Serves NDJSON-RPC 2.0 plugin requests from `reader` and writes responses to `writer`. -pub async fn serve(reader: R, mut writer: W) -> Result<()> -where - R: AsyncRead + Unpin, - W: AsyncWrite + Unpin, -{ - let mut lines = BufReader::new(reader); - let mut max_tokens: Option = None; - let mut next_callback_id: u64 = 1; - - while let Some(line) = read_line(&mut lines) - .await - .context("failed to read JSON-RPC line")? - { - let req = match parse_request(&line) { - Ok(req) => req, - Err(err_resp) => { - write_message(&mut writer, &err_resp) - .await - .context("failed to write JSON-RPC error response")?; - continue; - } - }; - - let Some(id) = req.id else { - continue; - }; - - let params = req.params.unwrap_or(Value::Null); - let response = match req.method.as_str() { - "initialize" => match parse_initialize_params(params) { - Ok(parsed) => { - max_tokens = parsed.config.max_tokens; - Response::ok(id, plugin_manifest_json()) - } - Err(err) => Response::err(id, err), - }, - - "compaction/compact" => { - match handle_compaction( - params, - max_tokens, - &mut lines, - &mut writer, - &mut next_callback_id, - ) - .await - { - Ok(value) => Response::ok(id, value), - Err(err) => Response::err(id, err), - } - } - - "shutdown" => { - write_message(&mut writer, &Response::ok(id, json!({}))) - .await - .context("failed to write shutdown response")?; - break; - } - - other => Response::err(id, RpcError::method_not_found(other)), - }; - - write_message(&mut writer, &response) - .await - .context("failed to write JSON-RPC response")?; - } - - Ok(()) -} - #[cfg(test)] mod tests { use ox_core::message::Message; diff --git a/plugins/ox-plugin-mcp/src/config.rs b/plugins/ox-plugin-mcp/src/config.rs index 625270fbc..2ddb6f871 100644 --- a/plugins/ox-plugin-mcp/src/config.rs +++ b/plugins/ox-plugin-mcp/src/config.rs @@ -355,62 +355,6 @@ mod tests { assert_eq!(config.servers.len(), 2); } - #[test] - fn split_cli_spec_rejects_empty_name_or_value() { - let cases = ["=cmd", "name=", " = ", "missing_equals"]; - for spec in cases { - let err = split_cli_spec(spec).expect_err("invalid cli spec should fail"); - assert!( - matches!(err, ConfigError::InvalidCliSpec(ref raw) if raw == spec), - "unexpected error for `{spec}`: {err:?}" - ); - } - } - - #[test] - fn validate_rejects_invalid_server_configs() { - let stdio = |command: CommandSpec| { - McpServerConfig::Stdio(StdioServerConfig { - command, - args: Vec::new(), - env: BTreeMap::new(), - timeout_ms: None, - defer_tools: None, - }) - }; - let http = |url: &str| { - McpServerConfig::Http(HttpServerConfig { - url: url.to_owned(), - headers: BTreeMap::new(), - timeout_ms: None, - defer_tools: None, - }) - }; - - let cases = [ - ("", stdio(CommandSpec::Single("echo".to_owned()))), - ("bad__name", stdio(CommandSpec::Single("echo".to_owned()))), - ("bad:name", stdio(CommandSpec::Single("echo".to_owned()))), - ("empty_list", stdio(CommandSpec::List(Vec::new()))), - ("empty_exec", stdio(CommandSpec::Single(String::new()))), - ("bad_scheme", http("ftp://example.com")), - ]; - - for (name, server) in cases { - let mut servers = BTreeMap::new(); - servers.insert(name.to_owned(), server); - let config = McpConfig { - servers, - ..McpConfig::default() - }; - let err = config.validate().expect_err("invalid config should fail"); - assert!( - matches!(err, ConfigError::InvalidServer { name: ref n, .. } if n == name), - "unexpected error for `{name}`: {err:?}" - ); - } - } - #[test] fn defer_tools_defaults_to_true_and_supports_overrides() { assert!(McpConfig::default().defer_tools); @@ -466,4 +410,60 @@ mod tests { assert!(!eager_json.should_defer_tools(&eager_json.servers["git"])); assert!(eager_json.should_defer_tools(&eager_json.servers["remote"])); } + + #[test] + fn split_cli_spec_rejects_empty_name_or_value() { + let cases = ["=cmd", "name=", " = ", "missing_equals"]; + for spec in cases { + let err = split_cli_spec(spec).expect_err("invalid cli spec should fail"); + assert!( + matches!(err, ConfigError::InvalidCliSpec(ref raw) if raw == spec), + "unexpected error for `{spec}`: {err:?}" + ); + } + } + + #[test] + fn validate_rejects_invalid_server_configs() { + let stdio = |command: CommandSpec| { + McpServerConfig::Stdio(StdioServerConfig { + command, + args: Vec::new(), + env: BTreeMap::new(), + timeout_ms: None, + defer_tools: None, + }) + }; + let http = |url: &str| { + McpServerConfig::Http(HttpServerConfig { + url: url.to_owned(), + headers: BTreeMap::new(), + timeout_ms: None, + defer_tools: None, + }) + }; + + let cases = [ + ("", stdio(CommandSpec::Single("echo".to_owned()))), + ("bad__name", stdio(CommandSpec::Single("echo".to_owned()))), + ("bad:name", stdio(CommandSpec::Single("echo".to_owned()))), + ("empty_list", stdio(CommandSpec::List(Vec::new()))), + ("empty_exec", stdio(CommandSpec::Single(String::new()))), + ("bad_scheme", http("ftp://example.com")), + ]; + + for (name, server) in cases { + let mut servers = BTreeMap::new(); + servers.insert(name.to_owned(), server); + let config = McpConfig { + servers, + ..McpConfig::default() + }; + let err = config.validate().expect_err("invalid config should fail"); + assert!( + matches!(err, ConfigError::InvalidServer { name: ref n, .. } if n == name), + "unexpected error for `{name}`: {err:?}" + ); + } + } } diff --git a/plugins/ox-plugin-mcp/src/mcp.rs b/plugins/ox-plugin-mcp/src/mcp.rs index 330cb23a1..4c4caf278 100644 --- a/plugins/ox-plugin-mcp/src/mcp.rs +++ b/plugins/ox-plugin-mcp/src/mcp.rs @@ -134,50 +134,6 @@ impl McpClient { Ok(()) } - async fn paginate_list( - &self, - method: &str, - ignore_method_not_found: bool, - mut extract: F, - ) -> Result, McpError> - where - P: DeserializeOwned, - F: FnMut(P) -> (Vec, Option), - { - let mut cursor: Option = None; - let mut seen_cursors = HashSet::new(); - let mut items = Vec::new(); - - for _ in 0..MAX_LIST_PAGES { - let params = match &cursor { - Some(next) => json!({ "cursor": next }), - None => json!({}), - }; - let result = match self.request(method, params).await { - Ok(val) => val, - - Err(McpError::Rpc { - code: ox_jsonrpc::METHOD_NOT_FOUND, - .. - }) if ignore_method_not_found => return Ok(Vec::new()), - - Err(err) => return Err(err), - }; - let page: P = serde_json::from_value(result)?; - let (page_items, next_cursor) = extract(page); - items.extend(page_items); - match next_cursor { - Some(next) if !next.is_empty() && seen_cursors.insert(next.clone()) => { - cursor = Some(next); - } - - _ => break, - } - } - - Ok(items) - } - /// Discovers tools from the server via `tools/list` and namespaces them under `server_name`. pub async fn list_tools( &self, @@ -285,6 +241,50 @@ impl McpClient { } } + async fn paginate_list( + &self, + method: &str, + ignore_method_not_found: bool, + mut extract: F, + ) -> Result, McpError> + where + P: DeserializeOwned, + F: FnMut(P) -> (Vec, Option), + { + let mut cursor: Option = None; + let mut seen_cursors = HashSet::new(); + let mut items = Vec::new(); + + for _ in 0..MAX_LIST_PAGES { + let params = match &cursor { + Some(next) => json!({ "cursor": next }), + None => json!({}), + }; + let result = match self.request(method, params).await { + Ok(val) => val, + + Err(McpError::Rpc { + code: ox_jsonrpc::METHOD_NOT_FOUND, + .. + }) if ignore_method_not_found => return Ok(Vec::new()), + + Err(err) => return Err(err), + }; + let page: P = serde_json::from_value(result)?; + let (page_items, next_cursor) = extract(page); + items.extend(page_items); + match next_cursor { + Some(next) if !next.is_empty() && seen_cursors.insert(next.clone()) => { + cursor = Some(next); + } + + _ => break, + } + } + + Ok(items) + } + async fn request(&self, method: &str, params: Value) -> Result { match &self.transport { McpTransport::Stdio(stdio) => stdio.request(method, params).await, diff --git a/plugins/ox-plugin-mcp/src/mcp/http.rs b/plugins/ox-plugin-mcp/src/mcp/http.rs index 3568a480a..59a294215 100644 --- a/plugins/ox-plugin-mcp/src/mcp/http.rs +++ b/plugins/ox-plugin-mcp/src/mcp/http.rs @@ -51,24 +51,6 @@ impl HttpMcpClient { }) } - async fn post_json(&self, payload: &impl Serialize) -> Result { - let mut req = self - .client - .post(&self.url) - .header(reqwest::header::CONTENT_TYPE, "application/json") - .header( - reqwest::header::ACCEPT, - "application/json, text/event-stream", - ) - .json(payload); - - if let Some(session_id) = self.session_id.lock().await.as_ref() { - req = req.header("mcp-session-id", session_id); - } - - Ok(req.send().await?) - } - pub(super) async fn request(&self, method: &str, params: Value) -> Result { let id = self.next_id.fetch_add(1, Ordering::Relaxed); let payload = ox_jsonrpc::Request::new(id, method, params); @@ -120,6 +102,24 @@ impl HttpMcpClient { } Ok(()) } + + async fn post_json(&self, payload: &impl Serialize) -> Result { + let mut req = self + .client + .post(&self.url) + .header(reqwest::header::CONTENT_TYPE, "application/json") + .header( + reqwest::header::ACCEPT, + "application/json, text/event-stream", + ) + .json(payload); + + if let Some(session_id) = self.session_id.lock().await.as_ref() { + req = req.header("mcp-session-id", session_id); + } + + Ok(req.send().await?) + } } fn parse_sse_json_rpc(body: &str, expected_id: u64) -> Result { diff --git a/plugins/ox-plugin-stats/src/lib.rs b/plugins/ox-plugin-stats/src/lib.rs index 4f234d236..1627d0667 100644 --- a/plugins/ox-plugin-stats/src/lib.rs +++ b/plugins/ox-plugin-stats/src/lib.rs @@ -36,10 +36,10 @@ impl StatsRange { /// Parses a `/stats` argument string into a [`StatsRange`]. pub fn parse(raw: &str) -> Result { match raw.trim().to_ascii_lowercase().as_str() { - "" | "all" => Ok(Self::All), "day" => Ok(Self::Day), "week" => Ok(Self::Week), "month" => Ok(Self::Month), + "" | "all" => Ok(Self::All), other => Err(format!( "invalid range {other:?}: expected one of day, week, month, all" )), @@ -122,18 +122,74 @@ struct CommandInvokeParams { context: CommandContext, } -fn stats_command_json() -> Value { - json!({ - "name": "stats", - "description": "Show token usage and cost summary from the state database", - "arguments": [ - { - "name": "range", - "description": "Time window: day, week, month, or all (default: all)", - "required": false +/// Serves NDJSON-RPC 2.0 plugin requests from `reader` and writes responses to `writer`. +pub async fn serve(reader: R, mut writer: W) -> Result<()> +where + R: AsyncRead + Unpin, + W: AsyncWrite + Unpin, +{ + let mut lines = BufReader::new(reader); + let mut init_db_path: Option = None; + + while let Some(line) = read_line(&mut lines) + .await + .context("failed to read JSON-RPC line")? + { + let req = match parse_request(&line) { + Ok(req) => req, + Err(err_resp) => { + write_message(&mut writer, &err_resp) + .await + .context("failed to write JSON-RPC error response")?; + continue; } - ] - }) + }; + + let Some(id) = req.id else { + continue; + }; + + let params = req.params.unwrap_or(Value::Null); + let response = match req.method.as_str() { + "initialize" => match parse_initialize_params(params) { + Ok(parsed) => { + init_db_path = parsed.state_db_path; + Response::ok(id, plugin_manifest_json()) + } + Err(err) => Response::err(id, err), + }, + + "command/list" => Response::ok(id, json!({ "commands": [stats_command_json()] })), + + "command/invoke" => match handle_command_invoke(params, init_db_path.as_ref()) { + Ok(value) => Response::ok(id, value), + Err(err) => Response::err(id, err), + }, + + "shutdown" => { + write_message(&mut writer, &Response::ok(id, json!({}))) + .await + .context("failed to write shutdown response")?; + break; + } + + other => Response::err(id, RpcError::method_not_found(other)), + }; + + write_message(&mut writer, &response) + .await + .context("failed to write JSON-RPC response")?; + } + + Ok(()) +} + +fn parse_initialize_params(params: Value) -> std::result::Result { + if params.is_null() { + return Ok(InitializeParams::default()); + } + serde_json::from_value(params) + .map_err(|err| RpcError::invalid_params(format!("invalid initialize params: {err}"))) } fn plugin_manifest_json() -> Value { @@ -152,18 +208,50 @@ fn plugin_manifest_json() -> Value { }) } -fn default_state_db_path() -> Option { - if let Some(dir) = std::env::var_os("XDG_STATE_HOME").filter(|v| !v.is_empty()) { - return Some(PathBuf::from(dir).join("ox").join("state.db")); +fn stats_command_json() -> Value { + json!({ + "name": "stats", + "description": "Show token usage and cost summary from the state database", + "arguments": [ + { + "name": "range", + "description": "Time window: day, week, month, or all (default: all)", + "required": false + } + ] + }) +} + +fn handle_command_invoke( + params: Value, + init_db_path: Option<&PathBuf>, +) -> std::result::Result { + let invoke: CommandInvokeParams = serde_json::from_value(params) + .map_err(|err| RpcError::invalid_params(format!("invalid command/invoke params: {err}")))?; + + if invoke.name != "stats" { + return Err(RpcError::invalid_params(format!( + "unknown command: {}", + invoke.name + ))); } - let home = std::env::var_os("HOME").filter(|v| !v.is_empty())?; - Some( - PathBuf::from(home) - .join(".local") - .join("state") - .join("ox") - .join("state.db"), - ) + + let range = StatsRange::parse(&invoke.args).map_err(RpcError::invalid_params)?; + let db_path = resolve_db_path(invoke.context.state_db_path.as_ref(), init_db_path) + .ok_or_else(|| RpcError::internal_error("could not resolve state database path"))?; + + let summary = query_usage_since(&db_path, range.since_ms(now_millis())).map_err(|err| { + RpcError::internal_error(format!( + "failed to query state database {}: {err}", + db_path.display() + )) + })?; + + Ok(json!({ + "content": format_usage_markdown(range, &summary), + "description": format!("Usage summary ({})", range.label()), + "mode": "markdown" + })) } fn resolve_db_path(context_path: Option<&PathBuf>, init_path: Option<&PathBuf>) -> Option { @@ -181,11 +269,18 @@ fn resolve_db_path(context_path: Option<&PathBuf>, init_path: Option<&PathBuf>) default_state_db_path() } -fn now_millis() -> i64 { - let millis = SystemTime::now() - .duration_since(UNIX_EPOCH) - .map_or(0, |d| d.as_millis()); - i64::try_from(millis).unwrap_or(i64::MAX) +fn default_state_db_path() -> Option { + if let Some(dir) = std::env::var_os("XDG_STATE_HOME").filter(|v| !v.is_empty()) { + return Some(PathBuf::from(dir).join("ox").join("state.db")); + } + let home = std::env::var_os("HOME").filter(|v| !v.is_empty())?; + Some( + PathBuf::from(home) + .join(".local") + .join("state") + .join("ox") + .join("state.db"), + ) } fn query_usage_since( @@ -259,12 +354,11 @@ fn query_usage_since( Ok(summary) } -fn format_cost_usd(cost_micros: i64) -> String { - let sign = if cost_micros < 0 { "-" } else { "" }; - let abs = cost_micros.unsigned_abs(); - let dollars = abs / 1_000_000; - let frac = (abs % 1_000_000) / 100; - format!("{sign}${dollars}.{frac:04}") +fn now_millis() -> i64 { + let millis = SystemTime::now() + .duration_since(UNIX_EPOCH) + .map_or(0, |d| d.as_millis()); + i64::try_from(millis).unwrap_or(i64::MAX) } /// Renders a [`UsageSummary`] for `range` as a Markdown report. @@ -312,106 +406,12 @@ pub fn format_usage_markdown(range: StatsRange, summary: &UsageSummary) -> Strin out } -fn parse_initialize_params(params: Value) -> std::result::Result { - if params.is_null() { - return Ok(InitializeParams::default()); - } - serde_json::from_value(params) - .map_err(|err| RpcError::invalid_params(format!("invalid initialize params: {err}"))) -} - -fn handle_command_invoke( - params: Value, - init_db_path: Option<&PathBuf>, -) -> std::result::Result { - let invoke: CommandInvokeParams = serde_json::from_value(params) - .map_err(|err| RpcError::invalid_params(format!("invalid command/invoke params: {err}")))?; - - if invoke.name != "stats" { - return Err(RpcError::invalid_params(format!( - "unknown command: {}", - invoke.name - ))); - } - - let range = StatsRange::parse(&invoke.args).map_err(RpcError::invalid_params)?; - let db_path = resolve_db_path(invoke.context.state_db_path.as_ref(), init_db_path) - .ok_or_else(|| RpcError::internal_error("could not resolve state database path"))?; - - let summary = query_usage_since(&db_path, range.since_ms(now_millis())).map_err(|err| { - RpcError::internal_error(format!( - "failed to query state database {}: {err}", - db_path.display() - )) - })?; - - Ok(json!({ - "content": format_usage_markdown(range, &summary), - "description": format!("Usage summary ({})", range.label()), - "mode": "markdown" - })) -} - -/// Serves NDJSON-RPC 2.0 plugin requests from `reader` and writes responses to `writer`. -pub async fn serve(reader: R, mut writer: W) -> Result<()> -where - R: AsyncRead + Unpin, - W: AsyncWrite + Unpin, -{ - let mut lines = BufReader::new(reader); - let mut init_db_path: Option = None; - - while let Some(line) = read_line(&mut lines) - .await - .context("failed to read JSON-RPC line")? - { - let req = match parse_request(&line) { - Ok(req) => req, - Err(err_resp) => { - write_message(&mut writer, &err_resp) - .await - .context("failed to write JSON-RPC error response")?; - continue; - } - }; - - let Some(id) = req.id else { - continue; - }; - - let params = req.params.unwrap_or(Value::Null); - let response = match req.method.as_str() { - "initialize" => match parse_initialize_params(params) { - Ok(parsed) => { - init_db_path = parsed.state_db_path; - Response::ok(id, plugin_manifest_json()) - } - Err(err) => Response::err(id, err), - }, - - "command/list" => Response::ok(id, json!({ "commands": [stats_command_json()] })), - - "command/invoke" => match handle_command_invoke(params, init_db_path.as_ref()) { - Ok(value) => Response::ok(id, value), - Err(err) => Response::err(id, err), - }, - - "shutdown" => { - write_message(&mut writer, &Response::ok(id, json!({}))) - .await - .context("failed to write shutdown response")?; - break; - } - - other => Response::err(id, RpcError::method_not_found(other)), - }; - - write_message(&mut writer, &response) - .await - .context("failed to write JSON-RPC response")?; - } - - Ok(()) +fn format_cost_usd(cost_micros: i64) -> String { + let sign = if cost_micros < 0 { "-" } else { "" }; + let abs = cost_micros.unsigned_abs(); + let dollars = abs / 1_000_000; + let frac = (abs % 1_000_000) / 100; + format!("{sign}${dollars}.{frac:04}") } #[cfg(test)] @@ -440,23 +440,6 @@ mod tests { serde_json::from_str(&line).expect("response should be valid JSON-RPC") } - #[test] - fn parse_range_accepts_known_values_and_rejects_unknown() { - assert_eq!(StatsRange::parse(""), Ok(StatsRange::All)); - assert_eq!(StatsRange::parse("all"), Ok(StatsRange::All)); - assert_eq!(StatsRange::parse("DAY"), Ok(StatsRange::Day)); - assert_eq!(StatsRange::parse(" week "), Ok(StatsRange::Week)); - assert_eq!(StatsRange::parse("month"), Ok(StatsRange::Month)); - assert!(StatsRange::parse("year").is_err()); - } - - #[test] - fn format_usage_markdown_handles_empty_summary() { - let rendered = format_usage_markdown(StatsRange::Day, &UsageSummary::default()); - assert!(rendered.contains("Last 24 Hours")); - assert!(rendered.contains("No usage events recorded")); - } - fn seed_state_store() -> (TempDir, std::path::PathBuf) { let dir = TempDir::new().expect("tempdir should be created"); let db_path = dir.path().join("state.db"); @@ -496,6 +479,23 @@ mod tests { (dir, db_path) } + #[test] + fn parse_range_accepts_known_values_and_rejects_unknown() { + assert_eq!(StatsRange::parse(""), Ok(StatsRange::All)); + assert_eq!(StatsRange::parse("all"), Ok(StatsRange::All)); + assert_eq!(StatsRange::parse("DAY"), Ok(StatsRange::Day)); + assert_eq!(StatsRange::parse(" week "), Ok(StatsRange::Week)); + assert_eq!(StatsRange::parse("month"), Ok(StatsRange::Month)); + assert!(StatsRange::parse("year").is_err()); + } + + #[test] + fn format_usage_markdown_handles_empty_summary() { + let rendered = format_usage_markdown(StatsRange::Day, &UsageSummary::default()); + assert!(rendered.contains("Last 24 Hours")); + assert!(rendered.contains("No usage events recorded")); + } + #[tokio::test] async fn serve_end_to_end_queries_seeded_state_store() { let (_dir, db_path) = seed_state_store();