mirror of
https://github.com/mountain-loop/yaak.git
synced 2026-11-28 19:22:39 +01:00
Agents pane: CLI-only MCP, yaak mcp --http, and plugin deprecation (#761)
This commit is contained in:
1 parent
349e6f9197
commit
6132171791
32 files changed
+950
-524
No files matched your search
@@ -93,8 +93,23 @@ pub enum Commands {
|
||||
/// Response commands
|
||||
Response(ResponseArgs),
|
||||
|
||||
/// Serve Yaak's MCP tools over stdio, for AI agents like Claude Code
|
||||
Mcp,
|
||||
/// Serve Yaak's MCP tools to AI agents like Claude Code, over stdio or with --http
|
||||
Mcp(McpArgs),
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
pub struct McpArgs {
|
||||
/// Serve over HTTP on 127.0.0.1 instead of stdio, for agents that cannot run this command
|
||||
#[arg(long)]
|
||||
pub http: bool,
|
||||
|
||||
/// Port to listen on with --http
|
||||
#[arg(long, default_value_t = yaak_mcp::http::DEFAULT_PORT, requires = "http")]
|
||||
pub port: u16,
|
||||
|
||||
/// Bearer token clients must send with --http; generated and printed when omitted
|
||||
#[arg(long, requires = "http", value_name = "TOKEN")]
|
||||
pub token: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Args)]
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use crate::cli::McpArgs;
|
||||
use crate::context::{CliContext, CliExecutionContext};
|
||||
use crate::plugin_events::SendContexts;
|
||||
use rand::Rng;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use yaak::send::{SendHttpRequestWithPluginsParams, send_http_request_with_plugins};
|
||||
@@ -13,7 +16,27 @@ use yaak_models::util::UpdateSource;
|
||||
use yaak_plugins::events::{PluginContext, ShowToastRequest};
|
||||
use yaak_plugins::manager::PluginManager;
|
||||
|
||||
pub async fn run(ctx: &CliContext, environment: Option<&str>, cookie_jar_id: Option<&str>) -> i32 {
|
||||
enum Transport {
|
||||
Stdio,
|
||||
Http { port: u16, token: Option<String> },
|
||||
}
|
||||
|
||||
impl From<McpArgs> for Transport {
|
||||
fn from(args: McpArgs) -> Self {
|
||||
if args.http {
|
||||
Transport::Http { port: args.port, token: args.token }
|
||||
} else {
|
||||
Transport::Stdio
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run(
|
||||
ctx: &CliContext,
|
||||
args: McpArgs,
|
||||
environment: Option<&str>,
|
||||
cookie_jar_id: Option<&str>,
|
||||
) -> i32 {
|
||||
let host = CliMcpHost {
|
||||
query_manager: ctx.query_manager().clone(),
|
||||
blob_manager: ctx.blob_manager().clone(),
|
||||
@@ -25,7 +48,11 @@ pub async fn run(ctx: &CliContext, environment: Option<&str>, cookie_jar_id: Opt
|
||||
environment_id: environment.map(str::to_string),
|
||||
cookie_jar_id: cookie_jar_id.map(str::to_string),
|
||||
};
|
||||
match yaak_mcp::serve_stdio(host).await {
|
||||
let result = match Transport::from(args) {
|
||||
Transport::Stdio => yaak_mcp::serve_stdio(host).await,
|
||||
Transport::Http { port, token } => serve_http(host, port, token).await,
|
||||
};
|
||||
match result {
|
||||
Ok(()) => 0,
|
||||
Err(error) => {
|
||||
eprintln!("Error: {error}");
|
||||
@@ -34,6 +61,24 @@ pub async fn run(ctx: &CliContext, environment: Option<&str>, cookie_jar_id: Opt
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve_http(host: CliMcpHost, port: u16, token: Option<String>) -> Result<(), String> {
|
||||
let token = token.unwrap_or_else(generate_token);
|
||||
let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, port));
|
||||
let server = yaak_mcp::http::serve(Arc::new(host), addr, token.clone())
|
||||
.await
|
||||
.map_err(|e| format!("Failed to start MCP server on {addr}: {e}"))?;
|
||||
eprintln!("Yaak MCP server listening on http://{}{}", server.addr, yaak_mcp::http::PATH);
|
||||
eprintln!("Token: {token}");
|
||||
eprintln!("Clients must send it as \"Authorization: Bearer <token>\". Press Ctrl+C to stop.");
|
||||
tokio::signal::ctrl_c().await.map_err(|e| format!("Failed to wait for Ctrl+C: {e}"))?;
|
||||
server.stop().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn generate_token() -> String {
|
||||
hex::encode(rand::thread_rng().r#gen::<[u8; 32]>())
|
||||
}
|
||||
|
||||
/// Every workspace in the database is "open", and the global `--environment`
|
||||
/// and `--cookie-jar` flags stand in for a window's selection.
|
||||
struct CliMcpHost {
|
||||
|
||||
@@ -184,7 +184,7 @@ async fn main() {
|
||||
context.shutdown().await;
|
||||
exit_code
|
||||
}
|
||||
Commands::Mcp => {
|
||||
Commands::Mcp(args) => {
|
||||
let mut context = CliContext::new(data_dir.clone(), app_id);
|
||||
context
|
||||
.init_plugins(CliExecutionContext {
|
||||
@@ -194,7 +194,8 @@ async fn main() {
|
||||
})
|
||||
.await;
|
||||
let exit_code =
|
||||
commands::mcp::run(&context, environment.as_deref(), cookie_jar.as_deref()).await;
|
||||
commands::mcp::run(&context, args, environment.as_deref(), cookie_jar.as_deref())
|
||||
.await;
|
||||
context.shutdown().await;
|
||||
exit_code
|
||||
}
|
||||
|
||||
@@ -222,3 +222,129 @@ async fn mcp_send_settings_reach_template_functions() {
|
||||
client.cancel().await.unwrap();
|
||||
assert!(child.wait().await.unwrap().success());
|
||||
}
|
||||
|
||||
/// Spawns `yaak mcp --http` with `args` and returns the child, the URL it
|
||||
/// printed, and the token it printed or was given.
|
||||
async fn spawn_http(data_dir: &std::path::Path, args: &[&str]) -> (tokio::process::Child, String, String) {
|
||||
use tokio::io::AsyncBufReadExt;
|
||||
|
||||
let mut child = Command::new(env!("CARGO_BIN_EXE_yaak"))
|
||||
.arg("--data-dir")
|
||||
.arg(data_dir)
|
||||
.args(["mcp", "--http", "--port", "0"])
|
||||
.args(args)
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::piped())
|
||||
.kill_on_drop(true)
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let mut stderr = tokio::io::BufReader::new(child.stderr.take().unwrap()).lines();
|
||||
let mut url = None;
|
||||
let mut token = None;
|
||||
while url.is_none() || token.is_none() {
|
||||
let line = stderr.next_line().await.unwrap().expect("server exited before announcing");
|
||||
if let Some(rest) = line.strip_prefix("Yaak MCP server listening on ") {
|
||||
url = Some(rest.to_string());
|
||||
} else if let Some(rest) = line.strip_prefix("Token: ") {
|
||||
token = Some(rest.to_string());
|
||||
}
|
||||
}
|
||||
(child, url.unwrap(), token.unwrap())
|
||||
}
|
||||
|
||||
/// Posts one JSON-RPC message, with the session id when there is one, and
|
||||
/// returns the response and its body parsed out of either JSON or SSE.
|
||||
async fn post(
|
||||
client: &reqwest::Client,
|
||||
url: &str,
|
||||
auth: Option<&str>,
|
||||
session: Option<&str>,
|
||||
body: Value,
|
||||
) -> (reqwest::StatusCode, reqwest::header::HeaderMap, Option<Value>) {
|
||||
let mut request = client
|
||||
.post(url)
|
||||
.header("Content-Type", "application/json")
|
||||
.header("Accept", "application/json, text/event-stream")
|
||||
.body(body.to_string());
|
||||
if let Some(auth) = auth {
|
||||
request = request.header("Authorization", auth);
|
||||
}
|
||||
if let Some(session) = session {
|
||||
request = request.header("Mcp-Session-Id", session);
|
||||
}
|
||||
let response = request.send().await.unwrap();
|
||||
let status = response.status();
|
||||
let headers = response.headers().clone();
|
||||
let text = response.text().await.unwrap();
|
||||
let message = text
|
||||
.lines()
|
||||
.filter_map(|l| l.strip_prefix("data:"))
|
||||
.last()
|
||||
.map(str::trim)
|
||||
.unwrap_or(text.trim());
|
||||
(status, headers, serde_json::from_str(message).ok())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_http_requires_the_token() {
|
||||
let temp_dir = TempDir::new().expect("Failed to create temp dir");
|
||||
let data_dir = temp_dir.path();
|
||||
seed_workspace(data_dir, "wk_test");
|
||||
let (mut child, url, token) = spawn_http(data_dir, &["--token", "s3cret"]).await;
|
||||
assert_eq!(token, "s3cret");
|
||||
assert!(url.starts_with("http://127.0.0.1:"), "{url}");
|
||||
assert!(url.ends_with("/mcp"), "{url}");
|
||||
let client = reqwest::Client::new();
|
||||
let initialize = json!({
|
||||
"jsonrpc": "2.0", "id": 1, "method": "initialize",
|
||||
"params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "test", "version": "1.0" } }
|
||||
});
|
||||
|
||||
for auth in [None, Some("Bearer wrong")] {
|
||||
let (status, headers, _) = post(&client, &url, auth, None, initialize.clone()).await;
|
||||
assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED, "{auth:?}");
|
||||
assert_eq!(headers["www-authenticate"], "Bearer");
|
||||
}
|
||||
|
||||
let auth = Some("Bearer s3cret");
|
||||
let (status, headers, body) = post(&client, &url, auth, None, initialize).await;
|
||||
assert_eq!(status, reqwest::StatusCode::OK);
|
||||
let session = headers["mcp-session-id"].to_str().unwrap().to_string();
|
||||
assert_eq!(body.unwrap()["result"]["serverInfo"]["name"], "yaak-mcp-server");
|
||||
|
||||
let initialized = json!({ "jsonrpc": "2.0", "method": "notifications/initialized" });
|
||||
let (status, _, _) = post(&client, &url, auth, Some(&session), initialized).await;
|
||||
assert_eq!(status, reqwest::StatusCode::ACCEPTED);
|
||||
|
||||
let list = json!({ "jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {} });
|
||||
let (status, _, body) = post(&client, &url, auth, Some(&session), list).await;
|
||||
assert_eq!(status, reqwest::StatusCode::OK);
|
||||
let tools = body.unwrap()["result"]["tools"].as_array().unwrap().len();
|
||||
assert_eq!(tools, 15);
|
||||
|
||||
child.kill().await.unwrap();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn mcp_http_generates_a_token() {
|
||||
let temp_dir = TempDir::new().expect("Failed to create temp dir");
|
||||
let data_dir = temp_dir.path();
|
||||
seed_workspace(data_dir, "wk_test");
|
||||
let (mut child, url, token) = spawn_http(data_dir, &[]).await;
|
||||
assert_eq!(token.len(), 64, "{token}");
|
||||
assert!(token.chars().all(|c| c.is_ascii_hexdigit()), "{token}");
|
||||
|
||||
let client = reqwest::Client::new();
|
||||
let initialize = json!({
|
||||
"jsonrpc": "2.0", "id": 1, "method": "initialize",
|
||||
"params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "test", "version": "1.0" } }
|
||||
});
|
||||
let (status, _, _) = post(&client, &url, None, None, initialize.clone()).await;
|
||||
assert_eq!(status, reqwest::StatusCode::UNAUTHORIZED);
|
||||
let (status, _, _) =
|
||||
post(&client, &url, Some(&format!("Bearer {token}")), None, initialize).await;
|
||||
assert_eq!(status, reqwest::StatusCode::OK);
|
||||
|
||||
child.kill().await.unwrap();
|
||||
}
|
||||
Reference in new issue
Block a user