Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.
feat(mcp): serve Jan's builtin tools over MCP (stdio + HTTP) (#9011)
Akarshan Biswas897008134d2c
diff --git a/docs/src/pages/docs/agent/mcp.mdx b/docs/src/pages/docs/agent/mcp.mdxindex 99742c932..b82f3a880 100644--- a/docs/src/pages/docs/agent/mcp.mdx+++ b/docs/src/pages/docs/agent/mcp.mdx@@ -118,6 +118,47 @@ Add, list, edit, remove, and toggle servers headlessly with `jan cli mcp ...` -files --command npx --arg -y --arg my-mcp`, `jan cli mcp list`, `jan cli mcp remove files`. See the[CLI reference](/docs/agent/cli#jan-cli-mcp).+## Serving Jan's own tools++The other direction: `jan mcp serve` exposes Jan's built-in tools - `read`, the memory and skill+store, `web_search`, `web_fetch` - as an MCP server, so Claude Code, Codex CLI or any other MCP+client can call them.++```bash+jan mcp serve --project . # stdio, what another agent spawns as a child process+jan mcp serve --transport http # loopback Streamable HTTP; prints its URL and bearer token+```++The served tools run against **one project root**, fixed when the server starts, with the same path+confinement and sandbox re-checks an in-agent call gets. A path argument that escapes that root is+refused, and so is anything inside the project's hidden `.jan` state.++The default set is read-only: file reading, search, memory, skills and the web tools. The two+classes that can change the machine are opt-in, because the caller is another program rather than a+person who can answer a permission prompt:++| Flag | Adds |+| --- | --- |+| `--allow-write` | `write` and `edit`, confined to the project root |+| `--allow-exec` | `bash`, under the same OS sandbox the agent's shell uses |+| `--tool NAME` | Narrows the set to these names; never widens what the flags above permit |++Anything that would otherwise wait for an approval returns an error instead of blocking, so a peer+never hangs on a prompt nobody can see. A project's `[tools]` section still applies: `sandbox` and+`allow_network` are read from its `agent.toml` exactly as a normal run reads them.++On `--transport http` the listener is loopback-only and every request must carry the bearer token+printed at startup (`--token` sets your own); a request without it gets a `401`. Point a client at+the printed URL:++```json+{+ "mcpServers": {+ "jan": { "command": "jan", "args": ["mcp", "serve", "--project", "/path/to/project"] }+ }+}+```+## Tool policyMCP tools follow the project's [`[tools]` policy](/docs/agent/permissions#project-policy):diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex bf48dadf5..113d5d379 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -6206,11 +6206,14 @@ dependencies = ["chrono","futures","http",+ "http-body",+ "http-body-util","indexmap 2.14.0","oauth2","pastey","pin-project-lite","process-wrap",+ "rand 0.10.2","reqwest 0.13.4","rmcp-macros","schemars 1.2.1",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex b5f167984..ff9c50175 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -127,11 +127,19 @@ log = "0.4"# accessors on the persisted token record (`core::mcp::oauth`).oauth2 = "5.0"rand = "0.8"+# Both directions: `client` + the http/child-process client transports consume+# other people's servers (`core::mcp::helpers`), while `server`,+# `transport-io` and `transport-streamable-http-server` serve Jan's own toolset+# (`core::mcp::server`). The server side is Tauri-free so it builds in the `cli`+# feature config too.rmcp = { version = "3.2.0", features = ["auth","client",+ "server",+ "transport-io","transport-streamable-http-client","transport-streamable-http-client-reqwest",+ "transport-streamable-http-server","transport-child-process","tower","reqwest",diff --git a/src-tauri/jan-cli/Cargo.lock b/src-tauri/jan-cli/Cargo.lockindex e2b312572..f2d4a8beb 100644--- a/src-tauri/jan-cli/Cargo.lock+++ b/src-tauri/jan-cli/Cargo.lock@@ -4233,11 +4233,14 @@ dependencies = ["chrono","futures","http",+ "http-body",+ "http-body-util","indexmap 2.14.2","oauth2","pastey","pin-project-lite","process-wrap",+ "rand 0.10.2","reqwest 0.13.5","rmcp-macros","schemars 1.2.2",diff --git a/src-tauri/jan-cli/src/main.rs b/src-tauri/jan-cli/src/main.rsindex aa6f0ca49..d74c77b0b 100644--- a/src-tauri/jan-cli/src/main.rs+++ b/src-tauri/jan-cli/src/main.rs@@ -11,6 +11,7 @@ use console::Style;// The lib target is named "app_lib" (see [lib] section in Cargo.toml).use app_lib::core::agent::plugins::InstalledPlugin;use app_lib::core::cli::mcp::{self, split_kv, McpServerEntry};+use app_lib::core::cli::mcp_serve::{cli_mcp_serve, ServeFlags, ServeTransport};use app_lib::core::cli::providers::{load_provider_configs, ProviderOverrides};use app_lib::core::cli::run_report::OutputFormat;use app_lib::core::cli::stream_input::InputFormat;@@ -237,8 +238,14 @@ enum Commands {#[command(subcommand)]cmd: PluginCommands,},- /// Update this binary to the latest build of the channel it was built for+ /// Serve Jan's built-in tools to another agent over MCP#[command(display_order = 6)]+ Mcp {+ #[command(subcommand)]+ cmd: McpServeCommands,+ },+ /// Update this binary to the latest build of the channel it was built for+ #[command(display_order = 7)]Update {/// Report whether an update exists without installing it#[arg(long)]@@ -249,6 +256,37 @@ enum Commands {},}+/// The server direction of MCP: Jan offered as a tool provider. The client+/// direction (managing the servers Jan *connects to*) stays under+/// `jan cli mcp`.+#[derive(Subcommand)]+enum McpServeCommands {+ /// Run an MCP server exposing Jan's built-in tools for one project+ Serve {+ /// Project root the served tools are confined to+ #[arg(long, default_value = ".")]+ project: String,+ /// Transport: stdio for a spawned child process, http for loopback Streamable HTTP+ #[arg(long, value_enum, default_value_t = ServeTransport::Stdio)]+ transport: ServeTransport,+ /// Also serve the mutating filesystem tools (write, edit), confined to the project root+ #[arg(long)]+ allow_write: bool,+ /// Also serve bash (runs under the same OS sandbox the agent's shell does)+ #[arg(long)]+ allow_exec: bool,+ /// Serve only these tools, repeatable; never widens what the allow flags permit+ #[arg(long = "tool")]+ tools: Vec<String>,+ /// Port for --transport http; 0 picks a free one+ #[arg(long, default_value_t = 0)]+ port: u16,+ /// Bearer token for --transport http; a random one is generated and printed if omitted+ #[arg(long)]+ token: Option<String>,+ },+}+/// Tokamak sign-in inspection and control.#[derive(Subcommand)]enum AuthCommands {@@ -628,7 +666,9 @@ async fn main() {// `jan update` reports the same thing itself, in more detail. The check// doubles as the usage record (see `updater::fetch_manifest`), so there is// no separate ping to fire here; `JAN_CLI_NO_UPDATE_CHECK` opts out of both.- if !matches!(command, Commands::Update { .. }) {+ // `jan mcp serve` is driven by another program, not a person: nobody reads+ // the notice, and an update fetch on every spawn is a cost the peer pays.+ if !matches!(command, Commands::Update { .. } | Commands::Mcp { .. }) {app_lib::core::cli::updater::print_update_notice_if_available().await;}@@ -653,10 +693,36 @@ async fn main() {}}Commands::Plugin { cmd } => handle_plugin(cmd).await,+ Commands::Mcp { cmd } => handle_mcp_serve(cmd).await,Commands::Update { check, force } => handle_update(check, force).await,}}+// ── MCP server handler ─────────────────────────────────────────────────────++async fn handle_mcp_serve(cmd: McpServeCommands) {+ let McpServeCommands::Serve {+ project,+ transport,+ allow_write,+ allow_exec,+ tools,+ port,+ token,+ } = cmd;+ let flags = ServeFlags {+ allow_write,+ allow_exec,+ only: tools,+ port,+ token,+ };+ if let Err(e) = cli_mcp_serve(&project, transport, flags).await {+ eprintln!("Error: {e}");+ std::process::exit(1);+ }+}+// ── Update handler ─────────────────────────────────────────────────────────async fn handle_update(check: bool, force: bool) {@@ -1373,6 +1439,87 @@ mod tests {assert!(Cli::try_parse_from(["jan", "update", "--check", "--force"]).is_err());}+ #[test]+ fn mcp_serve_parses_and_defaults_to_read_only_stdio() {+ let cli = Cli::parse_from(["jan", "mcp", "serve"]);+ let Some(Commands::Mcp {+ cmd: McpServeCommands::Serve {+ project,+ transport,+ allow_write,+ allow_exec,+ tools,+ port,+ token,+ },+ }) = cli.command+ else {+ panic!("expected mcp serve");+ };+ assert_eq!(project, ".");+ assert_eq!(transport, ServeTransport::Stdio);+ assert!(!allow_write);+ assert!(!allow_exec);+ assert!(tools.is_empty());+ assert_eq!(port, 0);+ assert!(token.is_none());+ }++ #[test]+ fn mcp_serve_http_flags_parse() {+ let cli = Cli::parse_from([+ "jan",+ "mcp",+ "serve",+ "--transport",+ "http",+ "--port",+ "7331",+ "--token",+ "abc",+ "--allow-write",+ "--allow-exec",+ "--tool",+ "read",+ "--tool",+ "grep",+ ]);+ let Some(Commands::Mcp {+ cmd: McpServeCommands::Serve {+ transport,+ allow_write,+ allow_exec,+ tools,+ port,+ token,+ ..+ },+ }) = cli.command+ else {+ panic!("expected mcp serve");+ };+ assert_eq!(transport, ServeTransport::Http);+ assert!(allow_write);+ assert!(allow_exec);+ assert_eq!(tools, vec!["read".to_string(), "grep".to_string()]);+ assert_eq!(port, 7331);+ assert_eq!(token.as_deref(), Some("abc"));+ }++ /// The client direction keeps its own place; `jan mcp` must not shadow it.+ #[test]+ fn mcp_client_subcommand_still_lives_under_cli() {+ let cli = Cli::parse_from(["jan", "cli", "mcp", "list"]);+ assert!(matches!(+ cli.command,+ Some(Commands::Cli {+ cmd: CliCommands::Mcp {+ cmd: McpCommands::List { .. }+ }+ })+ ));+ }+#[test]fn login_command_parses_and_takes_no_args() {let cli = Cli::parse_from(["jan", "login"]);diff --git a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rsindex 1d9fe0db0..b0b9014e4 100644--- a/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs+++ b/src-tauri/plugins/tauri-plugin-agent-tools/src/tools/schema.rs@@ -1,6 +1,11 @@//! OpenAI `tools` array entries for the built-in tools, one per BUILTIN_TOOLS//! entry. These are advertised to the model when a project is active; execution//! is dispatched by `handlers::execute_builtin` and gated by `gate`.+//!+//! Two views, one schema each: [`builtin_tool_schemas`] is what a model is+//! offered, and [`search_tool_schemas`] holds `ls`/`find`/`grep`, which the+//! model is not offered because `bash` covers them. A caller that has no `bash`+//! -- an external MCP client served the read-only set -- takes both.use serde_json::{json, Value};@@ -25,12 +30,12 @@ pub fn builtin_tool_schemas() -> Vec<Value> {}}}),- // ls / find / grep are deliberately NOT advertised: `bash` covers+ // ls / find / grep are deliberately NOT advertised here: `bash` covers// listing and searching (`ls`, `find`, `grep`/`rg`), so dedicated tools// for them only enlarge the schema a weak model has to handle. They stay- // in BUILTIN_TOOLS -- recognized, gated, and executable if named -- so- // the change is reversible and the handlers/tests are untouched; they are- // just no longer offered to the model.+ // in BUILTIN_TOOLS -- recognized, gated, and executable if named -- and+ // their schemas live in `search_tool_schemas` for callers that have no+ // `bash` to cover them.#[cfg(feature = "tauri")]json!({"type": "function",@@ -211,6 +216,70 @@ pub fn builtin_tool_schemas() -> Vec<Value> {.to_vec()}+/// Schemas for the three search tools a model is not offered (`bash` covers+/// them for the agent). Kept out of [`builtin_tool_schemas`] so the model's tool+/// array stays small, and defined here rather than at a call site so there is+/// still exactly one copy of each schema in the tree.+///+/// Taken by a surface that serves the read-only toolset without `bash`, where+/// otherwise nothing could list or search at all.+pub fn search_tool_schemas() -> Vec<Value> {+ [+ json!({+ "type": "function",+ "function": {+ "name": "ls",+ "description": "List the entries of a directory, one per line, with directories marked by a trailing slash.",+ "parameters": {+ "type": "object",+ "properties": {+ "path": { "type": "string", "description": "Directory path relative to the project root (or absolute). Defaults to the root." },+ "limit": { "type": "integer", "description": "Maximum number of entries to return (default 500)." }+ },+ "required": []+ }+ }+ }),+ json!({+ "type": "function",+ "function": {+ "name": "find",+ "description": "Find files whose path matches a glob pattern, honoring .gitignore. Use this to locate files by name; use grep to search their contents.",+ "parameters": {+ "type": "object",+ "properties": {+ "pattern": { "type": "string", "description": "Glob pattern to match against each path, e.g. **/*.rs." },+ "path": { "type": "string", "description": "Directory to search under, relative to the project root. Defaults to the root." },+ "limit": { "type": "integer", "description": "Maximum number of paths to return (default 1000)." }+ },+ "required": ["pattern"]+ }+ }+ }),+ json!({+ "type": "function",+ "function": {+ "name": "grep",+ "description": "Search file contents for a regular expression, honoring .gitignore, and return matching lines with their file and line number.",+ "parameters": {+ "type": "object",+ "properties": {+ "pattern": { "type": "string", "description": "Regular expression to search for, or a literal string when literal is true." },+ "path": { "type": "string", "description": "Directory or file to search, relative to the project root. Defaults to the root." },+ "glob": { "type": "string", "description": "Only search paths matching this glob, e.g. *.rs." },+ "ignore_case": { "type": "boolean", "description": "Match case-insensitively (default false)." },+ "literal": { "type": "boolean", "description": "Treat pattern as a literal string rather than a regex (default false)." },+ "context": { "type": "integer", "description": "Lines of context to include around each match (default 0)." },+ "limit": { "type": "integer", "description": "Maximum number of matches to return (default 100)." }+ },+ "required": ["pattern"]+ }+ }+ }),+ ]+ .to_vec()+}+#[cfg(test)]mod tests {use super::*;@@ -237,4 +306,57 @@ mod tests {.collect();assert_eq!(names, expected);}++ /// The two views together must cover BUILTIN_TOOLS exactly: no builtin+ /// without a schema, and no schema for something that is not a builtin.+ #[test]+ fn the_two_schema_views_together_cover_every_builtin() {+ let mut names: Vec<String> = builtin_tool_schemas()+ .iter()+ .chain(search_tool_schemas().iter())+ .map(|s| s["function"]["name"].as_str().unwrap().to_string())+ .collect();+ names.sort();+ let mut expected: Vec<String> =+ BUILTIN_TOOLS.iter().map(|t| t.name.to_string()).collect();+ expected.sort();+ assert_eq!(names, expected);+ }++ /// The search schemas name the arguments the handlers actually read; a+ /// rename on either side would otherwise silently produce a tool whose+ /// required argument never arrives.+ #[test]+ fn search_schemas_declare_the_handler_arguments() {+ let schemas = search_tool_schemas();+ for schema in &schemas {+ assert_eq!(schema["type"], "function");+ assert_eq!(schema["function"]["parameters"]["type"], "object");+ }+ let by_name = |n: &str| -> Value {+ schemas+ .iter()+ .find(|s| s["function"]["name"] == n)+ .expect("schema present")+ .clone()+ };+ // `path` is optional everywhere (it defaults to the root); `pattern` is+ // required exactly where the handler errors without it.+ assert!(by_name("ls")["function"]["parameters"]["properties"]["path"].is_object());+ assert_eq!(by_name("ls")["function"]["parameters"]["required"], json!([]));+ for tool in ["find", "grep"] {+ let s = by_name(tool);+ assert_eq!(+ s["function"]["parameters"]["required"],+ json!(["pattern"]),+ "{tool}"+ );+ }+ for key in ["glob", "ignore_case", "literal", "context", "limit"] {+ assert!(+ by_name("grep")["function"]["parameters"]["properties"][key].is_object(),+ "grep is missing {key}"+ );+ }+ }}diff --git a/src-tauri/plugins/tauri-plugin-websearch/src/provider.rs b/src-tauri/plugins/tauri-plugin-websearch/src/provider.rsindex 8f262ab61..6e0adc6b3 100644--- a/src-tauri/plugins/tauri-plugin-websearch/src/provider.rs+++ b/src-tauri/plugins/tauri-plugin-websearch/src/provider.rs@@ -293,6 +293,16 @@ fn parse_hosted_result_text(body: &str, provider: &str) -> Result<String, String.and_then(|a| a.first()).and_then(|c| c.get("text")).and_then(|v| v.as_str());+ // A throttled hosted endpoint answers HTTP 200 with no `isError`, putting+ // the refusal in the text block where it parses as zero results. Reported+ // as success that reads to a model as "the web has nothing", so the flag in+ // `_meta` is the only thing separating a refusal from a real empty answer.+ if is_rate_limited(result) {+ return Err(format!(+ "{provider} rate limit reached: {}",+ text.unwrap_or("no quota remaining on the keyless endpoint")+ ));+ }if result.get("isError").and_then(|v| v.as_bool()) == Some(true) {return Err(format!("{provider} tool call failed: {}",@@ -303,6 +313,22 @@ fn parse_hosted_result_text(body: &str, provider: &str) -> Result<String, String.ok_or_else(|| format!("{provider} response had no text content"))}+/// Whether a hosted `result` carries a provider rate-limit marker in `_meta`.+///+/// Namespaced per vendor (`ai.exa/rateLimited`), so the suffix is matched+/// rather than one hard-coded key: the hosted transport is shared by every+/// keyless backend here.+fn is_rate_limited(result: &Value) -> bool {+ result+ .get("_meta")+ .and_then(|m| m.as_object())+ .is_some_and(|meta| {+ meta.iter().any(|(k, v)| {+ (k == "rateLimited" || k.ends_with("/rateLimited")) && v.as_bool() == Some(true)+ })+ })+}+fn parse_hosted_search_text(text: &str) -> Vec<SearchResult> {let mut out = Vec::new();for block in text.split("\n---\n") {@@ -1090,6 +1116,54 @@ mod tests {.contains("bad"));}+ #[test]+ fn parse_hosted_result_text_surfaces_rate_limit_as_error() {+ // Verbatim shape of a throttled `mcp.exa.ai/mcp` reply: the call+ // "succeeds" (no `isError`, HTTP 200) and the refusal is prose in the+ // text block, so only `_meta` distinguishes it from a real answer.+ let sse = format!(+ "event: message\ndata: {}\n\n",+ json!({+ "jsonrpc": "2.0",+ "id": 1,+ "result": {+ "_meta": { "ai.exa/rateLimited": true },+ "content": [{+ "type": "text",+ "text": "You've hit Exa's free MCP rate limit. To continue using without limits, create your own Exa API key."+ }]+ }+ })+ );+ let err = parse_hosted_result_text(&sse, "Exa")+ .expect_err("a throttled reply must not read as a successful search");+ assert!(err.contains("rate limit"), "unexpected message: {err}");+ }++ #[test]+ fn parse_hosted_result_text_ignores_unrelated_meta() {+ let raw = json!({+ "result": {+ "_meta": { "ai.exa/cached": true },+ "content": [{ "type": "text", "text": "hello" }]+ }+ })+ .to_string();+ assert_eq!(parse_hosted_result_text(&raw, "Exa").unwrap(), "hello");+ }++ #[test]+ fn parse_hosted_result_text_rate_limit_flag_must_be_true() {+ let raw = json!({+ "result": {+ "_meta": { "ai.exa/rateLimited": false },+ "content": [{ "type": "text", "text": "hello" }]+ }+ })+ .to_string();+ assert_eq!(parse_hosted_result_text(&raw, "Exa").unwrap(), "hello");+ }+#[test]fn parse_hosted_search_text_maps_contract() {let text = "Title: Paris | Britannica\nURL: https://www.britannica.com/place/Paris\nPublished: 1998-07-20T00:00:00.000Z\nAuthor: N/A\nHighlights:\nParis is the capital of France.\n...\nSecond highlight.\n---\nTitle: Paris\nURL: https://en.wikipedia.org/wiki/Paris\nPublished: N/A\nAuthor: N/A\nHighlights:\nParis is the capital and largest city of France.";diff --git a/src-tauri/src/core/cli/mcp_serve.rs b/src-tauri/src/core/cli/mcp_serve.rsnew file mode 100644index 000000000..f79b418ee--- /dev/null+++ b/src-tauri/src/core/cli/mcp_serve.rs@@ -0,0 +1,137 @@+//! `jan mcp serve`: run Jan's built-in toolset as an MCP server so another+//! agent can call it.+//!+//! The protocol work lives in `core::mcp::server`; this is only the CLI's entry+//! point -- resolving the project root and its `agent.toml` settings, choosing a+//! transport, and keeping stdout clean on the stdio one.++use std::path::PathBuf;++use crate::core::mcp::server::{http, stdio, ServeOptions, ServedTools};++/// Which transport `jan mcp serve` should use.+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]+#[clap(rename_all = "kebab-case")]+pub enum ServeTransport {+ /// JSON-RPC over stdin/stdout: what another agent spawns as a child process.+ #[default]+ Stdio,+ /// Streamable HTTP on loopback, behind a bearer token.+ Http,+}++/// Flags that shape the served surface, mapped onto [`ServedTools`].+#[derive(Clone, Debug, Default)]+pub struct ServeFlags {+ pub allow_write: bool,+ pub allow_exec: bool,+ pub only: Vec<String>,+ pub port: u16,+ pub token: Option<String>,+}++/// Resolve the project root and its settings into [`ServeOptions`].+///+/// `[tools].allow_network` and `[tools].sandbox` are honored exactly as the+/// agent loop honors them, so a project that has configured its toolset gets the+/// same behavior whether the caller is Jan's own agent or someone else's.+fn options_for(project: &str, flags: &ServeFlags) -> Result<ServeOptions, String> {+ let root = PathBuf::from(project)+ .canonicalize()+ .map_err(|e| format!("Cannot resolve project '{project}': {e}"))?;+ let settings = crate::core::agent::project::run_settings(&root);+ let mut opts = ServeOptions::new(root);+ opts.enabled_skills = settings.enabled_skills;+ opts.allow_network = settings.allow_network.unwrap_or(false);+ opts.sandbox = settings.sandbox.unwrap_or(true);+ opts.served = ServedTools {+ allow_write: flags.allow_write,+ allow_exec: flags.allow_exec,+ only: flags.only.clone(),+ };+ Ok(opts)+}++/// Run the server until the peer disconnects (stdio) or the process is stopped+/// (http).+pub async fn cli_mcp_serve(+ project: &str,+ transport: ServeTransport,+ flags: ServeFlags,+) -> Result<(), String> {+ let opts = options_for(project, &flags)?;+ match transport {+ ServeTransport::Stdio => {+ // stdout is the JSON-RPC stream from here on; the startup notice+ // goes to stderr like every other log this binary writes.+ eprintln!(+ "jan mcp serve: stdio, project {}",+ opts.project_root.display()+ );+ stdio::serve(opts).await+ }+ ServeTransport::Http => {+ let (bound, serve) = http::bind(opts, flags.port, flags.token.clone()).await?;+ println!("url: {}", bound.url());+ println!("token: {}", bound.token);+ serve.await;+ Ok(())+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn options_follow_the_flags_and_default_to_read_only() {+ let dir = tempfile::tempdir().expect("tempdir");+ let project = dir.path().to_string_lossy().to_string();++ let opts = options_for(&project, &ServeFlags::default()).expect("options");+ assert_eq!(opts.served, ServedTools::default());+ assert!(opts.sandbox, "sandbox stays on unless agent.toml says otherwise");+ assert!(!opts.allow_network);+ assert_eq!(opts.store_root, opts.project_root.join(".jan").join("agent"));++ let opts = options_for(+ &project,+ &ServeFlags {+ allow_write: true,+ allow_exec: true,+ only: vec!["read".into()],+ ..Default::default()+ },+ )+ .expect("options");+ assert!(opts.served.allow_write);+ assert!(opts.served.allow_exec);+ assert_eq!(opts.served.only, vec!["read".to_string()]);+ }++ #[test]+ fn agent_toml_tool_settings_are_honored() {+ let dir = tempfile::tempdir().expect("tempdir");+ let agent_dir = dir.path().join(".jan").join("agent");+ std::fs::create_dir_all(&agent_dir).expect("mkdir");+ std::fs::write(+ agent_dir.join("agent.toml"),+ "[tools]\nsandbox = false\nallow_network = true\n\n[skills]\nenabled = [\"jan\"]\n",+ )+ .expect("write agent.toml");++ let opts = options_for(&dir.path().to_string_lossy(), &ServeFlags::default())+ .expect("options");+ assert!(!opts.sandbox);+ assert!(opts.allow_network);+ assert_eq!(opts.enabled_skills, vec!["jan".to_string()]);+ }++ #[test]+ fn a_missing_project_is_an_error_not_a_panic() {+ let err = options_for("/definitely/not/here", &ServeFlags::default())+ .expect_err("missing project");+ assert!(err.contains("Cannot resolve project"), "{err}");+ }+}diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rsindex 209191360..cd3a2a160 100644--- a/src-tauri/src/core/cli/mod.rs+++ b/src-tauri/src/core/cli/mod.rs@@ -10,6 +10,8 @@ pub mod device_auth;pub mod journal;pub mod login;pub mod mcp;+/// `jan mcp serve`: the other direction, Jan's toolset served over MCP.+pub mod mcp_serve;mod model_capabilities;pub mod model_catalog;mod path_refs;diff --git a/src-tauri/src/core/mcp/mod.rs b/src-tauri/src/core/mcp/mod.rsindex a6f1060da..d4adec61b 100644--- a/src-tauri/src/core/mcp/mod.rs+++ b/src-tauri/src/core/mcp/mod.rs@@ -13,6 +13,9 @@ pub mod models;pub mod oauth;#[cfg(not(feature = "cli"))]pub mod progress;+// The server direction: Jan's own toolset offered to other agents. Tauri-free,+// so it is built in both feature configs.+pub mod server;pub mod truncate;#[cfg(test)]diff --git a/src-tauri/src/core/mcp/server/http.rs b/src-tauri/src/core/mcp/server/http.rsnew file mode 100644index 000000000..e3ad70d9e--- /dev/null+++ b/src-tauri/src/core/mcp/server/http.rs@@ -0,0 +1,156 @@+//! The Streamable HTTP transport for [`JanToolServer`], bound to loopback+//! behind a bearer token.+//!+//! This is the same transport `core::mcp::helpers` connects *out* to, so a peer+//! that can talk to a remote MCP server can talk to this one. rmcp 3.x dropped+//! the HTTP+SSE client transport, so there is deliberately no SSE server here+//! either.+//!+//! Loopback plus a token, not one or the other: loopback keeps the listener off+//! the network, and the token keeps any other local process -- including a web+//! page's fetch from the user's browser -- from driving the agent's tools.++use std::convert::Infallible;+use std::net::SocketAddr;+use std::sync::Arc;++use http_body_util::{BodyExt, Full};+use hyper::body::Bytes;+use hyper::server::conn::http1;+use hyper::service::service_fn;+use hyper::{Request, Response, StatusCode};+use hyper_util::rt::TokioIo;+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;+use rmcp::transport::{StreamableHttpServerConfig, StreamableHttpService};++use super::{JanToolServer, ServeOptions};++/// A bound Streamable HTTP server: where it listens, and the token a caller+/// must present.+#[derive(Debug, Clone)]+pub struct BoundServer {+ pub addr: SocketAddr,+ pub token: String,+}++impl BoundServer {+ /// The URL an MCP client should be pointed at.+ pub fn url(&self) -> String {+ format!("http://{}/mcp", self.addr)+ }+}++/// A fresh random bearer token, hex-encoded 256 bits.+pub fn generate_token() -> String {+ use rand::Rng;+ let bytes: [u8; 32] = rand::thread_rng().gen();+ bytes.iter().map(|b| format!("{b:02x}")).collect()+}++/// Whether the request presents `token` as an RFC 6750 bearer credential.+///+/// Compared in constant time over the whole candidate: a short-circuiting+/// compare on a token a local attacker can retry at will is a timing oracle.+pub fn authorized(headers: &hyper::HeaderMap, token: &str) -> bool {+ let Some(value) = headers.get(hyper::header::AUTHORIZATION) else {+ return false;+ };+ let Ok(value) = value.to_str() else {+ return false;+ };+ let Some(presented) = value+ .strip_prefix("Bearer ")+ .or_else(|| value.strip_prefix("bearer "))+ else {+ return false;+ };+ constant_time_eq(presented.as_bytes(), token.as_bytes())+}++fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {+ if a.len() != b.len() {+ return false;+ }+ a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0+}++fn unauthorized() -> Response<http_body_util::combinators::BoxBody<Bytes, Infallible>> {+ let mut response = Response::new(+ Full::new(Bytes::from_static(b"unauthorized"))+ .map_err(|e: Infallible| match e {})+ .boxed(),+ );+ *response.status_mut() = StatusCode::UNAUTHORIZED;+ response.headers_mut().insert(+ hyper::header::WWW_AUTHENTICATE,+ hyper::header::HeaderValue::from_static("Bearer"),+ );+ response+}++/// Bind a loopback Streamable HTTP server and serve the built-in toolset on it+/// until the process ends.+///+/// `port` 0 picks a free one; the chosen address comes back in [`BoundServer`].+/// The returned future must be polled (spawn it, or await it) for the server to+/// accept anything -- binding is done eagerly so the caller can print the URL+/// and the token before a single connection arrives.+pub async fn bind(+ opts: ServeOptions,+ port: u16,+ token: Option<String>,+) -> Result<(BoundServer, impl std::future::Future<Output = ()>), String> {+ let addr = SocketAddr::from(([127, 0, 0, 1], port));+ let listener = tokio::net::TcpListener::bind(addr)+ .await+ .map_err(|e| format!("failed to bind {addr}: {e}"))?;+ let addr = listener+ .local_addr()+ .map_err(|e| format!("failed to read the bound address: {e}"))?;+ let token = token.unwrap_or_else(generate_token);+ let bound = BoundServer {+ addr,+ token: token.clone(),+ };++ // One handler per session; the options are shared, so the factory is a+ // clone rather than a rebuild.+ let server = JanToolServer::new(opts);+ let service = Arc::new(StreamableHttpService::new(+ move || Ok(server.clone()),+ Arc::new(LocalSessionManager::default()),+ StreamableHttpServerConfig::default(),+ ));+ let token = Arc::new(token);++ let serve = async move {+ loop {+ let (stream, _) = match listener.accept().await {+ Ok(c) => c,+ Err(e) => {+ log::error!("MCP server accept error: {e}");+ continue;+ }+ };+ let io = TokioIo::new(stream);+ let service = service.clone();+ let token = token.clone();+ tokio::spawn(async move {+ let handler = service_fn(move |req: Request<hyper::body::Incoming>| {+ let service = service.clone();+ let token = token.clone();+ async move {+ if !authorized(req.headers(), &token) {+ return Ok::<_, Infallible>(unauthorized());+ }+ Ok(service.handle(req).await)+ }+ });+ if let Err(e) = http1::Builder::new().serve_connection(io, handler).await {+ log::debug!("MCP server connection error: {e}");+ }+ });+ }+ };+ Ok((bound, serve))+}diff --git a/src-tauri/src/core/mcp/server/mod.rs b/src-tauri/src/core/mcp/server/mod.rsnew file mode 100644index 000000000..fd5c17af2--- /dev/null+++ b/src-tauri/src/core/mcp/server/mod.rs@@ -0,0 +1,333 @@+//! Jan as an MCP *server*: the built-in agent toolset offered to any other+//! agent that speaks MCP (Claude Code, Codex CLI, a custom orchestrator).+//!+//! This is the mirror of `core::mcp::helpers`, which consumes other people's+//! servers. Nothing here duplicates the tool layer: the advertised schemas come+//! from `tools::schema::builtin_tool_schemas()`, dispatch goes through+//! `tools::handlers::execute_builtin`, and the decision to run a call is made by+//! `tools::gate::resolve_decision` -- the same three functions the agent loop+//! uses. `tools::lookup()` stays the authority on capability and `path_args`.+//!+//! Tauri-free on purpose, so it compiles in the `cli` feature config and the+//! desktop one alike.+//!+//! An external caller is not a user standing at a permission prompt, so the two+//! answers the agent loop gets from a human are decided statically here:+//! anything the gate would prompt about is either pre-approved by an explicit+//! opt-in ([`ServedTools`]) or refused outright. Nothing ever blocks waiting for+//! an approval that cannot arrive.++use std::path::PathBuf;+use std::sync::Arc;++use rmcp::model::{+ CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock, Implementation,+ ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerInfo, Tool,+};+use rmcp::service::{RequestContext, RoleServer};+use rmcp::{ErrorData as McpError, ServerHandler};+use tauri_plugin_agent_tools::tools::gate::{+ resolve_decision, Decision, DenyReason, GateContext, PromptKind, SessionGrants,+};+use tauri_plugin_agent_tools::tools::handlers::execute_builtin;+use tauri_plugin_agent_tools::tools::schema::{builtin_tool_schemas, search_tool_schemas};+use tauri_plugin_agent_tools::tools::{lookup, Capability, ToolContext};++pub mod http;+pub mod stdio;++#[cfg(test)]+mod tests;++/// Which built-in tools this server offers.+///+/// The default is the read/search/memory/skill/web set. The two classes that can+/// change the machine -- `bash` and the mutating filesystem tools (`write`,+/// `edit`) -- are opt-in, because the caller is another program rather than a+/// user who can be asked. Opting one in *is* the approval: the gate's prompt for+/// it is then treated as granted, but only for a target inside the served root+/// (an escaping path still prompts, and a prompt is always a refusal here).+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct ServedTools {+ /// Offer `write` and `edit`, confined to the served project root.+ pub allow_write: bool,+ /// Offer `bash`. Runs under the same OS confinement the agent's shell does.+ pub allow_exec: bool,+ /// Restrict the offering further to these names. Empty means "everything the+ /// two flags above permit"; a name the flags exclude is not re-admitted by+ /// listing it here.+ pub only: Vec<String>,+}++impl ServedTools {+ /// Whether `name` is offered. Unknown names are not served: `lookup()`+ /// decides what a built-in is, and `path_args`/`capability` come from there.+ pub fn is_served(&self, name: &str) -> bool {+ let Some(tool) = lookup(name) else {+ return false;+ };+ if !self.only.is_empty() && !self.only.iter().any(|n| n == name) {+ return false;+ }+ match tool.capability {+ Capability::Exec => self.allow_exec,+ // A `Write` tool with no path argument is a workspace tool+ // (`memory_write`, `skill_write`): it writes into the agent's own+ // store by sanitized name and can never reach a project file, so it+ // belongs to the memory/skill set rather than the mutating one.+ Capability::Write => self.allow_write || tool.path_args.is_empty(),+ Capability::Read | Capability::Net => true,+ }+ }+}++/// Everything the served tools run against. One project root per server, fixed+/// at start: the containment an external caller gets is the containment the+/// agent gets, and it cannot be renegotiated mid-session.+#[derive(Debug, Clone)]+pub struct ServeOptions {+ /// The one project root the served tools are confined to.+ pub project_root: PathBuf,+ /// Where `memory/` and `skills/` live; normally+ /// `workspace::project_store(project_root)`.+ pub store_root: PathBuf,+ /// The `[skills].enabled` whitelist; empty means every skill.+ pub enabled_skills: Vec<String>,+ /// Let the sandboxed shell reach the network.+ pub allow_network: bool,+ /// Run `bash` under OS confinement. Left on unless the operator turns it off.+ pub sandbox: bool,+ /// Session scratch shared by the shell and the filesystem tools.+ pub scratch_root: Option<PathBuf>,+ /// Which tools are offered. See [`ServedTools`].+ pub served: ServedTools,+}++impl ServeOptions {+ /// Defaults for a project root: its co-located store, the read-only served+ /// set, sandbox on.+ pub fn new(project_root: PathBuf) -> Self {+ let store_root = tauri_plugin_agent_tools::workspace::project_store(&project_root);+ Self {+ project_root,+ store_root,+ enabled_skills: Vec::new(),+ allow_network: false,+ sandbox: true,+ scratch_root: None,+ served: ServedTools::default(),+ }+ }+}++/// The MCP server: Jan's built-in toolset behind a `ServerHandler`.+///+/// Cheap to clone (one `Arc`), which is what the Streamable HTTP transport needs+/// -- it builds a fresh handler per session from a factory.+#[derive(Debug, Clone)]+pub struct JanToolServer {+ opts: Arc<ServeOptions>,+}++impl JanToolServer {+ pub fn new(opts: ServeOptions) -> Self {+ Self {+ opts: Arc::new(opts),+ }+ }++ pub fn options(&self) -> &ServeOptions {+ &self.opts+ }++ /// The tools this server advertises, derived from the toolset's own schemas+ /// and filtered by [`ServedTools`]. There is no second copy of any schema:+ /// the OpenAI function entry's `parameters` object *is* the MCP+ /// `inputSchema`.+ ///+ /// `ls`/`find`/`grep` come from [`search_tool_schemas`] and are served even+ /// though a model is not offered them. The reason they are withheld from a+ /// model is that `bash` covers listing and searching, and `bash` is opt-in+ /// here -- so on the default read-only set, withholding them too would leave+ /// a peer able to read a file only if it already knew its name.+ pub fn tools(&self) -> Vec<Tool> {+ builtin_tool_schemas()+ .into_iter()+ .chain(search_tool_schemas())+ .filter_map(|schema| {+ let function = schema.get("function")?;+ let name = function.get("name")?.as_str()?.to_string();+ if !self.opts.served.is_served(&name) {+ return None;+ }+ let description = function+ .get("description")+ .and_then(|d| d.as_str())+ .map(|d| d.to_string());+ let input_schema = function+ .get("parameters")+ .and_then(|p| p.as_object())+ .cloned()+ .unwrap_or_default();+ Some(Tool::new_with_raw(+ name,+ description.map(Into::into),+ input_schema,+ ))+ })+ .collect()+ }++ /// The tool context a served call runs against.+ ///+ /// `confine_writes` is on and no read/write root is attached: unlike the CLI,+ /// which works *in* a project the user is sitting in, this caller only ever+ /// gets the one root it was started with.+ fn tool_context(&self) -> ToolContext<'_> {+ let mut ctx = ToolContext::new(+ &self.opts.project_root,+ &self.opts.store_root,+ &self.opts.enabled_skills,+ )+ .with_network(self.opts.allow_network)+ .with_sandbox(self.opts.sandbox)+ .with_confined_writes(true);+ if let Some(scratch) = self.opts.scratch_root.as_deref() {+ ctx = ctx.with_scratch_root(scratch);+ }+ ctx+ }++ /// Run one tool call, or explain why it was refused. The returned string is+ /// the tool result in the toolset's own convention: a failure starts with+ /// `ERROR`.+ ///+ /// Split out from [`ServerHandler::call_tool`] so the decision table is+ /// testable without a transport.+ pub async fn dispatch(+ &self,+ name: &str,+ args: &serde_json::Value,+ ) -> (String, Vec<ContentBlock>) {+ let Some(tool) = lookup(name) else {+ return (format!("ERROR: unknown tool '{name}'"), Vec::new());+ };+ if !self.opts.served.is_served(name) {+ return (+ format!(+ "ERROR: tool '{name}' is not served by this Jan MCP server. \+ Mutating filesystem tools and bash are opt-in."+ ),+ Vec::new(),+ );+ }+ let decision = resolve_decision(+ tool,+ args,+ &GateContext {+ project_root: &self.opts.project_root,+ scratch: self.opts.scratch_root.as_deref(),+ read_roots: &[],+ write_roots: &[],+ // The agent's own `.jan` state is never reachable as a path;+ // memory and skills are served through their own tools.+ hide_jan: true,+ },+ &Default::default(),+ &SessionGrants::default(),+ );+ match decision {+ Decision::Allow => {}+ Decision::HardDeny(DenyReason::Policy) => {+ return (format!("ERROR: tool '{name}' is denied by policy"), Vec::new())+ }+ Decision::HardDeny(DenyReason::Hidden) => {+ return (+ format!(+ "ERROR: tool '{name}' was refused: the path is inside the agent's \+ hidden .jan state. Use the memory_* and skill_* tools instead."+ ),+ Vec::new(),+ )+ }+ // An in-project write or a shell command: the opt-in that made the+ // tool servable is the approval, so run it. `is_served` already+ // refused the tool when the opt-in was absent.+ Decision::Prompt(PromptKind::Write) | Decision::Prompt(PromptKind::Exec) => {}+ // Escapes the served root. There is no one to ask, and the whole+ // point of a served root is that it holds, so refuse.+ Decision::Prompt(kind @ (PromptKind::ReadEscape | PromptKind::WriteEscape)) => {+ let what = match kind {+ PromptKind::ReadEscape => "read",+ _ => "write",+ };+ return (+ format!(+ "ERROR: tool '{name}' was refused: the path escapes the served project \+ root, and an external caller cannot be asked to approve a {what} \+ outside it."+ ),+ Vec::new(),+ );+ }+ }+ let ctx = self.tool_context();+ let (content, images) = execute_builtin(tool, args, &ctx).await;+ let blocks = images+ .unwrap_or_default()+ .iter()+ .filter_map(|part| image_block(&part.data_url))+ .collect();+ (content, blocks)+ }+}++/// Split a `data:<mime>;base64,<payload>` URL into an MCP image block. Returns+/// `None` for anything that is not one, so a malformed part is dropped rather+/// than sent as a broken block.+fn image_block(data_url: &str) -> Option<ContentBlock> {+ let rest = data_url.strip_prefix("data:")?;+ let (mime, payload) = rest.split_once(";base64,")?;+ Some(ContentBlock::image(payload.to_string(), mime.to_string()))+}++impl ServerHandler for JanToolServer {+ fn get_info(&self) -> ServerInfo {+ ServerInfo::new(ServerCapabilities::builder().enable_tools().build())+ .with_server_info(Implementation::new("jan", env!("CARGO_PKG_VERSION")))+ .with_instructions(+ "Jan's built-in agent tools, confined to one project root. Filesystem paths \+ are resolved against that root and a path escaping it is refused. Tools that \+ would need an interactive approval return an error instead of blocking.",+ )+ }++ async fn list_tools(+ &self,+ _request: Option<PaginatedRequestParams>,+ _context: RequestContext<RoleServer>,+ ) -> Result<ListToolsResult, McpError> {+ Ok(ListToolsResult::with_all_items(self.tools()))+ }++ async fn call_tool(+ &self,+ request: CallToolRequestParams,+ _context: RequestContext<RoleServer>,+ ) -> Result<CallToolResponse, McpError> {+ let args = serde_json::Value::Object(request.arguments.unwrap_or_default());+ let (content, mut blocks) = self.dispatch(&request.name, &args).await;+ let is_error = content.starts_with("ERROR");+ blocks.insert(0, ContentBlock::text(content));+ let result = if is_error {+ CallToolResult::error(blocks)+ } else {+ CallToolResult::success(blocks)+ };+ Ok(result.into())+ }++ fn get_tool(&self, name: &str) -> Option<Tool> {+ self.tools().into_iter().find(|t| t.name == name)+ }+}diff --git a/src-tauri/src/core/mcp/server/stdio.rs b/src-tauri/src/core/mcp/server/stdio.rsnew file mode 100644index 000000000..c0c728b5b--- /dev/null+++ b/src-tauri/src/core/mcp/server/stdio.rs@@ -0,0 +1,25 @@+//! The stdio transport for [`JanToolServer`]: the child-process shape every+//! other agent already knows how to spawn.+//!+//! stdout carries the JSON-RPC framing and nothing else. Anything this process+//! would otherwise print (logs, progress, a banner) must go to stderr, or the+//! peer's parser sees a corrupt stream; the caller is responsible for having+//! routed its logger there before calling [`serve`].++use rmcp::transport::io::stdio;+use rmcp::ServiceExt;++use super::{JanToolServer, ServeOptions};++/// Serve the built-in toolset over stdin/stdout until the peer disconnects.+pub async fn serve(opts: ServeOptions) -> Result<(), String> {+ let service = JanToolServer::new(opts)+ .serve(stdio())+ .await+ .map_err(|e| format!("failed to start the MCP stdio server: {e}"))?;+ service+ .waiting()+ .await+ .map_err(|e| format!("MCP stdio server stopped: {e}"))?;+ Ok(())+}diff --git a/src-tauri/src/core/mcp/server/tests.rs b/src-tauri/src/core/mcp/server/tests.rsnew file mode 100644index 000000000..0190ebc8b--- /dev/null+++ b/src-tauri/src/core/mcp/server/tests.rs@@ -0,0 +1,348 @@+//! Tests for the served side of MCP: the advertised set, the decision table,+//! and a list/call round trip over a real transport.++use std::path::PathBuf;++use rmcp::model::CallToolRequestParams;+use rmcp::transport::io::stdio;+use rmcp::{ServiceExt, ServerHandler};++use super::http::{authorized, generate_token};+use super::{JanToolServer, ServeOptions, ServedTools};++fn options(root: &std::path::Path) -> ServeOptions {+ let mut opts = ServeOptions::new(root.to_path_buf());+ // The sandbox is a kernel facility the CI container may not have; these+ // tests are about the served surface, not about confinement of `bash`.+ opts.sandbox = false;+ opts+}++fn tool_names(server: &JanToolServer) -> Vec<String> {+ server.tools().into_iter().map(|t| t.name.to_string()).collect()+}++#[test]+fn default_served_set_is_read_only() {+ let server = JanToolServer::new(options(&PathBuf::from(".")));+ let names = tool_names(&server);+ assert!(names.contains(&"read".to_string()));+ // Served even though a model is not offered them: `bash` is what covers+ // listing and searching for the agent, and `bash` is opt-in here.+ assert!(names.contains(&"ls".to_string()));+ assert!(names.contains(&"find".to_string()));+ assert!(names.contains(&"grep".to_string()));+ assert!(names.contains(&"web_search".to_string()));+ assert!(names.contains(&"memory_read".to_string()));+ // Workspace writes stay in: they reach the agent's own store by name, never+ // a project file.+ assert!(names.contains(&"memory_write".to_string()));+ assert!(names.contains(&"skill_write".to_string()));+ assert!(!names.contains(&"write".to_string()));+ assert!(!names.contains(&"edit".to_string()));+ assert!(!names.contains(&"bash".to_string()));+}++#[test]+fn opt_in_adds_mutating_tools() {+ let mut opts = options(&PathBuf::from("."));+ opts.served = ServedTools {+ allow_write: true,+ allow_exec: true,+ only: Vec::new(),+ };+ let names = tool_names(&JanToolServer::new(opts));+ assert!(names.contains(&"write".to_string()));+ assert!(names.contains(&"edit".to_string()));+ assert!(names.contains(&"bash".to_string()));+}++#[test]+fn only_narrows_the_set_but_never_widens_it() {+ let mut opts = options(&PathBuf::from("."));+ opts.served.only = vec!["read".into(), "bash".into()];+ let names = tool_names(&JanToolServer::new(opts));+ assert_eq!(names, vec!["read".to_string()]);+}++/// Every served name must be a real builtin, so the gate and `path_args` apply+/// to all of them; and the served set must carry no duplicate, which chaining+/// two schema lists could otherwise introduce.+#[test]+fn every_served_tool_is_a_gated_builtin_and_appears_once() {+ let mut opts = options(&PathBuf::from("."));+ opts.served = ServedTools {+ allow_write: true,+ allow_exec: true,+ only: Vec::new(),+ };+ let names = tool_names(&JanToolServer::new(opts));+ for name in &names {+ assert!(+ tauri_plugin_agent_tools::tools::lookup(name).is_some(),+ "{name} is served but is not a builtin"+ );+ }+ let mut unique = names.clone();+ unique.sort();+ unique.dedup();+ assert_eq!(unique.len(), names.len(), "duplicate in {names:?}");+}++#[test]+fn advertised_schemas_are_the_builtin_schemas() {+ let server = JanToolServer::new(options(&PathBuf::from(".")));+ let read = server+ .tools()+ .into_iter()+ .find(|t| t.name == "read")+ .expect("read is served");+ let source = tauri_plugin_agent_tools::tools::schema::builtin_tool_schemas()+ .into_iter()+ .find(|s| s["function"]["name"] == "read")+ .expect("read has a schema");+ assert_eq!(+ serde_json::Value::Object((*read.input_schema).clone()),+ source["function"]["parameters"]+ );+ assert_eq!(+ read.description.as_deref(),+ source["function"]["description"].as_str()+ );+}++#[tokio::test]+async fn unserved_tool_is_refused_without_running() {+ let dir = tempfile::tempdir().expect("tempdir");+ let server = JanToolServer::new(options(dir.path()));+ let (content, _) = server+ .dispatch(+ "write",+ &serde_json::json!({ "path": "out.txt", "content": "hi" }),+ )+ .await;+ assert!(content.starts_with("ERROR"), "{content}");+ assert!(content.contains("not served"), "{content}");+ assert!(!dir.path().join("out.txt").exists());+}++#[tokio::test]+async fn unknown_tool_is_refused() {+ let dir = tempfile::tempdir().expect("tempdir");+ let server = JanToolServer::new(options(dir.path()));+ let (content, _) = server.dispatch("nope", &serde_json::json!({})).await;+ assert!(content.starts_with("ERROR: unknown tool"), "{content}");+}++#[tokio::test]+async fn grep_searches_inside_the_root() {+ let dir = tempfile::tempdir().expect("tempdir");+ std::fs::write(dir.path().join("a.txt"), "alpha needle omega\n").expect("write fixture");+ let server = JanToolServer::new(options(dir.path()));+ let (content, _) = server+ .dispatch("grep", &serde_json::json!({ "pattern": "needle" }))+ .await;+ assert!(!content.starts_with("ERROR"), "{content}");+ assert!(content.contains("a.txt"), "{content}");+}++#[tokio::test]+async fn grep_cannot_search_outside_the_root() {+ let dir = tempfile::tempdir().expect("tempdir");+ let outside = tempfile::tempdir().expect("tempdir");+ std::fs::write(outside.path().join("secret.txt"), "needle\n").expect("write fixture");+ let server = JanToolServer::new(options(dir.path()));+ let (content, _) = server+ .dispatch(+ "grep",+ &serde_json::json!({+ "pattern": "needle",+ "path": outside.path().to_string_lossy(),+ }),+ )+ .await;+ assert!(content.starts_with("ERROR"), "{content}");+ assert!(content.contains("escapes the served project root"), "{content}");+}++#[tokio::test]+async fn read_inside_the_root_works() {+ let dir = tempfile::tempdir().expect("tempdir");+ std::fs::write(dir.path().join("hello.txt"), "served\n").expect("write fixture");+ let server = JanToolServer::new(options(dir.path()));+ let (content, _) = server+ .dispatch("read", &serde_json::json!({ "path": "hello.txt" }))+ .await;+ assert!(content.contains("served"), "{content}");+}++#[tokio::test]+async fn escaping_read_path_is_refused() {+ let dir = tempfile::tempdir().expect("tempdir");+ let outside = tempfile::tempdir().expect("tempdir");+ let secret = outside.path().join("secret.txt");+ std::fs::write(&secret, "classified").expect("write fixture");+ let server = JanToolServer::new(options(dir.path()));+ let (content, _) = server+ .dispatch(+ "read",+ &serde_json::json!({ "path": secret.to_string_lossy() }),+ )+ .await;+ assert!(content.starts_with("ERROR"), "{content}");+ assert!(content.contains("escapes the served project root"), "{content}");+ assert!(!content.contains("classified"));+}++#[tokio::test]+async fn escaping_write_path_is_refused_even_when_write_is_served() {+ let dir = tempfile::tempdir().expect("tempdir");+ let outside = tempfile::tempdir().expect("tempdir");+ let target = outside.path().join("planted.txt");+ let mut opts = options(dir.path());+ opts.served.allow_write = true;+ let server = JanToolServer::new(opts);+ let (content, _) = server+ .dispatch(+ "write",+ &serde_json::json!({ "path": target.to_string_lossy(), "content": "x" }),+ )+ .await;+ assert!(content.starts_with("ERROR"), "{content}");+ assert!(content.contains("escapes the served project root"), "{content}");+ assert!(!target.exists());+}++#[tokio::test]+async fn hidden_jan_state_is_refused() {+ let dir = tempfile::tempdir().expect("tempdir");+ std::fs::create_dir_all(dir.path().join(".jan/agent")).expect("mkdir");+ std::fs::write(dir.path().join(".jan/agent/agent.toml"), "x = 1").expect("write fixture");+ let server = JanToolServer::new(options(dir.path()));+ let (content, _) = server+ .dispatch("read", &serde_json::json!({ "path": ".jan/agent/agent.toml" }))+ .await;+ assert!(content.starts_with("ERROR"), "{content}");+ assert!(content.contains("hidden .jan state"), "{content}");+}++#[tokio::test]+async fn in_project_write_runs_once_opted_in() {+ let dir = tempfile::tempdir().expect("tempdir");+ let mut opts = options(dir.path());+ opts.served.allow_write = true;+ let server = JanToolServer::new(opts);+ let (content, _) = server+ .dispatch(+ "write",+ &serde_json::json!({ "path": "note.txt", "content": "served write" }),+ )+ .await;+ assert!(!content.starts_with("ERROR"), "{content}");+ assert_eq!(+ std::fs::read_to_string(dir.path().join("note.txt")).expect("written"),+ "served write"+ );+}++#[test]+fn initialize_advertises_tools() {+ let server = JanToolServer::new(options(&PathBuf::from(".")));+ let info = server.get_info();+ assert!(info.capabilities.tools.is_some());+ assert_eq!(info.server_info.name, "jan");+}++#[test]+fn bearer_token_check_rejects_everything_but_the_token() {+ let token = generate_token();+ assert_eq!(token.len(), 64);+ let mut headers = hyper::HeaderMap::new();+ assert!(!authorized(&headers, &token), "no header");+ headers.insert(+ hyper::header::AUTHORIZATION,+ hyper::header::HeaderValue::from_str(&format!("Bearer {token}x")).unwrap(),+ );+ assert!(!authorized(&headers, &token), "wrong token");+ headers.insert(+ hyper::header::AUTHORIZATION,+ hyper::header::HeaderValue::from_str(&token).unwrap(),+ );+ assert!(!authorized(&headers, &token), "missing scheme");+ headers.insert(+ hyper::header::AUTHORIZATION,+ hyper::header::HeaderValue::from_str(&format!("Bearer {token}")).unwrap(),+ );+ assert!(authorized(&headers, &token));+}++/// The end-to-end shape an external agent sees: initialize, `tools/list`,+/// `tools/call`. Driven over an in-memory duplex rather than a spawned process,+/// which is the same transport type (`AsyncRead + AsyncWrite`) the stdio+/// transport is built from, without needing a second binary in the test.+#[tokio::test]+async fn list_and_call_round_trip_over_a_stream_transport() {+ let dir = tempfile::tempdir().expect("tempdir");+ std::fs::write(dir.path().join("round.txt"), "round trip\n").expect("write fixture");++ let (server_io, client_io) = tokio::io::duplex(8 * 1024);+ let server = JanToolServer::new(options(dir.path()));+ let server_task = tokio::spawn(async move {+ let running = server.serve(server_io).await.expect("server starts");+ let _ = running.waiting().await;+ });++ let client = ().serve(client_io).await.expect("client initializes");+ let info = client.peer_info().expect("server info");+ assert!(info.capabilities.tools.is_some());++ let tools = client.list_all_tools().await.expect("tools/list");+ let names: Vec<String> = tools.iter().map(|t| t.name.to_string()).collect();+ assert!(names.contains(&"read".to_string()), "{names:?}");+ assert!(!names.contains(&"bash".to_string()), "{names:?}");++ let result = client+ .call_tool(+ CallToolRequestParams::new("read").with_arguments(+ serde_json::json!({ "path": "round.txt" })+ .as_object()+ .cloned()+ .expect("object"),+ ),+ )+ .await+ .expect("tools/call");+ assert_ne!(result.is_error, Some(true));+ let text = result+ .content+ .iter()+ .filter_map(|b| b.as_text().map(|t| t.text.clone()))+ .collect::<String>();+ assert!(text.contains("round trip"), "{text}");++ // A denied tool comes back as a tool-level error the caller can read, not+ // as a transport failure.+ let denied = client+ .call_tool(+ CallToolRequestParams::new("bash").with_arguments(+ serde_json::json!({ "command": "echo nope" })+ .as_object()+ .cloned()+ .expect("object"),+ ),+ )+ .await+ .expect("tools/call reaches the handler");+ assert_eq!(denied.is_error, Some(true));++ client.cancel().await.ok();+ server_task.abort();+}++/// `stdio()` is what the transport module hands to rmcp; assert it stays the+/// pair the server is built from, so a refactor cannot silently swap stdout for+/// something else and corrupt the framing.+#[test]+fn stdio_transport_is_stdin_stdout() {+ let (_stdin, _stdout) = stdio();+}