diff --git a/docs/api-coverage.md b/docs/api-coverage.md index 52e2e2a..beb0b72 100644 --- a/docs/api-coverage.md +++ b/docs/api-coverage.md @@ -72,6 +72,7 @@ one from the CLI, or reuse the UUID supplied with `--idempotency-key`. | `GET /v1/gateway/search` | `connections search QUERY` | | `POST /v1/gateway/describe` | `connections describe ID TOOL` | | `POST /v1/gateway/call` | `connections call ID TOOL --arguments JSON` | +| `POST /mcp` (JSON-RPC `tools/list`) | `mcp tools [NAME]` | Auth commands use `/v1/auth/device/code`, `/device/token`, `/get-session`, and `/sign-out`. Organization commands use Better Auth's `/v1/auth/organization/*` routes; organization diff --git a/docs/cli-reference.md b/docs/cli-reference.md index f1e7218..b1d09a7 100644 --- a/docs/cli-reference.md +++ b/docs/cli-reference.md @@ -44,15 +44,16 @@ For example, use `adapt org members ls` or `adapt sandbox ls --all`. | `connections` | `list`, `get`, `create`, `update`, `delete`, `refresh`, `grant`, `oauth`, `oauth-complete`, `calls`, `principals`, `search`, `describe`, `call` | | `keys` | `list`, `create`, `delete` | | `sessions` | `list`, `revoke`, `revoke-others` | -| `mcp` | `list`, `revoke` | +| `mcp` | `list`, `revoke`, `tools` | | `events` | Show organization changes, or personal changes with `--personal` | | `health` | Test API availability, or database readiness with `--ready` | | `profiles` | Show saved API URLs, organizations, and credential status | | `api` | Send an authenticated request to a path on the selected API server | `connections` manages upstream MCP services. -`mcp` manages clients with permission to connect to Platform. -Named commands do not cover internal compute administration, OAuth provider internals, or the `/mcp` transport. +`mcp list` and `mcp revoke` manage clients with permission to connect to Platform. +`mcp tools` lists the tools that Platform's own MCP server provides. +Named commands do not cover internal compute administration, OAuth provider internals, or calling tools through `/mcp`. See [API coverage](api-coverage.md) for routes and API version details. ## Authentication and profiles @@ -516,6 +517,37 @@ To revoke the key, use `adapt keys delete KEY_ID`. Logout always uses the saved credential. It never revokes a key from `ADAPT_TOKEN`. +## Platform MCP tools + +Platform hosts an MCP server at `/mcp` on the API origin. +To list its built-in tools, run: + +```sh +adapt mcp tools +adapt mcp tools read_file +adapt mcp tools --json +``` + +A terminal shows each tool's name, access hint, and the first sentence of its description. +The access hint comes from the tool's annotations: `read-only`, `write`, or `destructive`. +It describes the tool, not the permissions of your key. +With a tool name, the command prints that tool's full description, input schema, and annotations. +JSON output is the server's `tools/list` result, `{"tools":[...]}`, after the CLI follows every page. + +The command authenticates with an organization API key. +The MCP server rejects CLI sign-in sessions, so the command refuses a saved browser login before it sends a request. +To keep your browser login, save a key in its own profile: + +```sh +adapt keys create mcp-tools --json +adapt --profile agent auth login --token-stdin < /path/to/private/key-file +adapt --profile agent mcp tools +``` + +The CLI sends one stateless `tools/list` request per page with MCP protocol version `2025-03-26`. +It accepts JSON and event-stream responses. +It does not retry this request automatically. + ## Configuration | Setting | Option | Environment variable | diff --git a/skills/adapt/SKILL.md b/skills/adapt/SKILL.md index 1057c7e..3acb4d1 100644 --- a/skills/adapt/SKILL.md +++ b/skills/adapt/SKILL.md @@ -117,6 +117,19 @@ describe the message-posting tool and use that channel ID. Listing channels is a separate action from sending a message. Inspect tool results for reported errors as well as the CLI exit status. +## Platform MCP server + +```sh +adapt mcp tools +adapt mcp tools TOOL_NAME +``` + +`mcp tools` lists the built-in tools of Platform's own MCP server, and +`mcp tools TOOL_NAME` prints one tool's input schema. It requires an organization +API key (`adapt auth login --token-stdin` or `ADAPT_TOKEN`); browser sign-in +sessions are refused. These are not the user's connected tools; use +`connections search` for those. `mcp list` shows authorized MCP clients, not tools. + ## Output, pagination, and retries Normal commands print JSON when piped; `--json` requests it explicitly. Execution diff --git a/src/cli.rs b/src/cli.rs index 40afe9d..a1c1173 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -81,7 +81,7 @@ pub enum Command { /// Manage your browser and CLI sessions #[command(subcommand)] Sessions(SessionCommand), - /// Inspect and revoke connected MCP clients + /// Inspect connected MCP clients and the tools the Platform MCP server provides #[command(subcommand)] Mcp(McpCommand), /// Watch resource changes as newline-delimited JSON @@ -690,10 +690,18 @@ pub enum SessionCommand { #[derive(Subcommand)] pub enum McpCommand { + /// List MCP clients you have authorized #[command(visible_alias = "ls")] List, - Revoke { - id: Uuid, + /// Revoke an authorized MCP client + Revoke { id: Uuid }, + /// List the Platform MCP server's built-in tools (requires an API key) + #[command( + after_help = "The Platform MCP server accepts organization API keys, not browser sign-in sessions.\nSave a key with `adapt auth login --token-stdin` (optionally in its own --profile) or set ADAPT_TOKEN.\nWith NAME, prints that tool's full description, input schema, and annotations." + )] + Tools { + /// Show one tool's full definition + name: Option, }, } diff --git a/src/commands.rs b/src/commands.rs index 667be33..d6788ef 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -3,7 +3,7 @@ use crate::{ auth, cli::*, config::{self, Config, Credential, CredentialKind}, - input, output, shell, skill, stream, + input, mcp, output, shell, skill, stream, }; use anyhow::{Context, Result, bail}; use clap::ValueEnum; @@ -48,6 +48,13 @@ pub async fn run(cli: Cli) -> Result { let origin = config::origin(cli.api_url.as_deref().unwrap_or(&saved.api_url))?; let same_origin = config::origin(&saved.api_url)?.origin() == origin.origin(); let env_token = std::env::var("ADAPT_TOKEN").ok().filter(|s| !s.is_empty()); + // Platform's MCP server rejects sign-in sessions, so `mcp tools` refuses one up front. + let session_credential = env_token.is_none() + && same_origin + && saved + .credential + .as_ref() + .is_some_and(|c| c.kind == CredentialKind::Session); let token = env_token.as_deref().or_else(|| { same_origin .then_some(saved.credential.as_ref()) @@ -184,7 +191,9 @@ pub async fn run(cli: Cli) -> Result { SessionCommand::Revoke { id } => api.post("/v1/auth/sessions/revoke", &json!({"id":id.to_string()})).await?, SessionCommand::RevokeOthers => api.post("/v1/auth/sessions/revoke-others", &json!({})).await?, }, + Command::Mcp(McpCommand::Tools { name }) => return mcp::tools(&api, name, session_credential, cli.json).await, Command::Mcp(command) => match command { + McpCommand::Tools { .. } => unreachable!("MCP tool lists are dispatched separately"), McpCommand::List => api.get("/v1/auth/mcp/connections").await?, McpCommand::Revoke { id } => api.post("/v1/auth/mcp/revoke", &json!({"id":id.to_string()})).await?, }, diff --git a/src/main.rs b/src/main.rs index 8d48a55..bb1b7b0 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,7 @@ mod cli; mod commands; mod config; mod input; +mod mcp; mod output; mod shell; mod skill; diff --git a/src/mcp.rs b/src/mcp.rs new file mode 100644 index 0000000..dd9d832 --- /dev/null +++ b/src/mcp.rs @@ -0,0 +1,284 @@ +//! Lists the built-in tools of Platform's hosted MCP server (`POST /mcp`). +//! +//! Platform serves 2025-era MCP traffic statelessly: every POST is answered by a +//! fresh server instance, so a single `tools/list` request needs no `initialize` +//! handshake or session. The response is either JSON or a Server-Sent Events +//! stream, as the Streamable HTTP transport allows. + +use crate::{ + api::{self, Api, ApiError}, + output, + stream::Decoder, +}; +use anyhow::{Context, Result, anyhow, bail}; +use futures_util::StreamExt; +use reqwest::{Method, Response, StatusCode, header::CONTENT_TYPE}; +use serde_json::{Value, json}; +use std::{collections::HashSet, io}; + +/// The revision Platform's documentation and tests use for `/mcp`. +const PROTOCOL_VERSION: &str = "2025-03-26"; +/// Stop following cursors after this many pages, even if each cursor is new. +const MAX_PAGES: u64 = 100; +const MAX_JSON_BYTES: usize = 32 * 1024 * 1024; + +pub async fn tools(api: &Api, name: Option, session: bool, json: bool) -> Result { + if session { + bail!( + "The Platform MCP server accepts organization API keys, not CLI sign-in sessions. Create a key with `adapt keys create NAME` and save it in its own profile with `adapt --profile PROFILE auth login --token-stdin`, or set ADAPT_TOKEN to the key" + ); + } + if !api.authenticated { + bail!( + "Not signed in to {}. The Platform MCP server needs an organization API key: save one with `adapt auth login --token-stdin` or set ADAPT_TOKEN", + api.origin + ); + } + let tools = list(api).await.map_err(explain)?; + if let Some(name) = name { + let tool = tools + .into_iter() + .find(|tool| tool["name"] == name.as_str()) + .with_context(|| { + format!( + "No Platform MCP tool is named \"{}\". Run `adapt mcp tools` to list them", + output::safe(&name) + ) + })?; + output::print(&tool, json)?; + } else if output::tables(json) { + if tools.is_empty() { + println!("No results."); + } else { + let rows: Vec = tools.iter().map(row).collect(); + output::table( + &mut io::stdout().lock(), + &["name", "access", "description"], + &rows, + )?; + } + } else { + output::print(&json!({ "tools": tools }), json)?; + } + Ok(0) +} + +/// Follows `nextCursor` until the server stops returning one. +async fn list(api: &Api) -> Result> { + let mut tools = Vec::new(); + let mut seen = HashSet::new(); + let mut cursor: Option = None; + for id in 1..=MAX_PAGES { + let params = match &cursor { + Some(cursor) => json!({ "cursor": cursor }), + None => json!({}), + }; + let mut result = call(api, id, "tools/list", params).await?; + let Value::Array(page) = result["tools"].take() else { + bail!("Platform MCP server returned an invalid tools/list result"); + }; + tools.extend(page); + let Some(next) = result["nextCursor"].as_str() else { + return Ok(tools); + }; + if !seen.insert(next.to_owned()) { + bail!("Platform returned a repeated pagination cursor"); + } + cursor = Some(next.to_owned()); + } + bail!("Platform MCP server returned more than {MAX_PAGES} pages of tools") +} + +/// Sends one JSON-RPC request and returns its `result` within `--timeout`. +async fn call(api: &Api, id: u64, method: &str, params: Value) -> Result { + tokio::time::timeout(api.timeout, exchange(api, id, method, params)) + .await + .with_context(|| format!("Platform MCP {method} request timed out"))? +} + +async fn exchange(api: &Api, id: u64, method: &str, params: Value) -> Result { + let response = api + .request(Method::POST, "/mcp")? + .header("Accept", "application/json, text/event-stream") + .header("MCP-Protocol-Version", PROTOCOL_VERSION) + .json(&json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params })) + .send() + .await + .map_err(|e| e.without_url()) + .context("Platform MCP request failed")?; + let response = api::ensure_success(response).await?; + let content_type = response + .headers() + .get(CONTENT_TYPE) + .and_then(|value| value.to_str().ok()) + .unwrap_or_default() + .to_ascii_lowercase(); + let message = if content_type.starts_with("text/event-stream") { + from_stream(response, id, method).await? + } else if content_type.starts_with("application/json") { + serde_json::from_slice(&api::limited_bytes(response, MAX_JSON_BYTES).await?) + .context("Platform MCP server returned invalid JSON")? + } else { + bail!( + "Platform MCP server returned unexpected content type \"{}\"", + output::safe(&content_type) + ); + }; + rpc_result(message, id, method) +} + +/// Returns the response to request `id`, skipping any notifications or server +/// requests the stream carries first. +async fn from_stream(response: Response, id: u64, method: &str) -> Result { + let mut stream = response.bytes_stream(); + let mut decoder = Decoder::default(); + while let Some(chunk) = stream.next().await { + decoder.push(&chunk.map_err(|e| e.without_url())?)?; + while let Some(event) = decoder.events.pop_front() { + if !matches!(event.name.as_str(), "" | "message") { + continue; + } + let message: Value = serde_json::from_str(&event.data) + .context("Platform MCP server sent an invalid event")?; + if message["id"] == id + && (message.get("result").is_some() || message.get("error").is_some()) + { + return Ok(message); + } + } + } + bail!("Platform MCP response ended before the {method} result") +} + +fn rpc_result(mut message: Value, id: u64, method: &str) -> Result { + if message["jsonrpc"] != "2.0" || message["id"] != id { + bail!("Platform MCP server returned an unexpected JSON-RPC response to {method}"); + } + if let Some(error) = message.get("error") { + bail!( + "MCP {method} failed: {} {}", + error["code"], + output::safe(error["message"].as_str().unwrap_or("Unknown error")) + ); + } + match message["result"].take() { + result @ Value::Object(_) => Ok(result), + _ => bail!("Platform MCP server returned an invalid {method} result"), + } +} + +/// Replaces the generic sign-in advice with what `/mcp` actually accepts. +fn explain(error: anyhow::Error) -> anyhow::Error { + let Some(failure) = error.downcast_ref::() else { + return error; + }; + let hint = match failure.status { + StatusCode::UNAUTHORIZED => { + "CLI sign-in sessions don't work here; use an active organization API key: save one with `adapt auth login --token-stdin` or set ADAPT_TOKEN" + } + StatusCode::FORBIDDEN if failure.message.contains("organization") => { + "an API key works only in its own organization; remove --org or ADAPT_ORG_ID, or use the key's own profile" + } + _ => return error, + }; + anyhow!( + "{} {}: {}; {hint}", + failure.status.as_u16(), + output::safe(&failure.code), + output::safe(&failure.message) + ) +} + +/// Summarizes a tool for the terminal table: its access hint and first sentence. +fn row(tool: &Value) -> Value { + json!({ + "name": tool["name"], + "access": access(&tool["annotations"]), + "description": tool["description"].as_str().map(summary), + }) +} + +/// MCP hints default to a non-read-only, destructive tool when absent. +fn access(annotations: &Value) -> &'static str { + if annotations["readOnlyHint"] == true { + "read-only" + } else if annotations["destructiveHint"] == false { + "write" + } else { + "destructive" + } +} + +fn summary(description: &str) -> &str { + let line = description.lines().next().unwrap_or_default().trim(); + match line.find(". ") { + Some(end) => &line[..=end], + None => line, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn access_follows_mcp_hint_defaults() { + assert_eq!(access(&json!({"readOnlyHint":true})), "read-only"); + assert_eq!( + access(&json!({"readOnlyHint":false,"destructiveHint":false})), + "write" + ); + assert_eq!( + access(&json!({"readOnlyHint":false,"destructiveHint":true})), + "destructive" + ); + assert_eq!(access(&Value::Null), "destructive"); + } + + #[test] + fn summary_keeps_the_first_sentence() { + assert_eq!( + summary("Start a command (use argv). Poll get_exec."), + "Start a command (use argv)." + ); + assert_eq!( + summary("List volumes and quotas."), + "List volumes and quotas." + ); + assert_eq!(summary("First line\nSecond line"), "First line"); + assert_eq!(summary(""), ""); + } + + #[test] + fn rows_show_name_access_and_summary() { + let tool = json!({ + "name": "read_file", + "description": "Read a file up to 32 KiB. Use REST for larger files.", + "annotations": {"readOnlyHint": true}, + }); + assert_eq!( + row(&tool), + json!({"name":"read_file","access":"read-only","description":"Read a file up to 32 KiB."}) + ); + assert_eq!(row(&json!({"name":"x"}))["description"], Value::Null); + } + + #[test] + fn rpc_result_requires_the_matching_response() { + let ok = json!({"jsonrpc":"2.0","id":1,"result":{"tools":[]}}); + assert_eq!( + rpc_result(ok, 1, "tools/list").unwrap(), + json!({"tools":[]}) + ); + let other = json!({"jsonrpc":"2.0","id":2,"result":{}}); + assert!(rpc_result(other, 1, "tools/list").is_err()); + let failed = + json!({"jsonrpc":"2.0","id":1,"error":{"code":-32603,"message":"Internal error"}}); + assert_eq!( + rpc_result(failed, 1, "tools/list").unwrap_err().to_string(), + "MCP tools/list failed: -32603 Internal error" + ); + let missing = json!({"jsonrpc":"2.0","id":1}); + assert!(rpc_result(missing, 1, "tools/list").is_err()); + } +} diff --git a/src/output.rs b/src/output.rs index d62d571..fa3102f 100644 --- a/src/output.rs +++ b/src/output.rs @@ -54,42 +54,7 @@ pub fn print(value: &Value, json: bool) -> Result<()> { .filter(|k| rows.iter().any(|r| !r[*k].is_null())) .collect(); if !keys.is_empty() { - let cells: Vec> = rows - .iter() - .map(|row| keys.iter().map(|k| cell(&row[*k])).collect()) - .collect(); - let widths: Vec = keys - .iter() - .enumerate() - .map(|(i, k)| { - cells - .iter() - .map(|r| r[i].chars().count()) - .max() - .unwrap_or(0) - .max(k.len()) - }) - .collect(); - writeln!( - out, - "{}", - keys.iter() - .enumerate() - .map(|(i, k)| format!("{:>() - .join(" ") - )?; - for row in cells { - writeln!( - out, - "{}", - row.iter() - .enumerate() - .map(|(i, c)| format!("{c:>() - .join(" ") - )?; - } + table(&mut out, &keys, rows)?; if let Some(cursor) = value["nextCursor"].as_str() { writeln!( out, @@ -104,6 +69,48 @@ pub fn print(value: &Value, json: bool) -> Result<()> { Ok(()) } +/// Writes `keys` of each row as left-aligned columns under uppercase headings. +/// Cells are sanitized and cut at 80 characters; missing values show as —. +pub fn table(out: &mut impl Write, keys: &[&str], rows: &[Value]) -> io::Result<()> { + let cells: Vec> = rows + .iter() + .map(|row| keys.iter().map(|k| cell(&row[*k])).collect()) + .collect(); + let widths: Vec = keys + .iter() + .enumerate() + .map(|(i, k)| { + cells + .iter() + .map(|r| r[i].chars().count()) + .max() + .unwrap_or(0) + .max(k.len()) + }) + .collect(); + writeln!( + out, + "{}", + keys.iter() + .enumerate() + .map(|(i, k)| format!("{:>() + .join(" ") + )?; + for row in cells { + writeln!( + out, + "{}", + row.iter() + .enumerate() + .map(|(i, c)| format!("{c:>() + .join(" ") + )?; + } + Ok(()) +} + pub fn safe(text: &str) -> String { text.chars() .flat_map(|c| { @@ -131,3 +138,42 @@ fn cell(value: &Value) -> String { text } } + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + fn render(keys: &[&str], rows: &[Value]) -> String { + let mut out = Vec::new(); + table(&mut out, keys, rows).unwrap(); + String::from_utf8(out).unwrap() + } + + #[test] + fn table_pads_columns_to_the_widest_cell_or_heading() { + let rows = [ + json!({"id":"a","name":"short"}), + json!({"id":"abc","name":"x"}), + ]; + assert_eq!( + render(&["id", "name"], &rows), + "ID NAME \na short\nabc x \n" + ); + } + + #[test] + fn table_marks_missing_values_and_cuts_long_cells() { + let long = "y".repeat(81); + let rendered = render(&["id", "name"], &[json!({"id":null,"name":long})]); + let row = rendered.lines().nth(1).unwrap(); + assert!(row.starts_with("— ")); + assert!(row.ends_with(&format!("{}…", "y".repeat(79)))); + } + + #[test] + fn table_escapes_control_characters() { + let rendered = render(&["name"], &[json!({"name":"a\u{1b}[2Jb"})]); + assert_eq!(rendered.lines().nth(1), Some("a\\u{1b}[2Jb")); + } +} diff --git a/src/stream.rs b/src/stream.rs index 24bdf3b..2cd43f9 100644 --- a/src/stream.rs +++ b/src/stream.rs @@ -18,21 +18,23 @@ use tokio_tungstenite::tungstenite::{Message, client::IntoClientRequest}; use uuid::Uuid; #[derive(Default, Debug)] -struct Event { - name: String, - id: Option, - data: String, +pub(crate) struct Event { + pub(crate) name: String, + pub(crate) id: Option, + pub(crate) data: String, } +/// Incremental Server-Sent Events parser. Feed arbitrary chunks to `push`, then +/// drain complete events from `events`. #[derive(Default)] -struct Decoder { +pub(crate) struct Decoder { pending: Vec, current: Event, - events: VecDeque, + pub(crate) events: VecDeque, } impl Decoder { - fn push(&mut self, bytes: &[u8]) -> Result<()> { + pub(crate) fn push(&mut self, bytes: &[u8]) -> Result<()> { self.pending.extend_from_slice(bytes); if self.pending.len() + self.current.data.len() > 8 * 1024 * 1024 { bail!("SSE event exceeds 8 MiB"); diff --git a/tests/cli.rs b/tests/cli.rs index 3ed3eb4..10ce12e 100644 --- a/tests/cli.rs +++ b/tests/cli.rs @@ -4,6 +4,7 @@ use std::time::Duration; use support::*; mod image_list; +mod mcp_tools; mod resource_prefixes; mod retries; mod sandbox_list; diff --git a/tests/mcp_tools/mod.rs b/tests/mcp_tools/mod.rs new file mode 100644 index 0000000..c05b271 --- /dev/null +++ b/tests/mcp_tools/mod.rs @@ -0,0 +1,282 @@ +use crate::support::*; +use serde_json::{Value, json}; + +// Platform's hosted MCP server answers `tools/list` statelessly over Streamable HTTP. +// Its SDK replies with an event stream by default, so most cases use SSE replies. + +fn tool(name: &str) -> Value { + json!({ + "name": name, + "description": format!("Run {name}. More detail."), + "inputSchema": {"type":"object","properties":{}}, + "annotations": {"readOnlyHint":true,"destructiveHint":false}, + }) +} + +fn sse(messages: &[Value]) -> Reply { + let mut body = String::from(": keepalive\n\n"); + for message in messages { + body += &format!("event: message\ndata: {message}\n\n"); + } + Reply::bytes("text/event-stream", body.into_bytes()) +} + +/// Expects one `tools/list` request with this id and params, then sends `reply`. +fn tools_list(id: u64, params: Value, reply: Reply) -> Handler { + Box::new(move |request| { + assert_eq!(request.method, "POST"); + assert_eq!(request.target, "/mcp"); + assert_eq!(request.headers["authorization"], "Bearer test-token"); + assert_eq!(request.headers["x-organization-id"], ORG); + assert_eq!(request.headers["mcp-protocol-version"], "2025-03-26"); + assert_eq!(request.headers["content-type"], "application/json"); + let accept = &request.headers["accept"]; + assert!(accept.contains("application/json") && accept.contains("text/event-stream")); + assert_eq!( + request.json(), + json!({"jsonrpc":"2.0","id":id,"method":"tools/list","params":params}) + ); + reply + }) +} + +fn result(id: u64, result: Value) -> Value { + json!({"jsonrpc":"2.0","id":id,"result":result}) +} + +fn failure(output: &std::process::Output) -> String { + assert!(!output.status.success(), "command unexpectedly succeeded"); + String::from_utf8_lossy(&output.stderr).into_owned() +} + +#[test] +fn reads_the_result_from_an_event_stream() { + let notification = json!({"jsonrpc":"2.0","method":"notifications/message","params":{"level":"info","data":"hi"}}); + let server = Server::start(vec![tools_list( + 1, + json!({}), + sse(&[ + notification, + result(1, json!({"tools":[tool("whoami"), tool("list_sandboxes")]})), + ]), + )]); + let dir = tempfile::tempdir().unwrap(); + let output = success(&run(dir.path(), &server.url, &["mcp", "tools"])); + assert_eq!( + output, + json!({"tools":[tool("whoami"), tool("list_sandboxes")]}) + ); + server.finish(); +} + +#[test] +fn reads_a_json_result() { + let server = Server::start(vec![tools_list( + 1, + json!({}), + Reply::json(200, result(1, json!({"tools":[tool("whoami")]}))), + )]); + let dir = tempfile::tempdir().unwrap(); + let output = success(&run(dir.path(), &server.url, &["mcp", "tools"])); + assert_eq!(output["tools"][0]["name"], "whoami"); + server.finish(); +} + +#[test] +fn follows_cursors_until_the_last_page() { + let server = Server::start(vec![ + tools_list( + 1, + json!({}), + sse(&[result( + 1, + json!({"tools":[tool("first")],"nextCursor":"page-2"}), + )]), + ), + tools_list( + 2, + json!({"cursor":"page-2"}), + sse(&[result(2, json!({"tools":[tool("second")]}))]), + ), + ]); + let dir = tempfile::tempdir().unwrap(); + let output = success(&run(dir.path(), &server.url, &["mcp", "tools"])); + assert_eq!(output, json!({"tools":[tool("first"), tool("second")]})); + server.finish(); +} + +#[test] +fn rejects_a_repeated_cursor() { + let page = |id| sse(&[result(id, json!({"tools":[],"nextCursor":"same"}))]); + let server = Server::start(vec![ + tools_list(1, json!({}), page(1)), + tools_list(2, json!({"cursor":"same"}), page(2)), + ]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run(dir.path(), &server.url, &["mcp", "tools"])); + assert!(stderr.contains("repeated pagination cursor"), "{stderr}"); + server.finish(); +} + +#[test] +fn fails_on_a_json_rpc_error() { + let error = json!({"jsonrpc":"2.0","id":1,"error":{"code":-32602,"message":"Invalid params"}}); + let server = Server::start(vec![tools_list(1, json!({}), sse(&[error]))]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run(dir.path(), &server.url, &["mcp", "tools"])); + assert!( + stderr.contains("MCP tools/list failed: -32602 Invalid params"), + "{stderr}" + ); + server.finish(); +} + +#[test] +fn fails_when_the_stream_ends_before_the_result() { + let unrelated = result(99, json!({"tools":[tool("not-ours")]})); + let server = Server::start(vec![tools_list(1, json!({}), sse(&[unrelated]))]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run(dir.path(), &server.url, &["mcp", "tools"])); + assert!( + stderr.contains("ended before the tools/list result"), + "{stderr}" + ); + server.finish(); +} + +#[test] +fn unauthorized_explains_that_mcp_needs_an_api_key() { + let server = Server::start(vec![tools_list( + 1, + json!({}), + Reply::json( + 401, + json!({"error":"invalid_token","error_description":"Connect using OAuth, an identity session, or an organization API key."}), + ), + )]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run(dir.path(), &server.url, &["mcp", "tools"])); + assert!( + stderr.contains("401 invalid_token: Connect using OAuth"), + "{stderr}" + ); + assert!( + stderr.contains("sign-in sessions don't work here; use an active organization API key"), + "{stderr}" + ); + assert!(!stderr.contains("to sign in again"), "{stderr}"); + server.finish(); +} + +#[test] +fn organization_mismatch_explains_api_key_scope() { + let server = Server::start(vec![tools_list( + 1, + json!({}), + Reply::json( + 403, + json!({"error":{"code":"FORBIDDEN","message":"The API key cannot access this organization."}}), + ), + )]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run(dir.path(), &server.url, &["mcp", "tools"])); + assert!(stderr.contains("403 FORBIDDEN"), "{stderr}"); + assert!(stderr.contains("only in its own organization"), "{stderr}"); + server.finish(); +} + +#[test] +fn refuses_a_saved_sign_in_session_without_sending_it() { + let server = Server::start(vec![]); + let dir = tempfile::tempdir().unwrap(); + save_profile(dir.path(), &server.url); + let output = command(dir.path(), &server.url) + .args(["mcp", "tools"]) + .output() + .unwrap(); + let stderr = failure(&output); + assert!(stderr.contains("not CLI sign-in sessions"), "{stderr}"); + assert!(stderr.contains("--token-stdin"), "{stderr}"); + assert!(server.finish().is_empty()); +} + +#[test] +fn uses_a_saved_api_key() { + let server = Server::start(vec![Box::new(|request: &Request| { + assert_eq!(request.headers["authorization"], "Bearer saved-key"); + assert_eq!(request.headers["x-organization-id"], ORG); + sse(&[result(1, json!({"tools":[tool("whoami")]}))]) + })]); + let dir = tempfile::tempdir().unwrap(); + let config = json!({"profiles":{"default":{"api_url":server.url,"organization_id":ORG,"credential":{"token":"saved-key","kind":"api_key","expires_at":null}}}}); + std::fs::write( + dir.path().join("config.json"), + serde_json::to_vec(&config).unwrap(), + ) + .unwrap(); + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + std::fs::set_permissions( + dir.path().join("config.json"), + std::fs::Permissions::from_mode(0o600), + ) + .unwrap(); + } + let output = command(dir.path(), &server.url) + .args(["mcp", "tools"]) + .output() + .unwrap(); + assert_eq!(success(&output)["tools"][0]["name"], "whoami"); + server.finish(); +} + +#[test] +fn not_signed_in_points_to_api_keys() { + let server = Server::start(vec![]); + let dir = tempfile::tempdir().unwrap(); + let output = command(dir.path(), &server.url) + .args(["mcp", "tools"]) + .output() + .unwrap(); + let stderr = failure(&output); + assert!(stderr.contains("Not signed in"), "{stderr}"); + assert!(stderr.contains("organization API key"), "{stderr}"); + assert!(server.finish().is_empty()); +} + +#[test] +fn name_prints_one_tool_definition() { + let server = Server::start(vec![tools_list( + 1, + json!({}), + sse(&[result( + 1, + json!({"tools":[tool("whoami"), tool("read_file")]}), + )]), + )]); + let dir = tempfile::tempdir().unwrap(); + let output = success(&run( + dir.path(), + &server.url, + &["mcp", "tools", "read_file"], + )); + assert_eq!(output, tool("read_file")); + server.finish(); +} + +#[test] +fn unknown_name_fails_with_a_hint() { + let server = Server::start(vec![tools_list( + 1, + json!({}), + sse(&[result(1, json!({"tools":[tool("whoami")]}))]), + )]); + let dir = tempfile::tempdir().unwrap(); + let stderr = failure(&run(dir.path(), &server.url, &["mcp", "tools", "nope"])); + assert!( + stderr.contains("No Platform MCP tool is named \"nope\""), + "{stderr}" + ); + server.finish(); +}