Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(mcp): report bash failures as isError, plus review follow-ups (#9013)

Akarshan Biswas35508d16bd9d
diff --git a/docs/src/pages/docs/agent/cli.mdx b/docs/src/pages/docs/agent/cli.mdx
index 9861844f9..2148047a6 100644
--- a/docs/src/pages/docs/agent/cli.mdx
+++ b/docs/src/pages/docs/agent/cli.mdx
@@ -396,6 +396,34 @@ added servers default to inactive, so they are persisted but not connected until
See [MCP](/docs/agent/mcp).
+## `jan mcp serve`
+
+The other direction: serve Jan's own built-in tools to another MCP client. One project root, fixed
+at startup; a path argument that escapes it is refused, and so is the project's hidden `.jan` state.
+
+```bash
+jan mcp serve --project . # stdio, for a client that spawns it as a child
+jan mcp serve --transport http # loopback HTTP; prints its URL and bearer token
+jan mcp serve --allow-write --allow-exec # add the mutating and shell tools
+jan mcp serve --tool read --tool grep # narrow the set
+```
+
+| Flag | Description |
+| --- | --- |
+| `--project <PATH>` | Project root the served tools are confined to. Defaults to `.` |
+| `--transport <T>` | `stdio` (default) or `http` |
+| `--port <PORT>` | Port for `http`. Defaults to an ephemeral one |
+| `--token <TOKEN>` | Bearer token for `http`. One is generated and printed if omitted |
+| `--allow-write` | Offer `write` and `edit`, confined to the project root |
+| `--allow-exec` | Offer `bash`, under the same OS sandbox the agent's shell uses |
+| `--tool <NAME>` | Serve only these tools. Repeatable; never widens what the flags above permit |
+
+The default set touches no project file, and the two classes that can change the machine are opt-in:
+the caller is another program, so anything that would wait for an approval returns an error rather
+than blocking. On `http` the listener is loopback-only and every request must carry the token.
+
+See [Serving Jan's own tools](/docs/agent/mcp#serving-jans-own-tools).
+
## `jan update`
Update the binary to the latest build of the channel it was built for.
diff --git a/docs/src/pages/docs/agent/mcp.mdx b/docs/src/pages/docs/agent/mcp.mdx
index b82f3a880..24957c6c6 100644
--- a/docs/src/pages/docs/agent/mcp.mdx
+++ b/docs/src/pages/docs/agent/mcp.mdx
@@ -122,7 +122,7 @@ files --command npx --arg -y --arg my-mcp`, `jan cli mcp list`, `jan cli mcp rem
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.
+client can call them. See the [CLI reference](/docs/agent/cli#jan-mcp-serve) for every flag.
```bash
jan mcp serve --project . # stdio, what another agent spawns as a child process
@@ -133,9 +133,14 @@ The served tools run against **one project root**, fixed when the server starts,
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:
+The default set touches no project file: file reading, search, the web tools, and the memory and
+skill tools. Those last two do write, but only into the agent's own store under `.jan/agent` and
+only by sanitized name, so they can never reach a file in your project. Note that a skill written
+this way is an instruction Jan's own agent may later read, so a peer you would not trust to write
+instructions should be narrowed with `--tool`.
+
+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 |
| --- | --- |
diff --git a/src-tauri/src/core/cli/mcp_serve.rs b/src-tauri/src/core/cli/mcp_serve.rs
index f79b418ee..d98c237e6 100644
--- a/src-tauri/src/core/cli/mcp_serve.rs
+++ b/src-tauri/src/core/cli/mcp_serve.rs
@@ -52,6 +52,15 @@ fn options_for(project: &str, flags: &ServeFlags) -> Result<ServeOptions, String
Ok(opts)
}
+/// The `--tool` names that are not built-ins. `lookup()` is the authority on
+/// what a built-in is, so this cannot drift from what is actually servable.
+fn unknown_tool_names(only: &[String]) -> Vec<String> {
+ only.iter()
+ .filter(|n| tauri_plugin_agent_tools::tools::lookup(n).is_none())
+ .cloned()
+ .collect()
+}
+
/// Run the server until the peer disconnects (stdio) or the process is stopped
/// (http).
pub async fn cli_mcp_serve(
@@ -60,6 +69,14 @@ pub async fn cli_mcp_serve(
flags: ServeFlags,
) -> Result<(), String> {
let opts = options_for(project, &flags)?;
+ // Always to stderr: on stdio, stdout is the JSON-RPC stream.
+ let unknown = unknown_tool_names(&flags.only);
+ if !unknown.is_empty() {
+ eprintln!(
+ "jan mcp serve: warning: unknown --tool name(s): {}. Nothing is served for them.",
+ unknown.join(", ")
+ );
+ }
match transport {
ServeTransport::Stdio => {
// stdout is the JSON-RPC stream from here on; the startup notice
@@ -128,6 +145,22 @@ mod tests {
assert_eq!(opts.enabled_skills, vec!["jan".to_string()]);
}
+ /// A mistyped `--tool` serves an empty set and exits 0, which looks like a
+ /// working server that offers nothing. Name the unknown ones so the typo is
+ /// fixable.
+ #[test]
+ fn unknown_tool_names_are_reported() {
+ assert_eq!(unknown_tool_names(&[]), Vec::<String>::new());
+ assert_eq!(
+ unknown_tool_names(&["read".into(), "grep".into()]),
+ Vec::<String>::new()
+ );
+ assert_eq!(
+ unknown_tool_names(&["read".into(), "nope".into(), "alsonope".into()]),
+ vec!["nope".to_string(), "alsonope".to_string()]
+ );
+ }
+
#[test]
fn a_missing_project_is_an_error_not_a_panic() {
let err = options_for("/definitely/not/here", &ServeFlags::default())
diff --git a/src-tauri/src/core/mcp/server/http.rs b/src-tauri/src/core/mcp/server/http.rs
index e3ad70d9e..81f8a618a 100644
--- a/src-tauri/src/core/mcp/server/http.rs
+++ b/src-tauri/src/core/mcp/server/http.rs
@@ -58,12 +58,15 @@ pub fn authorized(headers: &hyper::HeaderMap, token: &str) -> bool {
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;
+ // RFC 7235: the auth-scheme is case-insensitive. Only the scheme -- the
+ // credential keeps its constant-time byte compare below.
+ let (scheme, presented) = match value.split_once(' ') {
+ Some(parts) => parts,
+ None => return false,
};
+ if !scheme.eq_ignore_ascii_case("bearer") {
+ return false;
+ }
constant_time_eq(presented.as_bytes(), token.as_bytes())
}
diff --git a/src-tauri/src/core/mcp/server/mod.rs b/src-tauri/src/core/mcp/server/mod.rs
index fd5c17af2..ab8425879 100644
--- a/src-tauri/src/core/mcp/server/mod.rs
+++ b/src-tauri/src/core/mcp/server/mod.rs
@@ -29,7 +29,7 @@ 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::handlers::{bash_result_failed, execute_builtin};
use tauri_plugin_agent_tools::tools::schema::{builtin_tool_schemas, search_tool_schemas};
use tauri_plugin_agent_tools::tools::{lookup, Capability, ToolContext};
@@ -317,7 +317,11 @@ impl ServerHandler for JanToolServer {
) -> 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");
+ // Same two clauses the agent loop uses. `bash` reports a non-zero exit
+ // as an `[exit N]` trailer rather than an `ERROR` prefix, so the prefix
+ // alone would tell a peer that a command which exited 3 succeeded.
+ let is_error = content.starts_with("ERROR")
+ || (request.name == "bash" && bash_result_failed(&content));
blocks.insert(0, ContentBlock::text(content));
let result = if is_error {
CallToolResult::error(blocks)
diff --git a/src-tauri/src/core/mcp/server/tests.rs b/src-tauri/src/core/mcp/server/tests.rs
index 0190ebc8b..8395ac0d9 100644
--- a/src-tauri/src/core/mcp/server/tests.rs
+++ b/src-tauri/src/core/mcp/server/tests.rs
@@ -4,7 +4,6 @@
use std::path::PathBuf;
use rmcp::model::CallToolRequestParams;
-use rmcp::transport::io::stdio;
use rmcp::{ServiceExt, ServerHandler};
use super::http::{authorized, generate_token};
@@ -276,6 +275,34 @@ fn bearer_token_check_rejects_everything_but_the_token() {
assert!(authorized(&headers, &token));
}
+/// RFC 7235 makes the auth-scheme case-insensitive, so a client that sends
+/// `BEARER` is presenting a valid credential and must not be turned away. The
+/// token itself stays case-sensitive.
+#[test]
+fn bearer_scheme_is_case_insensitive_but_the_token_is_not() {
+ let token = generate_token();
+ let mut headers = hyper::HeaderMap::new();
+ for scheme in ["Bearer", "bearer", "BEARER", "BeArEr"] {
+ headers.insert(
+ hyper::header::AUTHORIZATION,
+ hyper::header::HeaderValue::from_str(&format!("{scheme} {token}")).unwrap(),
+ );
+ assert!(authorized(&headers, &token), "scheme {scheme} must be accepted");
+ }
+
+ headers.insert(
+ hyper::header::AUTHORIZATION,
+ hyper::header::HeaderValue::from_str(&format!("Bearer {}", token.to_uppercase())).unwrap(),
+ );
+ assert!(!authorized(&headers, &token), "the credential is case-sensitive");
+
+ headers.insert(
+ hyper::header::AUTHORIZATION,
+ hyper::header::HeaderValue::from_str(&format!("Basic {token}")).unwrap(),
+ );
+ assert!(!authorized(&headers, &token), "a different scheme is not a bearer");
+}
+
/// 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
@@ -339,10 +366,55 @@ async fn list_and_call_round_trip_over_a_stream_transport() {
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();
+/// A shell command that fails must reach the peer as `isError: true`.
+///
+/// `bash` deliberately does not prefix `ERROR` on a non-zero exit, so the
+/// prefix alone is a strictly narrower predicate than the agent loop's and
+/// reports a failed command as a success to a caller that trusts the protocol
+/// field. Driven through a real client because `is_error` is decided in
+/// `call_tool`, which `dispatch` never reaches.
+#[tokio::test]
+async fn bash_exit_status_decides_is_error() {
+ let dir = tempfile::tempdir().expect("tempdir");
+ let mut opts = options(dir.path());
+ opts.served.allow_exec = true;
+
+ let (server_io, client_io) = tokio::io::duplex(8 * 1024);
+ let server = JanToolServer::new(opts);
+ 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");
+
+ for (command, expected) in [
+ ("exit 3", Some(true)),
+ ("kill -TERM $$", Some(true)),
+ ("echo fine", Some(false)),
+ ] {
+ let result = client
+ .call_tool(
+ CallToolRequestParams::new("bash").with_arguments(
+ serde_json::json!({ "command": command })
+ .as_object()
+ .cloned()
+ .expect("object"),
+ ),
+ )
+ .await
+ .expect("tools/call reaches the handler");
+ let text = result
+ .content
+ .iter()
+ .filter_map(|b| b.as_text().map(|t| t.text.clone()))
+ .collect::<String>();
+ assert_eq!(
+ result.is_error, expected,
+ "`{command}` reported is_error={:?}; content: {text}",
+ result.is_error
+ );
+ }
+
+ client.cancel().await.ok();
+ server_task.abort();
}