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.

feat(mcp): OAuth for remote servers, and a real /mcp management screen (#8735)

Akarshan Biswas49695a1f4186
diff --git a/docs/src/pages/docs/agent/mcp.mdx b/docs/src/pages/docs/agent/mcp.mdx
index f28e351d7..5d4fe6abd 100644
--- a/docs/src/pages/docs/agent/mcp.mdx
+++ b/docs/src/pages/docs/agent/mcp.mdx
@@ -42,15 +42,18 @@ half-connected one. A slow stdio server delays that first turn, not the whole se
/mcp
```
-Lists every configured server with its state. <kbd>Enter</kbd> toggles the highlighted one. Turning
-one on connects it in the background; the tools appear once it lands.
+Lists every configured server with its state. <kbd>Space</kbd> toggles the highlighted one; turning
+one on connects it in the background and the tools appear once it lands. <kbd>Enter</kbd> opens the
+server's detail screen (see below).
-While the picker is open you can also manage the list itself:
+While the list is open you can also manage it:
- <kbd>a</kbd> opens an add form (`name`, transport, then the transport-specific fields)
- <kbd>e</kbd> edits the highlighted server, prefilled
- <kbd>d</kbd> removes the highlighted server after writing it out
+The list opens even with nothing configured, so <kbd>a</kbd> is reachable on a fresh install.
+
Inside the form, arrow keys (or <kbd>Tab</kbd>) move between fields. <kbd>k</kbd> and <kbd>j</kbd>
type as ordinary characters - URLs, paths, and header values contain them - so they no longer
steer between fields as they did in earlier releases.
@@ -60,6 +63,51 @@ it on.
The change is written back to `mcp_config.json`, so it persists - and applies to Jan Desktop too.
+### The server detail screen
+
+<kbd>Enter</kbd> on a row opens that server on its own screen: transport, endpoint or command, the
+`mcp_config.json` path it came from, connection state, authentication state, the tool count, and the
+name and version the server reported when it connected. Everything there is read from local state,
+so it opens immediately; only the tool listing is a round trip and it fills in when it lands.
+
+The actions below the info block are filtered to what the server can actually do - no sign-in rows
+for a stdio server, no `View tools` while it is disconnected, no `Reconnect` while it is disabled:
+
+- `View tools` prints the tool names into the conversation, where they scroll and persist
+- `Authenticate` / `Re-authenticate` runs the OAuth flow (see below)
+- `Clear authentication` forgets the stored tokens and drops the connection, which still holds the
+ old one. The server stays enabled, so signing back in brings it up again
+- `Reconnect`, `Enable` / `Disable`, `Edit configuration`, `Remove server`
+
+<kbd>Esc</kbd> steps back to the list rather than out of `/mcp`.
+
+### Signing in to a remote server
+
+Remote (`http` / `sse`) servers that require OAuth are handled for you: Jan discovers the provider's
+metadata, registers itself dynamically, and runs the authorization-code flow with PKCE against a
+loopback redirect. `Authenticate` prints the consent URL into the conversation *before* it starts
+waiting, and opens it in your browser - so a remote or headless session can still finish the sign-in
+by opening the URL by hand. The wait times out after five minutes.
+
+A server that fails to connect purely for want of a sign-in says so, rather than reporting a
+transport error: Jan asks the server whether it advertises OAuth instead of guessing from the
+failure.
+
+Tokens are written to `mcp_oauth.json`, next to `mcp_config.json` in the Jan data folder, with
+`0600` permissions:
+
+- **not in `mcp_config.json`**, which is hand-edited, copied between machines and shared with Jan
+ Desktop; bearer tokens have no business travelling with it
+- Access tokens are refreshed automatically, a minute before they expire, when the provider issued a
+ refresh token
+- Changing a server's `url` invalidates its stored tokens rather than silently sending credentials
+ issued for a different resource
+- Removing a server clears its tokens too, so a later server reusing the name does not inherit the
+ authorization
+
+If you set an `Authorization` header by hand, that wins: OAuth is never attempted and never reported
+as missing, because wrapping it would put two credentials on one request.
+
### From the command line
Add, list, edit, remove, and toggle servers headlessly with `jan cli mcp ...` - `jan cli mcp add
diff --git a/docs/src/pages/docs/agent/slash-commands.mdx b/docs/src/pages/docs/agent/slash-commands.mdx
index 122602a5a..6fd08014b 100644
--- a/docs/src/pages/docs/agent/slash-commands.mdx
+++ b/docs/src/pages/docs/agent/slash-commands.mdx
@@ -57,7 +57,7 @@ See [Run modes](/docs/agent/run-modes), [Goals and todos](/docs/agent/goals-and-
| --- | --- |
| `/model [id]` | Switch model. Bare: pick interactively |
| `/effort [low\|medium\|high]` | Set reasoning effort. Bare: show current; `low` is faster, `high` thinks deeper |
-| `/mcp` | List, toggle, add, edit, and remove MCP servers |
+| `/mcp` | List, toggle, add, edit, and remove MCP servers; Enter opens a server's detail screen, where you can list its tools and sign in to it |
| `/plugin [list\|install <spec>\|remove <name>\|search [query]]` | Manage plugins: install from a git URL or the marketplace, list/remove installed, search the marketplace |
| `/login` | Sign in to Tokamak and save the API key |
| `/config` | View provider config (`~/.jan/config.toml`) |
diff --git a/docs/src/pages/docs/desktop/integrations/mcp-servers.mdx b/docs/src/pages/docs/desktop/integrations/mcp-servers.mdx
index 4885294a9..459651cde 100644
--- a/docs/src/pages/docs/desktop/integrations/mcp-servers.mdx
+++ b/docs/src/pages/docs/desktop/integrations/mcp-servers.mdx
@@ -47,6 +47,33 @@ Toggle the server on. It will appear in the list with a green indicator when act
</Steps>
+## Authentication
+
+Each remote (`HTTP` / `SSE`) server shows an **Auth** line with its current state and the actions
+that state allows.
+
+- **Sign in** runs OAuth against the server: Jan discovers the provider's metadata, registers itself
+ dynamically, and completes the authorization-code flow with PKCE against a loopback redirect. Your
+ browser opens automatically; if it does not, use the **Open the sign-in page** link that appears
+ while the flow is pending. The wait times out after five minutes.
+- **Clear authentication** forgets the stored tokens and disconnects the server, since the live
+ connection still holds the old token. The server stays configured, so signing back in brings it up
+ again.
+
+A server that fails to connect purely for want of a sign-in says so, instead of showing a transport
+error - Jan asks the server whether it advertises OAuth rather than guessing from the failure.
+
+Tokens are stored in `mcp_oauth.json` in the Jan data folder, next to `mcp_config.json` and never
+inside it, with owner-only permissions. They are refreshed automatically shortly before they expire
+when the provider issued a refresh token. Changing a server's URL invalidates its tokens rather than
+sending credentials issued for a different endpoint, and removing a server clears them too.
+
+<Callout type="info">
+If you set an `Authorization` header on a server yourself, that credential is used as-is: OAuth is
+never attempted and never reported as missing, because wrapping it would put two credentials on one
+request.
+</Callout>
+
<Callout type="info">
Find more MCP servers at [mcp.so](https://mcp.so).
</Callout>
\ No newline at end of file
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lock
index 9e847a9ad..cb150c753 100644
--- a/src-tauri/Cargo.lock
+++ b/src-tauri/Cargo.lock
@@ -20,6 +20,7 @@ dependencies = [
"env_logger",
"fix-path-env",
"flate2",
+ "form_urlencoded",
"futures",
"futures-util",
"glob",
@@ -39,6 +40,7 @@ dependencies = [
"log",
"machine-uid",
"nix 0.30.1",
+ "oauth2",
"once_cell",
"png 0.17.16",
"pulldown-cmark",
@@ -81,6 +83,7 @@ dependencies = [
"tokio-util",
"toml 0.8.2",
"toml_edit 0.23.10+spec-1.0.0",
+ "unicode-width 0.2.2",
"url",
"uuid",
"windows-sys 0.60.2",
@@ -4271,6 +4274,26 @@ dependencies = [
"libloading 0.8.9",
]
+[[package]]
+name = "oauth2"
+version = "5.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "51e219e79014df21a225b1860a479e2dcd7cbd9130f4defd4bd0e191ea31d67d"
+dependencies = [
+ "base64 0.22.1",
+ "chrono",
+ "getrandom 0.2.17",
+ "http",
+ "rand 0.8.7",
+ "reqwest 0.12.28",
+ "serde",
+ "serde_json",
+ "serde_path_to_error",
+ "sha2",
+ "thiserror 1.0.69",
+ "url",
+]
+
[[package]]
name = "objc"
version = "0.2.7"
@@ -5810,6 +5833,7 @@ dependencies = [
"chrono",
"futures",
"http",
+ "oauth2",
"paste",
"pin-project-lite",
"process-wrap",
@@ -5825,6 +5849,7 @@ dependencies = [
"tokio-util",
"tower-service",
"tracing",
+ "url",
]
[[package]]
@@ -6263,6 +6288,17 @@ dependencies = [
"zmij",
]
+[[package]]
+name = "serde_path_to_error"
+version = "0.1.20"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
+dependencies = [
+ "itoa",
+ "serde",
+ "serde_core",
+]
+
[[package]]
name = "serde_repr"
version = "0.1.20"
diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.toml
index da2073ce4..f9f5abd4e 100644
--- a/src-tauri/Cargo.toml
+++ b/src-tauri/Cargo.toml
@@ -93,7 +93,7 @@ test-tauri = [
"deep-link",
"hardware",
]
-cli = ["dep:env_logger", "dep:indicatif", "dep:console", "dep:ratatui", "dep:pulldown-cmark", "dep:syntect", "dep:comfy-table", "dep:arboard", "dep:png"]
+cli = ["dep:env_logger", "dep:indicatif", "dep:console", "dep:ratatui", "dep:unicode-width", "dep:pulldown-cmark", "dep:syntect", "dep:comfy-table", "dep:arboard", "dep:png"]
[build-dependencies]
tauri-build = { version = "2.0.2", features = [], optional = true }
@@ -105,6 +105,7 @@ async-trait = "0.1"
env = "1.0.1"
fix-path-env = { git = "https://github.com/tauri-apps/fix-path-env-rs", optional = true }
flate2 = "1.0"
+form_urlencoded = "1.2"
futures-util = "0.3.31"
hex = "0.4"
hmac = "0.12"
@@ -115,8 +116,12 @@ tokio-stream = "0.1"
jan-utils = { path = "./utils" }
libloading = "0.8.7"
log = "0.4"
+# Pulled in by rmcp's `auth` feature; used directly for `TokenResponse`
+# accessors on the persisted token record (`core::mcp::oauth`).
+oauth2 = "5.0"
rand = "0.8"
rmcp = { version = "0.8.5", features = [
+ "auth",
"client",
"transport-sse-client",
"transport-sse-client-reqwest",
@@ -202,6 +207,10 @@ keyring = { version = "3", features = [
aes-gcm = "0.10"
machine-uid = "0.5"
ratatui = { version = "0.30", optional = true, features = ["unstable-rendered-line-info"] }
+# Display width for the TUI's own truncation: a CJK glyph or emoji is two
+# cells wide, so counting chars overflows a bordered panel. Already in the graph
+# via ratatui; named here because this crate calls it directly.
+unicode-width = { version = "0.2", optional = true }
pulldown-cmark = { version = "0.13", optional = true, default-features = false }
# `regex-fancy` keeps this pure Rust: the default `onig` backend links libonig,
# which the headless CLI must not pull in. The raw `.sublime-syntax`/`.tmTheme`
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
index f3ebf721d..78666074a 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/commands.rs
@@ -1106,7 +1106,7 @@ pub async fn try_graceful_stop_router<R: Runtime>(
}
Err((h, busy)) => {
let mut guard = state.router.lock().await;
- *guard = Some(h);
+ *guard = Some(*h);
Ok(Some(busy))
}
}
diff --git a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs
index 23c47b11f..53a1f7e9a 100644
--- a/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs
+++ b/src-tauri/plugins/tauri-plugin-llamacpp/src/router.rs
@@ -753,7 +753,7 @@ pub async fn stop_router(handle: RouterHandle) -> ServerResult<()> {
busy.len(),
busy
);
- force_kill_router_tree(h).await;
+ force_kill_router_tree(*h).await;
Ok(())
}
}
@@ -763,7 +763,7 @@ pub async fn stop_router(handle: RouterHandle) -> ServerResult<()> {
pub async fn try_graceful_stop_router(
mut handle: RouterHandle,
deadline: Duration,
-) -> Result<(), (RouterHandle, Vec<String>)> {
+) -> Result<(), (Box<RouterHandle>, Vec<String>)> {
let start = Instant::now();
let client = match reqwest::Client::builder().build() {
@@ -799,7 +799,7 @@ pub async fn try_graceful_stop_router(
processing.len(),
processing
);
- return Err((handle, processing));
+ return Err((Box::new(handle), processing));
}
if !initial.is_empty() {
@@ -838,7 +838,7 @@ pub async fn try_graceful_stop_router(
deadline,
still.len()
);
- return Err((handle, still));
+ return Err((Box::new(handle), still));
}
let remaining = deadline - elapsed;
tokio::time::sleep(Duration::from_millis(150).min(remaining)).await;
diff --git a/src-tauri/src/core/app/commands.rs b/src-tauri/src/core/app/commands.rs
index a1db403a1..0bb40e8c0 100644
--- a/src-tauri/src/core/app/commands.rs
+++ b/src-tauri/src/core/app/commands.rs
@@ -119,6 +119,28 @@ pub fn resolve_config_file_path() -> PathBuf {
app_data.join(CONFIGURATION_FILE_NAME)
}
+/// Run `f` with `JAN_DATA_FOLDER` pointed at a fresh temp directory, restoring
+/// the previous value afterwards. Serialized on its own lock: the env is
+/// process-wide and Rust runs tests on threads, so two of these overlapping
+/// would each see the other's folder.
+#[cfg(all(test, feature = "cli"))]
+pub(crate) fn with_temp_data_folder<T>(f: impl FnOnce(&std::path::Path) -> T) -> T {
+ use std::sync::Mutex;
+
+ static ENV_LOCK: Mutex<()> = Mutex::new(());
+ let _guard = ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+
+ let dir = tempfile::tempdir().expect("tempdir");
+ let prev = std::env::var_os("JAN_DATA_FOLDER");
+ std::env::set_var("JAN_DATA_FOLDER", dir.path());
+ let result = f(dir.path());
+ match prev {
+ Some(p) => std::env::set_var("JAN_DATA_FOLDER", p),
+ None => std::env::remove_var("JAN_DATA_FOLDER"),
+ }
+ result
+}
+
/// Resolve the Jan data folder path without an AppHandle (for CLI use).
/// Reads AppConfiguration from the config file; falls back to the default location.
pub fn resolve_jan_data_folder() -> PathBuf {
diff --git a/src-tauri/src/core/cli/browser.rs b/src-tauri/src/core/cli/browser.rs
new file mode 100644
index 000000000..39d2e36dc
--- /dev/null
+++ b/src-tauri/src/core/cli/browser.rs
@@ -0,0 +1,50 @@
+//! Best-effort browser launch, shared by `/login` (Tokamak sign-in) and the
+//! `/mcp` OAuth flow.
+//!
+//! Every caller prints the URL as well, because a spawned launcher reports
+//! nothing about whether a page actually appeared: `Err` here is a reason to
+//! *say* "open this yourself", never a reason to abandon the flow.
+
+/// Hand `url` to the platform's opener. `Err` carries a reason worth showing
+/// the user, not a failure to recover from.
+pub fn open(url: &str) -> Result<(), String> {
+ if cfg!(test) {
+ // A test run must never take over the developer's browser.
+ return Err("browser launch is disabled under test".to_string());
+ }
+ launch(url)
+}
+
+fn launch(url: &str) -> Result<(), String> {
+ #[cfg(target_os = "macos")]
+ let (program, args): (&str, &[&str]) = ("open", &[]);
+ #[cfg(target_os = "windows")]
+ let (program, args): (&str, &[&str]) = ("cmd", &["/C", "start", ""]);
+ #[cfg(all(unix, not(target_os = "macos")))]
+ let (program, args): (&str, &[&str]) = ("xdg-open", &[]);
+
+ #[cfg(all(unix, not(target_os = "macos")))]
+ if !has_display() {
+ return Err("no graphical session detected".to_string());
+ }
+
+ std::process::Command::new(program)
+ .args(args)
+ .arg(url)
+ .stdin(std::process::Stdio::null())
+ .stdout(std::process::Stdio::null())
+ .stderr(std::process::Stdio::null())
+ .spawn()
+ .map(|_| ())
+ .map_err(|e| format!("could not launch {program}: {e}"))
+}
+
+/// Whether a Linux/BSD session has a display server to open a browser on. Over
+/// SSH or in a container `xdg-open` would either fail noisily or block, so the
+/// caller falls back to printing the URL.
+#[cfg(all(unix, not(target_os = "macos")))]
+fn has_display() -> bool {
+ ["WAYLAND_DISPLAY", "DISPLAY"]
+ .iter()
+ .any(|var| std::env::var_os(var).is_some_and(|v| !v.is_empty()))
+}
diff --git a/src-tauri/src/core/cli/mcp.rs b/src-tauri/src/core/cli/mcp.rs
index fbf16a06e..c7a26ff8e 100644
--- a/src-tauri/src/core/cli/mcp.rs
+++ b/src-tauri/src/core/cli/mcp.rs
@@ -15,7 +15,8 @@ use std::process::Stdio;
use rmcp::{
model::{ClientCapabilities, ClientInfo, Implementation},
transport::{
- sse_client::SseClientConfig, streamable_http_client::StreamableHttpClientTransportConfig,
+ sse_client::{SseClient, SseClientConfig},
+ streamable_http_client::{StreamableHttpClient, StreamableHttpClientTransportConfig},
SseClientTransport, StreamableHttpClientTransport, TokioChildProcess,
},
ServiceExt,
@@ -26,6 +27,7 @@ use tokio::process::Command;
use crate::core::app::commands::resolve_jan_data_folder;
use crate::core::mcp::models::McpSettings;
use crate::core::mcp::models::{extract_active_status, extract_command_args};
+use crate::core::mcp::oauth;
use crate::core::state::{RunningServiceEnum, SharedMcpServers};
/// The Jan Browser MCP needs the desktop bridge/lockfile machinery, so it is
@@ -332,53 +334,109 @@ pub fn parse_pairs(s: &str, what: &str) -> Result<serde_json::Map<String, Value>
Ok(map)
}
+/// Why a connect failed, when the difference changes what the user should do.
+///
+/// A missing binary and an unauthorized remote both surface as "failed to
+/// connect" from the transport, but only one of them is fixed by signing in --
+/// so the distinction is carried in the type rather than left for the UI to
+/// guess from an error string.
+#[derive(Debug)]
+pub enum ConnectError {
+ /// The server advertises OAuth and there are no usable credentials for it.
+ /// `/mcp` turns this into an `Authenticate` action.
+ NeedsAuth { server: String, detail: String },
+ Failed(String),
+}
+
+impl std::fmt::Display for ConnectError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::NeedsAuth { server, detail } => {
+ write!(f, "'{server}' needs authentication: {detail}")
+ }
+ Self::Failed(e) => f.write_str(e),
+ }
+ }
+}
+
+impl ConnectError {
+ pub fn needs_auth(&self) -> bool {
+ matches!(self, Self::NeedsAuth { .. })
+ }
+}
+
+impl From<String> for ConnectError {
+ fn from(e: String) -> Self {
+ Self::Failed(e)
+ }
+}
+
/// Connect one server and insert it into the shared map. Best-effort: a bad
/// transport/config returns `Err` without touching the map.
+///
+/// For http/sse this is where OAuth is applied: stored credentials (refreshed
+/// if stale) are wrapped around the base client so every request carries the
+/// bearer token. When there are none and the connect fails, the server is asked
+/// whether it advertises OAuth at all, which is what separates
+/// `ConnectError::NeedsAuth` from an ordinary transport failure.
pub async fn connect(
name: &str,
config: &Value,
servers: &SharedMcpServers,
-) -> Result<(), String> {
+) -> Result<(), ConnectError> {
+ connect_in(&default_data_folder(), name, config, servers).await
+}
+
+async fn connect_in(
+ data_folder: &std::path::Path,
+ name: &str,
+ config: &Value,
+ servers: &SharedMcpServers,
+) -> Result<(), ConnectError> {
if name == BROWSER_MCP_NAME {
- return Err("Jan Browser MCP is desktop-only".to_string());
+ return Err(ConnectError::Failed(
+ "Jan Browser MCP is desktop-only".to_string(),
+ ));
}
let params = extract_command_args(config)
- .ok_or_else(|| format!("invalid MCP config for '{name}'"))?;
+ .ok_or_else(|| ConnectError::Failed(format!("invalid MCP config for '{name}'")))?;
let service = match (params.transport_type.as_deref(), params.url.as_deref()) {
- (Some("http"), Some(url)) => {
- let client = http_client(&params.headers)?;
- let transport = StreamableHttpClientTransport::with_client(
- client,
- StreamableHttpClientTransportConfig {
- uri: url.to_string().into(),
- ..Default::default()
- },
- );
- RunningServiceEnum::WithInit(
- client_info()
- .serve(transport)
- .await
- .map_err(|e| format!("failed to connect to '{name}': {e}"))?,
- )
- }
- (Some("sse"), Some(url)) => {
- let client = http_client(&params.headers)?;
- let transport = SseClientTransport::start_with_client(
- client,
- SseClientConfig {
- sse_endpoint: url.to_string().into(),
- ..Default::default()
- },
- )
- .await
- .map_err(|e| format!("failed to start SSE transport for '{name}': {e}"))?;
- RunningServiceEnum::WithInit(
- client_info()
- .serve(transport)
- .await
- .map_err(|e| format!("failed to connect to '{name}': {e}"))?,
- )
+ (Some(transport @ ("http" | "sse")), Some(url)) => {
+ let base = http_client(&params.headers)?;
+ // A credential problem we can already name (expired with no refresh
+ // token, or issued for a different url) is `NeedsAuth` outright --
+ // there is no point attempting a connect we know is unauthorized.
+ let auth = oauth::authorized_client(data_folder, name, url, config, base.clone())
+ .await
+ .map_err(|detail| ConnectError::NeedsAuth {
+ server: name.to_string(),
+ detail,
+ })?;
+ let authorized = auth.is_some();
+ let result = match (transport, auth) {
+ ("http", Some(client)) => serve_http(client, url, name).await,
+ ("http", None) => serve_http(base, url, name).await,
+ (_, Some(client)) => serve_sse(client, url, name).await,
+ (_, None) => serve_sse(base, url, name).await,
+ };
+ match result {
+ Ok(service) => service,
+ // Only worth probing when we did not already send a token: a
+ // failure *with* credentials is either a real outage or tokens
+ // the provider revoked, and `advertises_oauth` cannot tell the
+ // difference. Re-authenticating is offered from `/mcp` anyway.
+ Err(e) if !authorized && oauth::advertises_oauth(url).await => {
+ // The transport error is kept: a server can advertise OAuth
+ // *and* have failed for an unrelated reason, and dropping
+ // the cause would report that as "needs authentication".
+ return Err(ConnectError::NeedsAuth {
+ server: name.to_string(),
+ detail: format!("no credentials are stored ({e})"),
+ });
+ }
+ Err(e) => return Err(ConnectError::Failed(e)),
+ }
}
_ => {
let mut cmd = Command::new(&params.command);
@@ -403,12 +461,12 @@ pub async fn connect(
let (process, _stderr) = TokioChildProcess::builder(cmd)
.stderr(Stdio::null())
.spawn()
- .map_err(|e| format!("failed to spawn '{name}': {e}"))?;
+ .map_err(|e| ConnectError::Failed(format!("failed to spawn '{name}': {e}")))?;
RunningServiceEnum::NoInit(
()
.serve(process)
.await
- .map_err(|e| format!("failed to connect to '{name}': {e}"))?,
+ .map_err(|e| ConnectError::Failed(format!("failed to connect to '{name}': {e}")))?,
)
}
};
@@ -417,6 +475,50 @@ pub async fn connect(
Ok(())
}
+/// Serve the streamable-http transport over any client that implements it, so
+/// the plain and OAuth-wrapped clients share one code path instead of the
+/// transport construction being written out twice.
+async fn serve_http<C>(client: C, url: &str, name: &str) -> Result<RunningServiceEnum, String>
+where
+ C: StreamableHttpClient + Send + Sync + 'static,
+{
+ let transport = StreamableHttpClientTransport::with_client(
+ client,
+ StreamableHttpClientTransportConfig {
+ uri: url.to_string().into(),
+ ..Default::default()
+ },
+ );
+ Ok(RunningServiceEnum::WithInit(
+ client_info()
+ .serve(transport)
+ .await
+ .map_err(|e| format!("failed to connect to '{name}': {e}"))?,
+ ))
+}
+
+/// `serve_http`'s counterpart for the legacy SSE transport.
+async fn serve_sse<C>(client: C, url: &str, name: &str) -> Result<RunningServiceEnum, String>
+where
+ C: SseClient + Send + Sync + 'static,
+{
+ let transport = SseClientTransport::start_with_client(
+ client,
+ SseClientConfig {
+ sse_endpoint: url.to_string().into(),
+ ..Default::default()
+ },
+ )
+ .await
+ .map_err(|e| format!("failed to start SSE transport for '{name}': {e}"))?;
+ Ok(RunningServiceEnum::WithInit(
+ client_info()
+ .serve(transport)
+ .await
+ .map_err(|e| format!("failed to connect to '{name}': {e}"))?,
+ ))
+}
+
fn client_info() -> ClientInfo {
ClientInfo {
protocol_version: Default::default(),
@@ -467,6 +569,159 @@ pub async fn disconnect(name: &str, servers: &SharedMcpServers) {
}
}
+/// The `mcp_config.json` a server is declared in. Surfaced by the `/mcp` detail
+/// screen: "where do I edit this by hand" is otherwise unanswerable from the UI.
+pub fn config_file_path() -> PathBuf {
+ config_path(&default_data_folder())
+}
+
+/// This server's OAuth state, without touching the network.
+pub fn auth_status(name: &str, config: &Value) -> oauth::AuthStatus {
+ oauth::status(&default_data_folder(), name, config)
+}
+
+/// Forget one server's stored tokens. `Ok(false)` when there were none.
+pub fn clear_auth(name: &str) -> Result<bool, String> {
+ oauth::clear(&default_data_folder(), name)
+}
+
+/// Start an interactive authorization for a configured http/sse server. The
+/// caller owns opening the browser and awaiting `PendingAuth::complete`.
+pub async fn begin_auth(name: &str) -> Result<oauth::PendingAuth, String> {
+ let entry =
+ get_server(name).ok_or_else(|| format!("server '{name}' not found in mcp_config.json"))?;
+ let url = entry
+ .config
+ .get("url")
+ .and_then(Value::as_str)
+ .filter(|u| !u.trim().is_empty())
+ .ok_or_else(|| {
+ format!("'{name}' is a stdio server - OAuth applies to http/sse servers only")
+ })?;
+ oauth::begin(name, url).await
+}
+
+/// Finish an authorization by persisting the tokens it produced.
+pub async fn finish_auth(pending: oauth::PendingAuth) -> Result<oauth::StoredCredentials, String> {
+ pending.complete(&default_data_folder()).await
+}
+
+/// Everything the `/mcp` detail screen shows about one server. Split from the
+/// tool list on purpose: all of this is local (config plus the cached
+/// `initialize` response), so the screen opens without a round trip and the
+/// tool list arrives separately.
+pub struct ServerDetail {
+ pub name: String,
+ pub active: bool,
+ pub connected: bool,
+ pub transport: String,
+ /// The url for http/sse, or `command args` for stdio.
+ pub endpoint: String,
+ pub config_path: PathBuf,
+ pub auth: oauth::AuthStatus,
+ /// Capability names the server advertised, in a stable display order.
+ pub capabilities: Vec<&'static str>,
+ /// `name version` from the server's `initialize` response, when connected.
+ pub implementation: Option<String>,
+}
+
+/// Snapshot one server for the detail screen. `None` when the name is no longer
+/// in the config (deleted from another surface while the picker was open).
+pub async fn describe(name: &str, servers: &SharedMcpServers) -> Option<ServerDetail> {
+ let entry = get_server(name)?;
+ let cfg = &entry.config;
+ let transport = cfg
+ .get("type")
+ .and_then(Value::as_str)
+ .unwrap_or("stdio")
+ .to_string();
+ let endpoint = if transport == "stdio" {
+ let command = cfg.get("command").and_then(Value::as_str).unwrap_or("");
+ let args: Vec<&str> = cfg
+ .get("args")
+ .and_then(Value::as_array)
+ .map(|a| a.iter().filter_map(Value::as_str).collect())
+ .unwrap_or_default();
+ if args.is_empty() {
+ command.to_string()
+ } else {
+ format!("{command} {}", args.join(" "))
+ }
+ } else {
+ cfg.get("url").and_then(Value::as_str).unwrap_or("").to_string()
+ };
+
+ // The lock is held only for the cached `initialize` response; nothing here
+ // goes to the network, so the render loop is never parked on a peer.
+ let peer = servers.lock().await.get(name).and_then(|s| s.peer_info());
+ let connected = peer.is_some();
+ let mut capabilities = Vec::new();
+ let mut implementation = None;
+ if let Some(peer) = peer {
+ let caps = &peer.capabilities;
+ for (present, label) in [
+ (caps.tools.is_some(), "tools"),
+ (caps.resources.is_some(), "resources"),
+ (caps.prompts.is_some(), "prompts"),
+ (caps.logging.is_some(), "logging"),
+ (caps.completions.is_some(), "completions"),
+ ] {
+ if present {
+ capabilities.push(label);
+ }
+ }
+ implementation = Some(format!(
+ "{} {}",
+ peer.server_info.name, peer.server_info.version
+ ));
+ }
+
+ Some(ServerDetail {
+ auth: auth_status(name, cfg),
+ name: entry.name,
+ active: entry.active,
+ connected,
+ transport,
+ endpoint,
+ config_path: config_file_path(),
+ capabilities,
+ implementation,
+ })
+}
+
+/// The tool names a connected server exposes, for the detail screen's `Tools:`
+/// line and its `View tools` action. `Err` when the server is not connected or
+/// the listing round trip fails.
+///
+/// This is the one part of the detail screen that talks to the peer, which is
+/// why it is a separate call: the caller runs it off the render loop.
+///
+/// The round trip is bounded by `tool_call_timeout_duration`, as every other
+/// `list_all_tools` call site is: the guard is the process-wide server map that
+/// each agent turn also locks, so a peer that accepts the request and never
+/// answers would otherwise stall turns and not just this screen.
+pub async fn list_tools(name: &str, servers: &SharedMcpServers) -> Result<Vec<String>, String> {
+ let timeout_duration = read_settings().tool_call_timeout_duration();
+ let guard = servers.lock().await;
+ let service = guard
+ .get(name)
+ .ok_or_else(|| format!("'{name}' is not connected"))?;
+ let mut names: Vec<String> = tokio::time::timeout(timeout_duration, service.list_all_tools())
+ .await
+ .map_err(|_| {
+ format!(
+ "listing tools for '{name}' timed out after {}s",
+ timeout_duration.as_secs()
+ )
+ })?
+ .map_err(|e| format!("could not list tools for '{name}': {e}"))?
+ .into_iter()
+ .map(|t| t.name.to_string())
+ .collect();
+ names.sort();
+ Ok(names)
+}
+
/// Number of servers marked `active` in `mcp_config.json`.
pub fn active_count() -> usize {
list_servers().iter().filter(|e| e.active).count()
@@ -484,6 +739,10 @@ pub struct ConnectOutcome {
pub connected: Vec<String>,
/// One `failed to connect to '<name>': <error>` per server that didn't.
pub failed: Vec<String>,
+ /// Servers that are up to the user to sign into, kept apart from `failed`
+ /// so the caller can point at `/mcp` instead of repeating a transport error
+ /// nobody can act on.
+ pub needs_auth: Vec<String>,
}
/// Connect every `active` server into the shared map, best-effort.
@@ -492,7 +751,8 @@ pub async fn connect_active(servers: &SharedMcpServers) -> ConnectOutcome {
for entry in list_servers().into_iter().filter(|e| e.active) {
match connect(&entry.name, &entry.config, servers).await {
Ok(()) => out.connected.push(entry.name),
- Err(e) => out.failed.push(e),
+ Err(ConnectError::NeedsAuth { server, .. }) => out.needs_auth.push(server),
+ Err(e) => out.failed.push(e.to_string()),
}
}
out
diff --git a/src-tauri/src/core/cli/mod.rs b/src-tauri/src/core/cli/mod.rs
index eb36e1fd8..9c61a8add 100644
--- a/src-tauri/src/core/cli/mod.rs
+++ b/src-tauri/src/core/cli/mod.rs
@@ -3,6 +3,7 @@
//! This module is only compiled when the `cli` feature is enabled.
pub mod brand;
+pub mod browser;
pub mod journal;
pub mod login;
pub mod mcp;
@@ -1115,6 +1116,14 @@ async fn run_agent_loop(
for failure in &outcome.failed {
log::warn!("MCP: {failure}");
}
+ // Signing in needs a browser and a keypress, neither of which
+ // exists here, so the fix is named rather than attempted.
+ if !outcome.needs_auth.is_empty() {
+ log::warn!(
+ "MCP: {} need authentication - run `jan` and use /mcp to sign in",
+ outcome.needs_auth.join(", ")
+ );
+ }
}
Err(e) => log::warn!("MCP connect task failed: {e}"),
}
diff --git a/src-tauri/src/core/cli/tokamak.rs b/src-tauri/src/core/cli/tokamak.rs
index 94a0862d8..58f7aef5a 100644
--- a/src-tauri/src/core/cli/tokamak.rs
+++ b/src-tauri/src/core/cli/tokamak.rs
@@ -176,49 +176,7 @@ pub(crate) fn parse_models(value: &serde_json::Value) -> Vec<String> {
/// unconditionally anyway, since a spawned launcher reports nothing about
/// whether a page actually appeared.
pub fn open_api_keys_page() -> Result<(), String> {
- open_url(API_KEYS_URL)
-}
-
-fn open_url(url: &str) -> Result<(), String> {
- if cfg!(test) {
- // A test run must never take over the developer's browser.
- return Err("browser launch is disabled under test".to_string());
- }
- launch(url)
-}
-
-fn launch(url: &str) -> Result<(), String> {
- #[cfg(target_os = "macos")]
- let (program, args): (&str, &[&str]) = ("open", &[]);
- #[cfg(target_os = "windows")]
- let (program, args): (&str, &[&str]) = ("cmd", &["/C", "start", ""]);
- #[cfg(all(unix, not(target_os = "macos")))]
- let (program, args): (&str, &[&str]) = ("xdg-open", &[]);
-
- #[cfg(all(unix, not(target_os = "macos")))]
- if !has_display() {
- return Err("no graphical session detected".to_string());
- }
-
- std::process::Command::new(program)
- .args(args)
- .arg(url)
- .stdin(std::process::Stdio::null())
- .stdout(std::process::Stdio::null())
- .stderr(std::process::Stdio::null())
- .spawn()
- .map(|_| ())
- .map_err(|e| format!("could not launch {program}: {e}"))
-}
-
-/// Whether a Linux/BSD session has a display server to open a browser on. Over
-/// SSH or in a container `xdg-open` would either fail noisily or block, so the
-/// caller falls back to printing the URL.
-#[cfg(all(unix, not(target_os = "macos")))]
-fn has_display() -> bool {
- ["WAYLAND_DISPLAY", "DISPLAY"]
- .iter()
- .any(|var| std::env::var_os(var).is_some_and(|v| !v.is_empty()))
+ super::browser::open(API_KEYS_URL)
}
#[cfg(test)]
diff --git a/src-tauri/src/core/cli/tui.rs b/src-tauri/src/core/cli/tui.rs
index bb83e2427..cd9b4fe63 100644
--- a/src-tauri/src/core/cli/tui.rs
+++ b/src-tauri/src/core/cli/tui.rs
@@ -404,6 +404,9 @@ enum PickerKind {
/// `/plugin install <collection>`: choose which plugins inside a collection
/// repo to install. Space toggles a row, Enter installs everything checked.
PluginSelect,
+ /// One MCP server's detail screen: the info block plus the actions that
+ /// apply to it (see `open_mcp_detail`). Reached with Enter from `ToggleMcp`.
+ McpServer,
}
/// Interactive list overlay (`/resume` threads, `/model` models, `/mcp`
@@ -431,6 +434,7 @@ impl Picker {
PickerKind::ProviderSettings => " providers ",
PickerKind::Todo => " todo ",
PickerKind::PluginSelect => " install plugins ",
+ PickerKind::McpServer => " mcp server ",
}
}
@@ -438,7 +442,9 @@ impl Picker {
match self.kind {
PickerKind::ResumeThread => " ↑/↓ select Enter resume Esc cancel",
PickerKind::SelectModel => " ↑/↓ select Enter choose Esc cancel",
- PickerKind::ToggleMcp => " ↑/↓ select Enter toggle a add e edit d delete Esc close",
+ PickerKind::ToggleMcp => {
+ " ↑/↓ select Enter open Space toggle a add e edit d delete Esc close"
+ }
PickerKind::RewindMessage => " ↑/↓ select Enter choose Esc cancel",
PickerKind::RewindScope => " ↑/↓ select Enter restore Esc cancel",
PickerKind::ViewConfig => " set via: jan config set --provider <id> ... Esc close",
@@ -448,6 +454,7 @@ impl Picker {
PickerKind::PluginSelect => {
" ↑/↓ select Space toggle Enter install Esc cancel"
}
+ PickerKind::McpServer => " ↑/↓ select Enter run Esc back",
}
}
}
@@ -463,6 +470,65 @@ struct PickerItem {
checkbox: Option<bool>,
}
+/// The `/mcp` detail screen's data: a local snapshot (config plus the cached
+/// `initialize` response) and the one field that needs a round trip.
+struct McpDetail {
+ server: super::mcp::ServerDetail,
+ tools: ToolsState,
+}
+
+/// Where the detail screen's tool list is. Split from `Option<Vec<_>>` so the
+/// screen can say *why* there is no list -- "not connected" and "the listing
+/// failed" are different problems.
+enum ToolsState {
+ /// Not connected, so there is nothing to ask for.
+ Unavailable,
+ Loading,
+ Ready(Vec<String>),
+ Failed(String),
+}
+
+/// Off-loop MCP work the detail screen hands to the loop. Everything here
+/// either talks to a peer or waits on a browser, so none of it may run inside
+/// `handle_key`.
+enum McpJob {
+ /// List a connected server's tools for the `Tools:` line.
+ Tools(String),
+ /// Discover the provider and mint a consent url. Deliberately separate from
+ /// `Authorize`: the url must reach the transcript *before* anything waits on
+ /// the redirect, or a user with no browser has nothing to act on.
+ BeginAuth(String),
+ /// Wait for the redirect and persist the tokens.
+ Authorize {
+ server: String,
+ pending: Box<crate::core::mcp::oauth::PendingAuth>,
+ },
+ /// Bring a server up. Run as a job rather than detached whenever the detail
+ /// screen is open, so the screen refreshes when the connect lands instead of
+ /// sitting on `not connected` until the user navigates away and back.
+ Connect(String),
+}
+
+/// What an `McpJob` came back with.
+enum McpJobDone {
+ Tools {
+ server: String,
+ result: Result<Vec<String>, String>,
+ },
+ AuthStarted {
+ server: String,
+ result: Result<Box<crate::core::mcp::oauth::PendingAuth>, String>,
+ },
+ Authorized {
+ server: String,
+ result: Result<(), String>,
+ },
+ Connected {
+ server: String,
+ result: Result<(), String>,
+ },
+}
+
/// `/login` key entry: a docked prompt that collects a Tokamak API key without
/// echoing it. Verification runs off the render loop (see `login_task` in
/// `chat_loop`), so `verifying` marks the window where the prompt is read-only.
@@ -1399,6 +1465,12 @@ struct App {
settings_prompt: Option<SettingsPrompt>,
/// Active MCP add/edit wizard (docked); owns the keyboard while open.
mcp_prompt: Option<McpPrompt>,
+ /// The `/mcp` detail screen's data, alongside the `McpServer` picker whose
+ /// rows are its actions. Held on `App` rather than in the picker so a job
+ /// landing later (a tool list, a finished sign-in) can update it in place.
+ mcp_detail: Option<McpDetail>,
+ /// MCP work handed to the loop to run off the render loop. Taken once.
+ mcp_job_request: Option<McpJob>,
/// Active OpenAI-compatible provider wizard (docked); owns the keyboard.
provider_prompt: Option<ProviderPrompt>,
/// Providers already probed for a missing model list this session
@@ -1779,6 +1851,8 @@ impl App {
login: None,
settings_prompt: None,
mcp_prompt: None,
+ mcp_detail: None,
+ mcp_job_request: None,
provider_prompt: None,
probed_models: std::collections::HashSet::new(),
login_submit: None,
@@ -5677,6 +5751,21 @@ async fn await_snapshot(
}
}
+/// Await an in-flight `/mcp` job, parking forever when none is running so this
+/// can sit in the loop's `select!` unconditionally.
+async fn await_mcp_job(
+ task: &mut Option<tokio::task::JoinHandle<McpJobDone>>,
+) -> Option<McpJobDone> {
+ let joined = match task.as_mut() {
+ Some(h) => h.await,
+ None => return pending().await,
+ };
+ *task = None;
+ // A cancelled or panicked job is dropped rather than reported: the only
+ // paths that abort it have already told the user why.
+ joined.ok()
+}
+
/// Await an in-flight `/login` verification, parking forever when none is
/// running so this can sit in the loop's `select!` unconditionally.
async fn await_login(
@@ -6139,6 +6228,11 @@ async fn chat_loop<B: Backend>(
tokio::task::JoinHandle<Result<super::tokamak::Login, String>>,
> = None;
+ // `/mcp` work that must not run on the render loop: a tool listing is a
+ // round trip to the peer, and an authorization waits on a browser for up to
+ // five minutes. One at a time -- the detail screen only ever asks for one.
+ let mut mcp_job: Option<tokio::task::JoinHandle<McpJobDone>> = None;
+
// The update check is a network round trip, so it runs off the render loop
// and notes itself whenever it lands rather than delaying the first frame.
let mut update_task = Some(tokio::spawn(super::updater::available_update()));
@@ -6203,6 +6297,21 @@ async fn chat_loop<B: Backend>(
}
}
+ // The detail screen asked for something off-loop. One job at a time, and
+ // a request arriving while one is in flight *waits* rather than being
+ // dropped: an authorization owns the slot for up to `CALLBACK_TIMEOUT`
+ // while the browser is out, and a tool listing dropped in that window
+ // would leave the screen on `listing...` with nothing to retrigger it.
+ // The slot holds the latest request only -- a newer one replaces it, and
+ // a request whose server the screen has since left is discarded on
+ // arrival by `finish_mcp_job`.
+ if mcp_job.is_none() {
+ if let Some(job) = app.mcp_job_request.take() {
+ let servers = mcp_servers.clone();
+ mcp_job = Some(tokio::spawn(run_mcp_job(job, servers)));
+ }
+ }
+
// A key was submitted at the `/login` prompt: verify it off-loop. One at
// a time -- the prompt is read-only while `verifying`.
if login_task.is_none() {
@@ -6365,6 +6474,17 @@ async fn chat_loop<B: Backend>(
for failure in &outcome.failed {
app.note(&format!("MCP: {failure}"));
}
+ // A server that only needs signing in is separated from a
+ // broken one: the fix is a keypress away, so name it.
+ if !outcome.needs_auth.is_empty() {
+ app.note(&format!(
+ "MCP: {} need authentication - open /mcp to sign in",
+ outcome.needs_auth.join(", ")
+ ));
+ }
+ }
+ Some(done) = await_mcp_job(&mut mcp_job) => {
+ finish_mcp_job(app, done, mcp_servers, &mut mcp_job).await;
}
login_res = await_login(&mut login_task) => {
let login_ok = login_res.is_ok();
@@ -6926,12 +7046,36 @@ async fn handle_key(
picker.armed_delete = None;
picker.selected = (picker.selected + 1).min(picker.items.len() - 1);
}
- KeyCode::Enter if picker.kind == PickerKind::ToggleMcp => {
+ // Space toggles the row in place; Enter opens its detail screen.
+ // Enter used to be the toggle, but with a detail screen to reach it
+ // is the row's primary action, and Space is already the toggle in
+ // the one other checkbox picker (`PluginSelect`).
+ KeyCode::Char(' ') if picker.kind == PickerKind::ToggleMcp => {
let item = &mut picker.items[picker.selected];
+ if item.value.is_empty() {
+ return;
+ }
let name = item.value.clone();
let enable = !item.checkbox.unwrap_or(false);
item.checkbox = Some(enable);
- toggle_mcp_server(app, mcp_servers, name, enable);
+ if set_mcp_active(app, mcp_servers, &name, enable).await {
+ // Nothing on this screen is waiting on the answer, so it is
+ // detached rather than taking the single job slot.
+ reconnect_mcp_server(mcp_servers, name);
+ }
+ }
+ KeyCode::Enter if picker.kind == PickerKind::ToggleMcp => {
+ let name = picker.items[picker.selected].value.clone();
+ // The watermark row of an empty config: nothing to open.
+ if name.is_empty() {
+ return;
+ }
+ open_mcp_detail(app, &name, mcp_servers).await;
+ }
+ // The detail screen's rows are actions on one server.
+ KeyCode::Enter if picker.kind == PickerKind::McpServer => {
+ let action = picker.items[picker.selected].value.clone();
+ run_mcp_action(app, &action, mcp_servers).await;
}
// `/mcp` picker: `a` opens the add wizard, `e` opens the edit
// wizard prefilled from the selected row, `d` removes the selected
@@ -6954,23 +7098,18 @@ async fn handle_key(
}
KeyCode::Char('e') if picker.kind == PickerKind::ToggleMcp => {
let name = picker.items[picker.selected].value.clone();
- let entry = super::mcp::get_server(&name);
- if let Some(entry) = entry {
- app.picker = None;
- app.mcp_prompt = Some(McpPrompt::from_entry(&entry));
- } else {
- app.note(&format!("server '{name}' no longer exists"));
+ if name.is_empty() {
+ return;
}
+ edit_mcp_server(app, &name);
}
KeyCode::Char('d') if picker.kind == PickerKind::ToggleMcp => {
let name = picker.items[picker.selected].value.clone();
- app.picker = None;
- if let Err(e) = super::mcp::remove_server(&name) {
- app.note(&format!("failed to remove '{name}': {e}"));
- } else {
- super::mcp::disconnect(&name, mcp_servers).await;
- app.note(&format!("removed MCP server '{name}'"));
+ if name.is_empty() {
+ return;
}
+ app.picker = None;
+ remove_mcp_server(app, &name, mcp_servers).await;
}
// `/settings > providers` picker: `a` opens the add wizard, `d`
// deletes the selected provider only after a confirmation `d` on
@@ -7138,15 +7277,27 @@ async fn handle_key(
PickerKind::Todo => {}
// PluginSelect Enter is handled by the guarded arm above.
PickerKind::PluginSelect => {}
+ // McpServer Enter is handled by the guarded arm above.
+ PickerKind::McpServer => {}
}
}
+ // Esc on the detail screen steps back to the server list rather
+ // than closing outright: the detail is one level *inside* `/mcp`,
+ // and dropping the user to the prompt loses the place they were at.
+ KeyCode::Esc | KeyCode::Char('q')
+ if !ctrl && picker.kind == PickerKind::McpServer =>
+ {
+ open_mcp_picker(app, mcp_servers).await;
+ }
KeyCode::Esc | KeyCode::Char('q') if !ctrl => {
app.plugin_collection_url = None;
app.picker = None;
+ app.mcp_detail = None;
}
_ if ctrl_c => {
app.plugin_collection_url = None;
app.picker = None;
+ app.mcp_detail = None;
}
_ => {}
}
@@ -7301,7 +7452,7 @@ async fn handle_key(
if !text.is_empty() {
app.record_submitted(&text);
if let Some(cmd) = text.strip_prefix('/') {
- run_command(app, cmd).await;
+ run_command(app, cmd, mcp_servers).await;
} else {
app.submit_user(text);
}
@@ -7814,7 +7965,11 @@ fn parse_command(line: &str) -> (&str, &str) {
}
/// Execute a `/command` typed into the input box. Runs only while idle.
-async fn run_command(app: &mut App, line: &str) {
+async fn run_command(
+ app: &mut App,
+ line: &str,
+ mcp_servers: &crate::core::state::SharedMcpServers,
+) {
let (name, arg) = parse_command(line);
match name {
"" | "help" | "?" => {
@@ -7881,7 +8036,7 @@ async fn run_command(app: &mut App, line: &str) {
app.set_model(arg.to_string());
}
}
- "mcp" => open_mcp_picker(app),
+ "mcp" => open_mcp_picker(app, mcp_servers).await,
"plugin" => plugin_command(app, arg).await,
"login" => open_login_prompt(app),
"update" => update_command(app),
@@ -8375,11 +8530,16 @@ impl McpPrompt {
super::mcp::parse_pairs(self.headers.trim(), "header")?,
self.active,
)?;
+ // Read the *previous* active flag before the write. `upsert_server` has
+ // already replaced the entry by the time it lands on disk, so reading it
+ // afterwards reports the new value and a server being disabled from this
+ // form was left connected.
+ let was_active = self
+ .editing
+ .as_deref()
+ .is_some_and(|n| super::mcp::get_server(n).is_some_and(|e| e.active));
super::mcp::upsert_server(self.name.trim(), &config)?;
let name = self.name.trim().to_string();
- let was_active = self.editing.as_deref().is_some_and(|n| {
- super::mcp::get_server(n).is_some_and(|e| e.active)
- });
// Disconnect the old live service on rename/edit, then reconnect if active.
if let Some(old) = self.editing.take() {
if old != name {
@@ -8387,15 +8547,9 @@ impl McpPrompt {
}
}
if self.active {
- let cfg = super::mcp::list_servers()
- .into_iter()
- .find(|s| s.name == name)
- .map(|s| s.config);
- if let Some(cfg) = cfg {
- if let Err(e) = super::mcp::connect(&name, &cfg, mcp_servers).await {
- log::warn!("MCP: {e}");
- }
- }
+ // Off the render loop: a cold stdio spawn or an http handshake here
+ // would freeze the frame the form was submitted on.
+ reconnect_mcp_server(mcp_servers, name);
} else if was_active {
super::mcp::disconnect(&name, mcp_servers).await;
}
@@ -9617,23 +9771,65 @@ async fn open_model_picker(app: &mut App) {
});
}
-/// Open the `/mcp` picker listing configured MCP servers with their enabled
-/// state. Enter toggles a row in place (see `toggle_mcp_server`); `a` adds, `e`
-/// edits, and `d` removes (see the picker key handler).
-fn open_mcp_picker(app: &mut App) {
+/// Action ids for the `McpServer` detail screen. String values rather than an
+/// enum because `PickerItem::value` is the picker's one payload; keeping them
+/// as constants is what stops the key handler and the row builder from drifting.
+const MCP_ACTION_TOOLS: &str = "tools";
+const MCP_ACTION_AUTH: &str = "auth";
+const MCP_ACTION_CLEAR_AUTH: &str = "clear-auth";
+const MCP_ACTION_RECONNECT: &str = "reconnect";
+const MCP_ACTION_TOGGLE: &str = "toggle";
+const MCP_ACTION_EDIT: &str = "edit";
+const MCP_ACTION_REMOVE: &str = "remove";
+
+/// Open the `/mcp` screen: one row per configured server, with its live state.
+///
+/// An empty config opens the screen anyway, on a watermark row (the same shape
+/// `open_provider_settings` uses). Returning a note instead left a fresh install
+/// with no way *in* to the thing `/mcp` manages -- `a` to add is only reachable
+/// once the picker exists, so the one state that most needs the add wizard was
+/// the one state that could not reach it.
+async fn open_mcp_picker(app: &mut App, mcp_servers: &crate::core::state::SharedMcpServers) {
let servers = super::mcp::list_servers();
- if servers.is_empty() {
- return app.note("no MCP servers configured (press a to add one, or use `jan cli mcp add ...`)");
- }
- let items = servers
- .into_iter()
- .map(|s| PickerItem {
- label: s.name.clone(),
- value: s.name,
+ let items: Vec<PickerItem> = if servers.is_empty() {
+ vec![PickerItem {
+ label: "no MCP servers configured - press a to add one".to_string(),
+ value: String::new(),
hint: None,
- checkbox: Some(s.active),
- })
- .collect();
+ checkbox: None,
+ }]
+ } else {
+ // One lock for the whole list: `describe` per row would take and drop it
+ // N times, and nothing here goes to the network.
+ let connected: std::collections::HashSet<String> =
+ mcp_servers.lock().await.keys().cloned().collect();
+ servers
+ .into_iter()
+ .map(|s| {
+ let state = if !s.active {
+ "disabled".to_string()
+ } else if connected.contains(&s.name) {
+ "connected".to_string()
+ } else {
+ match super::mcp::auth_status(&s.name, &s.config) {
+ crate::core::mcp::oauth::AuthStatus::Unauthenticated
+ | crate::core::mcp::oauth::AuthStatus::Expired { .. }
+ | crate::core::mcp::oauth::AuthStatus::StaleResource => {
+ "needs auth".to_string()
+ }
+ _ => "not connected".to_string(),
+ }
+ };
+ PickerItem {
+ label: format!("{} {state}", s.name),
+ value: s.name,
+ hint: None,
+ checkbox: Some(s.active),
+ }
+ })
+ .collect()
+ };
+ app.mcp_detail = None;
app.picker = Some(Picker {
kind: PickerKind::ToggleMcp,
items,
@@ -9642,6 +9838,261 @@ fn open_mcp_picker(app: &mut App) {
});
}
+/// Open the detail screen for one server: the info block plus the actions that
+/// apply to it. Everything shown is local, so this opens in one frame; the tool
+/// list is requested as a job and fills in when it lands.
+async fn open_mcp_detail(
+ app: &mut App,
+ name: &str,
+ mcp_servers: &crate::core::state::SharedMcpServers,
+) {
+ let Some(server) = super::mcp::describe(name, mcp_servers).await else {
+ app.mcp_detail = None;
+ return app.note(&format!("server '{name}' no longer exists"));
+ };
+ let tools = if server.connected {
+ app.mcp_job_request = Some(McpJob::Tools(name.to_string()));
+ ToolsState::Loading
+ } else {
+ ToolsState::Unavailable
+ };
+ app.picker = Some(Picker {
+ kind: PickerKind::McpServer,
+ items: mcp_action_items(&server),
+ selected: 0,
+ armed_delete: None,
+ });
+ app.mcp_detail = Some(McpDetail { server, tools });
+}
+
+/// The actions offered for one server, filtered to what its state can actually
+/// do: a stdio server has nothing to authenticate, and a disconnected one has no
+/// tools to list.
+fn mcp_action_items(server: &super::mcp::ServerDetail) -> Vec<PickerItem> {
+ use crate::core::mcp::oauth::AuthStatus;
+ let mut actions: Vec<(&str, String)> = Vec::new();
+ if server.connected {
+ actions.push((MCP_ACTION_TOOLS, "View tools".to_string()));
+ }
+ match server.auth {
+ // A pipe has nothing to authorize, and a hand-written header is the
+ // user's own credential -- offering to overwrite it with OAuth would be
+ // offering to break it.
+ AuthStatus::NotApplicable | AuthStatus::StaticHeader => {}
+ // Anything with tokens on disk can be renewed *and* forgotten, whether
+ // they still work or not.
+ AuthStatus::Authenticated { .. }
+ | AuthStatus::Expired { .. }
+ | AuthStatus::StaleResource => {
+ actions.push((MCP_ACTION_AUTH, "Re-authenticate".to_string()));
+ actions.push((MCP_ACTION_CLEAR_AUTH, "Clear authentication".to_string()));
+ }
+ AuthStatus::Unauthenticated => {
+ actions.push((MCP_ACTION_AUTH, "Authenticate".to_string()));
+ }
+ }
+ if server.active {
+ actions.push((MCP_ACTION_RECONNECT, "Reconnect".to_string()));
+ actions.push((MCP_ACTION_TOGGLE, "Disable".to_string()));
+ } else {
+ actions.push((MCP_ACTION_TOGGLE, "Enable".to_string()));
+ }
+ actions.push((MCP_ACTION_EDIT, "Edit configuration".to_string()));
+ actions.push((MCP_ACTION_REMOVE, "Remove server".to_string()));
+
+ actions
+ .into_iter()
+ .enumerate()
+ .map(|(i, (value, label))| PickerItem {
+ // Numbered like the rest of the screen reads: the hint column is
+ // already the dim prefix slot, so this costs no extra layout.
+ hint: Some(format!("{}.", i + 1)),
+ label,
+ value: value.to_string(),
+ checkbox: None,
+ })
+ .collect()
+}
+
+/// The info block above the detail screen's actions: aligned labels, the state
+/// in colour, and the config path so "where do I edit this" is answerable
+/// without leaving the screen.
+fn mcp_detail_lines(detail: &McpDetail, width: u16) -> Vec<Line<'static>> {
+ use crate::core::mcp::oauth::AuthStatus;
+ let server = &detail.server;
+ let dim = Style::new().dark_gray();
+ let good = Style::new().green();
+ let bad = Style::new().red();
+ let warn = Style::new().yellow();
+
+ let mut rows: Vec<(&str, Vec<Span<'static>>)> = Vec::new();
+
+ let status = if !server.active {
+ vec![Span::styled("- disabled", dim)]
+ } else if server.connected {
+ vec![Span::styled("✓ connected", good)]
+ } else {
+ vec![Span::styled("✗ not connected", bad)]
+ };
+ rows.push(("Status", status));
+
+ let auth = match &server.auth {
+ AuthStatus::NotApplicable => vec![Span::styled("- not required (stdio)", dim)],
+ AuthStatus::StaticHeader => {
+ vec![Span::styled("✓ Authorization header (configured)", good)]
+ }
+ AuthStatus::Authenticated { expires_at } => {
+ let mut spans = vec![Span::styled("✓ authenticated", good)];
+ if let Some(at) = expires_at {
+ spans.push(Span::styled(
+ format!(" (expires in {})", until_label(*at)),
+ dim,
+ ));
+ }
+ spans
+ }
+ AuthStatus::Expired { renewable, .. } => vec![Span::styled(
+ if *renewable {
+ "! expired (renewable)"
+ } else {
+ "! expired - re-authenticate"
+ },
+ warn,
+ )],
+ AuthStatus::StaleResource => vec![Span::styled(
+ "! tokens were issued for a different url",
+ warn,
+ )],
+ AuthStatus::Unauthenticated => vec![Span::styled("✗ not authenticated", bad)],
+ };
+ rows.push(("Auth", auth));
+
+ let endpoint_label = if server.transport == "stdio" {
+ "Command"
+ } else {
+ "URL"
+ };
+ rows.push((
+ endpoint_label,
+ vec![Span::styled(server.endpoint.clone(), dim)],
+ ));
+ rows.push((
+ "Config location",
+ vec![Span::styled(
+ tilde_path(&server.config_path),
+ dim,
+ )],
+ ));
+ if let Some(implementation) = &server.implementation {
+ rows.push(("Server", vec![Span::styled(implementation.clone(), dim)]));
+ }
+ if !server.capabilities.is_empty() {
+ rows.push((
+ "Capabilities",
+ vec![Span::styled(server.capabilities.join(" · "), dim)],
+ ));
+ }
+ rows.push(("Tools", vec![tools_span(&detail.tools)]));
+
+ // One label column for every row, so the values line up the way the screen
+ // is meant to read.
+ let pad = rows.iter().map(|(k, _)| k.len()).max().unwrap_or(0) + 2;
+ let mut out = vec![
+ Line::from(Span::styled(
+ server.name.clone(),
+ Style::new().cyan().bold(),
+ )),
+ Line::raw(""),
+ ];
+ for (key, value) in rows {
+ let mut spans = vec![Span::styled(
+ format!("{key}:{}", " ".repeat(pad - key.len())),
+ Style::new().bold(),
+ )];
+ spans.extend(value);
+ out.push(clamp_line(Line::from(spans), width));
+ }
+ out.push(Line::raw(""));
+ out
+}
+
+fn tools_span(tools: &ToolsState) -> Span<'static> {
+ let dim = Style::new().dark_gray();
+ match tools {
+ ToolsState::Unavailable => Span::styled("- connect to list", dim),
+ ToolsState::Loading => Span::styled("listing...", dim),
+ ToolsState::Ready(names) if names.is_empty() => {
+ Span::styled("none exposed", dim)
+ }
+ ToolsState::Ready(names) => Span::styled(format!("{} tools", names.len()), dim),
+ ToolsState::Failed(e) => Span::styled(e.clone(), Style::new().red()),
+ }
+}
+
+/// A coarse "in 42m" / "in 3h" for a unix-second deadline. Coarse on purpose:
+/// the exact second a token dies is never what the reader wants to know.
+fn until_label(expires_at: u64) -> String {
+ let now = std::time::SystemTime::now()
+ .duration_since(std::time::UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0);
+ match expires_at.saturating_sub(now) {
+ s if s < 60 => format!("{s}s"),
+ s if s < 3600 => format!("{}m", s / 60),
+ s if s < 86400 => format!("{}h", s / 3600),
+ s => format!("{}d", s / 86400),
+ }
+}
+
+/// Truncate a composed line to `width`, so a long url or path cannot push the
+/// panel's border off the frame. Spans are kept whole where they fit and the
+/// overflowing one is cut with an ellipsis.
+///
+/// Two cells short of `width` on purpose: callers pass the *inner* width of a
+/// bordered panel, and a line that exactly fills it wraps into a second row,
+/// which pushes the action list down by one for as long as the value is long.
+///
+/// Measured in display cells, not chars: a CJK server name or an emoji in a tool
+/// name is two cells wide, so a char count would let it overrun the border.
+fn clamp_line(line: Line<'static>, width: u16) -> Line<'static> {
+ use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
+
+ let max = width.saturating_sub(2) as usize;
+ if max == 0 {
+ return Line::raw("");
+ }
+ let total: usize = line.spans.iter().map(|s| s.content.width()).sum();
+ if total <= max {
+ return line;
+ }
+ let mut used = 0usize;
+ let mut spans: Vec<Span<'static>> = Vec::new();
+ for span in line.spans {
+ let len = span.content.width();
+ if used + len <= max.saturating_sub(1) {
+ used += len;
+ spans.push(span);
+ continue;
+ }
+ // The ellipsis takes the last cell; a wide glyph that would straddle the
+ // boundary is dropped rather than half-drawn.
+ let room = max.saturating_sub(used + 1);
+ let mut cut = String::new();
+ let mut cut_width = 0usize;
+ for c in span.content.chars() {
+ let w = c.width().unwrap_or(0);
+ if cut_width + w > room {
+ break;
+ }
+ cut_width += w;
+ cut.push(c);
+ }
+ spans.push(Span::styled(format!("{cut}…"), span.style));
+ break;
+ }
+ Line::from(spans)
+}
+
/// Open the `/login` prompt: send the user to Tokamak's API-keys page and wait
/// for the key they paste back. The URL is always written to the transcript, not
/// just handed to the browser, so a headless or remote session can still be
@@ -9805,41 +10256,267 @@ fn open_config_screen(app: &mut App) {
});
}
-/// Persist a server's enabled flag and connect/disconnect it in the background
-/// (off the render loop, so a cold stdio spawn never freezes the UI). Later
-/// turns read the shared map fresh, so tools appear/vanish once the task lands.
-fn toggle_mcp_server(
+/// Run one `McpJob`. Off the render loop: every arm either talks to a peer or
+/// waits on the user's browser.
+async fn run_mcp_job(job: McpJob, servers: crate::core::state::SharedMcpServers) -> McpJobDone {
+ match job {
+ McpJob::Tools(server) => {
+ let result = super::mcp::list_tools(&server, &servers).await;
+ McpJobDone::Tools { server, result }
+ }
+ McpJob::BeginAuth(server) => {
+ let result = super::mcp::begin_auth(&server).await.map(Box::new);
+ McpJobDone::AuthStarted { server, result }
+ }
+ McpJob::Authorize { server, pending } => {
+ let result = super::mcp::finish_auth(*pending).await.map(|_| ());
+ McpJobDone::Authorized { server, result }
+ }
+ McpJob::Connect(server) => {
+ let result = connect_mcp_server(&server, &servers).await;
+ McpJobDone::Connected { server, result }
+ }
+ }
+}
+
+/// Fold a finished job back into the screen. `job` is passed in so the
+/// two-phase authorization can chain its second half without going back through
+/// `mcp_job_request` -- the loop owns the slot, and round-tripping a `PendingAuth`
+/// through `App` would park a bound listener in UI state.
+async fn finish_mcp_job(
app: &mut App,
+ done: McpJobDone,
mcp_servers: &crate::core::state::SharedMcpServers,
- name: String,
- enable: bool,
+ job: &mut Option<tokio::task::JoinHandle<McpJobDone>>,
) {
- if let Err(e) = super::mcp::set_active(&name, enable) {
- app.note(&format!("failed to update mcp_config.json: {e}"));
+ match done {
+ McpJobDone::Tools { server, result } => {
+ // Only apply it if the screen is still showing that server: the user
+ // may have navigated on while the listing was in flight.
+ let Some(detail) = app.mcp_detail.as_mut() else {
+ return;
+ };
+ if detail.server.name != server {
+ return;
+ }
+ detail.tools = match result {
+ Ok(names) => ToolsState::Ready(names),
+ Err(e) => ToolsState::Failed(e),
+ };
+ }
+ McpJobDone::AuthStarted { server, result } => match result {
+ Ok(pending) => {
+ // The url reaches the transcript before anything waits on the
+ // redirect, so a headless or remote session can finish by hand.
+ app.note(&format!("sign in to authorize '{server}':"));
+ app.system_detail(vec![Span::styled(
+ pending.authorization_url.clone(),
+ Style::new().cyan(),
+ )]);
+ match super::browser::open(&pending.authorization_url) {
+ Ok(()) => app.system_detail_text("opening that page in your browser"),
+ Err(e) => {
+ app.system_detail_text(&format!("open that URL yourself ({e})"))
+ }
+ }
+ let servers = mcp_servers.clone();
+ *job = Some(tokio::spawn(run_mcp_job(
+ McpJob::Authorize { server, pending },
+ servers,
+ )));
+ }
+ Err(e) => app.note(&format!("could not start sign-in for '{server}': {e}")),
+ },
+ McpJobDone::Authorized { server, result } => match result {
+ Ok(()) => {
+ app.note(&format!("authorized '{server}' - reconnecting..."));
+ // The live connection (if any) predates the token, so it is
+ // replaced rather than left unauthorized.
+ super::mcp::disconnect(&server, mcp_servers).await;
+ let servers = mcp_servers.clone();
+ *job = Some(tokio::spawn(run_mcp_job(McpJob::Connect(server), servers)));
+ }
+ Err(e) => app.note(&format!("sign-in for '{server}' failed: {e}")),
+ },
+ McpJobDone::Connected { server, result } => {
+ match result {
+ Ok(()) => app.note(&format!("'{server}' connected")),
+ Err(e) => app.note(&format!("MCP: {e}")),
+ }
+ if app.mcp_detail.as_ref().is_some_and(|d| d.server.name == server) {
+ open_mcp_detail(app, &server, mcp_servers).await;
+ }
+ }
+ }
+}
+
+/// Open the add/edit wizard prefilled from a configured server.
+fn edit_mcp_server(app: &mut App, name: &str) {
+ match super::mcp::get_server(name) {
+ Some(entry) => {
+ app.picker = None;
+ app.mcp_detail = None;
+ app.mcp_prompt = Some(McpPrompt::from_entry(&entry));
+ }
+ None => app.note(&format!("server '{name}' no longer exists")),
+ }
+}
+
+/// Drop a server from the config and disconnect it. Its OAuth tokens go too:
+/// leaving them behind would silently re-authorize a later server that happened
+/// to reuse the name.
+async fn remove_mcp_server(
+ app: &mut App,
+ name: &str,
+ mcp_servers: &crate::core::state::SharedMcpServers,
+) {
+ if let Err(e) = super::mcp::remove_server(name) {
+ return app.note(&format!("failed to remove '{name}': {e}"));
+ }
+ super::mcp::disconnect(name, mcp_servers).await;
+ let _ = super::mcp::clear_auth(name);
+ app.mcp_detail = None;
+ app.note(&format!("removed MCP server '{name}'"));
+}
+
+/// Run one detail-screen action. Anything that talks to a peer or waits on a
+/// browser leaves as an `McpJob` instead of running here -- `handle_key` is on
+/// the render loop.
+async fn run_mcp_action(
+ app: &mut App,
+ action: &str,
+ mcp_servers: &crate::core::state::SharedMcpServers,
+) {
+ let Some(detail) = app.mcp_detail.as_ref() else {
+ return;
+ };
+ let name = detail.server.name.clone();
+ match action {
+ MCP_ACTION_TOOLS => show_mcp_tools(app),
+ MCP_ACTION_AUTH => {
+ app.note(&format!("starting sign-in for '{name}'..."));
+ app.mcp_job_request = Some(McpJob::BeginAuth(name));
+ }
+ MCP_ACTION_CLEAR_AUTH => {
+ match super::mcp::clear_auth(&name) {
+ Ok(true) => app.note(&format!("cleared stored credentials for '{name}'")),
+ Ok(false) => app.note(&format!("'{name}' had no stored credentials")),
+ Err(e) => app.note(&format!("could not clear credentials for '{name}': {e}")),
+ }
+ // The connection still holds the old bearer token, so it is dropped
+ // too: leaving it up would report "authenticated" work against
+ // credentials the user just asked to forget.
+ super::mcp::disconnect(&name, mcp_servers).await;
+ open_mcp_detail(app, &name, mcp_servers).await;
+ }
+ MCP_ACTION_RECONNECT => {
+ super::mcp::disconnect(&name, mcp_servers).await;
+ app.note(&format!("reconnecting '{name}'..."));
+ open_mcp_detail(app, &name, mcp_servers).await;
+ // Set after `open_mcp_detail`, which requests the tool list and
+ // would otherwise overwrite this.
+ app.mcp_job_request = Some(McpJob::Connect(name));
+ }
+ MCP_ACTION_TOGGLE => {
+ let enable = !detail.server.active;
+ let connect = set_mcp_active(app, mcp_servers, &name, enable).await;
+ open_mcp_detail(app, &name, mcp_servers).await;
+ if connect {
+ // After `open_mcp_detail`, which requests the tool list and
+ // would otherwise overwrite this.
+ app.mcp_job_request = Some(McpJob::Connect(name));
+ }
+ }
+ MCP_ACTION_EDIT => edit_mcp_server(app, &name),
+ MCP_ACTION_REMOVE => {
+ app.picker = None;
+ remove_mcp_server(app, &name, mcp_servers).await;
+ }
+ _ => {}
+ }
+}
+
+/// Write the fetched tool list into the transcript. The detail screen shows a
+/// count; the names belong in the conversation, where they scroll and persist.
+fn show_mcp_tools(app: &mut App) {
+ let Some(detail) = app.mcp_detail.as_ref() else {
return;
+ };
+ let name = detail.server.name.clone();
+ match &detail.tools {
+ ToolsState::Ready(names) if names.is_empty() => {
+ app.note(&format!("'{name}' exposes no tools"))
+ }
+ ToolsState::Ready(names) => {
+ let names = names.clone();
+ app.note(&format!("{} tool(s) on '{name}':", names.len()));
+ for tool in names {
+ app.system_detail_text(&tool);
+ }
+ }
+ ToolsState::Loading => app.note("still listing tools..."),
+ ToolsState::Unavailable => app.note(&format!("'{name}' is not connected")),
+ ToolsState::Failed(e) => {
+ let e = e.clone();
+ app.note(&e)
+ }
}
+}
+
+/// Bring one server up, reading its config fresh from disk. The single
+/// connect implementation behind every surface: the detail screen's `Reconnect`
+/// runs it as a job (so the screen refreshes), while the list's toggle and the
+/// edit wizard detach it (nothing there is waiting on the answer).
+async fn connect_mcp_server(
+ name: &str,
+ servers: &crate::core::state::SharedMcpServers,
+) -> Result<(), String> {
+ let cfg = super::mcp::list_servers()
+ .into_iter()
+ .find(|s| s.name == name)
+ .map(|s| s.config)
+ .ok_or_else(|| format!("'{name}' is no longer in mcp_config.json"))?;
+ super::mcp::connect(name, &cfg, servers)
+ .await
+ .map_err(|e| e.to_string())
+}
+
+/// `connect_mcp_server`, detached: for the paths with no screen waiting on the
+/// result. Off the render loop, so a cold stdio spawn never freezes a frame.
+fn reconnect_mcp_server(mcp_servers: &crate::core::state::SharedMcpServers, name: String) {
let servers = mcp_servers.clone();
- let task_name = name.clone();
tokio::spawn(async move {
- if enable {
- let cfg = super::mcp::list_servers()
- .into_iter()
- .find(|s| s.name == task_name)
- .map(|s| s.config);
- if let Some(cfg) = cfg {
- if let Err(e) = super::mcp::connect(&task_name, &cfg, &servers).await {
- log::warn!("MCP: {e}");
- }
- }
- } else {
- super::mcp::disconnect(&task_name, &servers).await;
+ if let Err(e) = connect_mcp_server(&name, &servers).await {
+ log::warn!("MCP: {e}");
}
});
- app.note(&if enable {
- format!("enabling MCP server '{name}'...")
+}
+
+/// Persist a server's enabled flag, tear down its connection when disabling,
+/// and say so. Returns whether the caller now owes a *connect* -- which it
+/// does, rather than connecting here, because the two callers want it delivered
+/// differently: the list detaches it, the detail screen runs it as a job so the
+/// screen can refresh when it lands.
+///
+/// Later turns read the shared map fresh, so tools appear/vanish once that
+/// connect completes.
+async fn set_mcp_active(
+ app: &mut App,
+ mcp_servers: &crate::core::state::SharedMcpServers,
+ name: &str,
+ enable: bool,
+) -> bool {
+ if let Err(e) = super::mcp::set_active(name, enable) {
+ app.note(&format!("failed to update mcp_config.json: {e}"));
+ return false;
+ }
+ if enable {
+ app.note(&format!("enabling MCP server '{name}'..."));
} else {
- format!("disabled MCP server '{name}'")
- });
+ super::mcp::disconnect(name, mcp_servers).await;
+ app.note(&format!("disabled MCP server '{name}'"));
+ }
+ enable
}
/// Resolve a thread by id (exact or unique prefix), load its messages into the
@@ -10590,7 +11267,7 @@ fn draw(f: &mut Frame, app: &mut App) {
if let Some(picker) = &app.picker {
app.row_index.clear();
let toml_path = app.agent_dir.join("agent.toml");
- draw_picker(f, chunks[1], picker, &toml_path);
+ draw_picker(f, chunks[1], picker, &toml_path, app.mcp_detail.as_ref());
f.render_widget(input_box(app), chunks[2]);
f.render_widget(dock_line(app, chunks[3].width), chunks[3]);
return;
@@ -11522,6 +12199,7 @@ fn draw_picker(
area: ratatui::layout::Rect,
picker: &Picker,
toml_path: &std::path::Path,
+ mcp_detail: Option<&McpDetail>,
) {
use ratatui::widgets::{List, ListItem, ListState};
@@ -11602,6 +12280,34 @@ fn draw_picker(
},
);
}
+ } else if let (PickerKind::McpServer, Some(detail)) = (picker.kind, mcp_detail) {
+ // The info block and the actions share one border: they are one screen,
+ // and two stacked frames would read as two unrelated panels.
+ let block = Block::default()
+ .borders(Borders::ALL)
+ .title(picker.title());
+ let inner = block.inner(area);
+ f.render_widget(block, area);
+
+ let info = mcp_detail_lines(detail, inner.width);
+ // A frame too short for the whole block gives its rows to the actions:
+ // an info line the user cannot act on is worth less than the action row
+ // it would displace.
+ let info_h = (info.len() as u16).min(inner.height.saturating_sub(1));
+ let (info_area, list_area) = (
+ Rect { height: info_h, ..inner },
+ Rect {
+ y: inner.y + info_h,
+ height: inner.height - info_h,
+ ..inner
+ },
+ );
+ f.render_widget(Paragraph::new(info), info_area);
+ f.render_stateful_widget(
+ list.block(Block::default()),
+ list_area,
+ &mut state,
+ );
} else {
f.render_stateful_widget(list, area, &mut state);
}
@@ -12471,6 +13177,12 @@ fn footer_spans(app: &App) -> Vec<Span<'static>> {
#[cfg(test)]
mod tests {
+
+ /// An empty MCP map, for the `run_command`/`handle_key` paths that take one
+ /// but whose behaviour under test has nothing to do with MCP.
+ fn no_mcp() -> crate::core::state::SharedMcpServers {
+ std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()))
+ }
use super::SessionLimits;
use super::{journal, DisplayEntry};
use super::{
@@ -12723,7 +13435,7 @@ mod tests {
#[tokio::test]
async fn update_command_requests_an_install_once() {
let mut app = test_app();
- run_command(&mut app, "update").await;
+ run_command(&mut app, "update", &no_mcp()).await;
assert!(app.update_requested, "the loop should pick up the request");
assert!(transcript_text(&app).contains("downloading"), "no progress note");
@@ -12731,7 +13443,7 @@ mod tests {
// concurrent install (two processes rewriting the same binary).
app.update_installing = true;
app.update_requested = false;
- run_command(&mut app, "update").await;
+ run_command(&mut app, "update", &no_mcp()).await;
assert!(!app.update_requested);
assert!(transcript_text(&app).contains("already installing"));
}
@@ -15310,7 +16022,7 @@ mod tests {
#[tokio::test]
async fn login_prompt_captures_keys_and_never_renders_the_key() {
let mut app = test_app();
- run_command(&mut app, "login").await;
+ run_command(&mut app, "login", &no_mcp()).await;
assert!(app.login.is_some(), "/login must open the prompt");
type_key_chars(&mut app, "tk-secret").await;
@@ -15332,7 +16044,7 @@ mod tests {
#[tokio::test]
async fn login_enter_hands_a_trimmed_key_to_the_loop() {
let mut app = test_app();
- run_command(&mut app, "login").await;
+ run_command(&mut app, "login", &no_mcp()).await;
app.login.as_mut().unwrap().paste(" tk-abc\n");
press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
@@ -15343,7 +16055,7 @@ mod tests {
#[tokio::test]
async fn login_rejects_a_mispasted_key_before_any_request() {
let mut app = test_app();
- run_command(&mut app, "login").await;
+ run_command(&mut app, "login", &no_mcp()).await;
type_key_chars(&mut app, "tk-abc def").await;
press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
@@ -15361,7 +16073,7 @@ mod tests {
#[tokio::test]
async fn login_backspace_edits_and_esc_cancels() {
let mut app = test_app();
- run_command(&mut app, "login").await;
+ run_command(&mut app, "login", &no_mcp()).await;
type_key_chars(&mut app, "tk-ab").await;
press(&mut app, KeyCode::Backspace, KeyModifiers::NONE).await;
assert_eq!(app.login.as_ref().unwrap().input, "tk-a");
@@ -15374,7 +16086,7 @@ mod tests {
#[tokio::test]
async fn login_stays_cancellable_while_verifying() {
let mut app = test_app();
- run_command(&mut app, "login").await;
+ run_command(&mut app, "login", &no_mcp()).await;
app.login.as_mut().unwrap().paste("tk-abc");
press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
app.login_submit.take();
@@ -15393,7 +16105,7 @@ mod tests {
#[tokio::test]
async fn failed_verification_keeps_the_prompt_open_with_the_reason() {
let mut app = test_app();
- run_command(&mut app, "login").await;
+ run_command(&mut app, "login", &no_mcp()).await;
app.login.as_mut().unwrap().paste("tk-abc");
press(&mut app, KeyCode::Enter, KeyModifiers::NONE).await;
app.login_submit.take();
@@ -16822,7 +17534,7 @@ mod tests {
let mut app = test_app();
// `with_temp_home` is sync; drive the async command on a dedicated runtime.
let rt = tokio::runtime::Runtime::new().unwrap();
- rt.block_on(super::run_command(&mut app, "model"));
+ rt.block_on(super::run_command(&mut app, "model", &no_mcp()));
let picker = app.picker.as_ref().expect("model picker opened");
assert_eq!(picker.kind, PickerKind::SelectModel);
@@ -16855,7 +17567,7 @@ mod tests {
let mut app = test_app();
let rt = tokio::runtime::Runtime::new().unwrap();
- rt.block_on(super::run_command(&mut app, "model"));
+ rt.block_on(super::run_command(&mut app, "model", &no_mcp()));
// The picker opened (no reachable pairs => the note path fires,
// but there is no panic, no hang, and the provider stays put).
@@ -16864,7 +17576,7 @@ mod tests {
// Opening once more must not re-contact the dead endpoint: the
// session short-circuit means the second open is near-instant.
- rt.block_on(super::run_command(&mut app, "model"));
+ rt.block_on(super::run_command(&mut app, "model", &no_mcp()));
});
}
@@ -19411,7 +20123,7 @@ mod tests {
async fn compact_command_notes_when_unavailable() {
let mut app = test_app();
app.history.push(json!({ "role": "user", "content": "hi" }));
- run_command(&mut app, "compact").await;
+ run_command(&mut app, "compact", &no_mcp()).await;
let text: String = app.transcript.iter().map(row_text).collect();
assert!(text.contains("compaction unavailable"), "got: {text}");
// History untouched when no session is attached.
@@ -19423,7 +20135,7 @@ mod tests {
async fn compact_command_is_refused_while_one_is_in_flight() {
let mut app = test_app();
app.compacting = Some(CompactKind::Auto);
- run_command(&mut app, "compact").await;
+ run_command(&mut app, "compact", &no_mcp()).await;
let text: String = app.transcript.iter().map(row_text).collect();
assert!(text.contains("already compacting"), "got: {text}");
assert!(app.compact_request.is_none());
@@ -20582,7 +21294,7 @@ mod tests {
#[tokio::test]
async fn help_lists_every_keybinding() {
let mut app = test_app();
- run_command(&mut app, "help").await;
+ run_command(&mut app, "help", &no_mcp()).await;
let text: String = app.transcript.iter().map(row_text).collect();
for (keys, description) in KEY_BINDINGS {
assert!(text.contains(keys), "missing keys {keys:?} in: {text}");
@@ -20701,7 +21413,7 @@ mod tests {
#[tokio::test]
async fn goal_set_stores_condition_and_starts_a_turn() {
let mut app = test_app();
- run_command(&mut app, "goal all tests in test/auth pass").await;
+ run_command(&mut app, "goal all tests in test/auth pass", &no_mcp()).await;
let goal = app.goal.as_ref().expect("goal should be set");
assert_eq!(goal.condition, "all tests in test/auth pass");
assert!(goal.is_active());
@@ -20719,7 +21431,7 @@ mod tests {
async fn goal_clear_removes_active_goal() {
let mut app = test_app();
app.goal = Some(crate::core::agent::goal::GoalState::new("x"));
- run_command(&mut app, "goal clear").await;
+ run_command(&mut app, "goal clear", &no_mcp()).await;
assert!(app.goal.is_none());
let text: String = app.transcript.iter().map(row_text).collect();
assert!(text.contains("goal cleared"), "missing note: {text}");
@@ -20728,7 +21440,7 @@ mod tests {
#[tokio::test]
async fn goal_clear_with_no_goal_notes() {
let mut app = test_app();
- run_command(&mut app, "goal clear").await;
+ run_command(&mut app, "goal clear", &no_mcp()).await;
assert!(app.goal.is_none());
let text: String = app.transcript.iter().map(row_text).collect();
assert!(text.contains("no active goal"), "missing note: {text}");
@@ -20741,7 +21453,7 @@ mod tests {
goal.turns = 3;
goal.last_reason = "two files still modified".into();
app.goal = Some(goal);
- run_command(&mut app, "goal").await;
+ run_command(&mut app, "goal", &no_mcp()).await;
let text: String = app.transcript.iter().map(row_text).collect();
assert!(text.contains("make git status clean"), "condition: {text}");
assert!(text.contains("turns: 3"), "turn count: {text}");
@@ -20751,7 +21463,7 @@ mod tests {
#[tokio::test]
async fn goal_status_with_no_goal_notes() {
let mut app = test_app();
- run_command(&mut app, "goal").await;
+ run_command(&mut app, "goal", &no_mcp()).await;
let text: String = app.transcript.iter().map(row_text).collect();
assert!(text.contains("no active goal"), "missing note: {text}");
}
@@ -20759,7 +21471,7 @@ mod tests {
#[tokio::test]
async fn effort_command_reports_current_level() {
let mut app = test_app();
- run_command(&mut app, "effort").await;
+ run_command(&mut app, "effort", &no_mcp()).await;
let text: String = app.transcript.iter().map(row_text).collect();
assert!(text.contains("medium"), "default level not reported: {text}");
}
@@ -20767,7 +21479,7 @@ mod tests {
#[tokio::test]
async fn effort_command_sets_valid_level() {
let mut app = test_app();
- run_command(&mut app, "effort high").await;
+ run_command(&mut app, "effort high", &no_mcp()).await;
assert_eq!(app.reasoning_effort, "high");
assert_eq!(app.last_non_low_effort, "high");
let text: String = app.transcript.iter().map(row_text).collect();
@@ -20777,7 +21489,7 @@ mod tests {
#[tokio::test]
async fn effort_command_rejects_unknown_level() {
let mut app = test_app();
- run_command(&mut app, "effort turbo").await;
+ run_command(&mut app, "effort turbo", &no_mcp()).await;
assert_eq!(app.reasoning_effort, "medium", "invalid level must not apply");
let text: String = app.transcript.iter().map(row_text).collect();
assert!(text.contains("unknown effort level"), "missing note: {text}");
@@ -20915,9 +21627,9 @@ mod tests {
async fn plan_command_enters_and_exits_while_idle() {
use crate::core::agent::plan::RunMode;
let mut app = test_app();
- run_command(&mut app, "plan").await;
+ run_command(&mut app, "plan", &no_mcp()).await;
assert_eq!(app.run_mode, RunMode::Plan);
- run_command(&mut app, "plan exit").await;
+ run_command(&mut app, "plan exit", &no_mcp()).await;
assert_eq!(app.run_mode, RunMode::Normal);
}
@@ -20926,7 +21638,7 @@ mod tests {
use crate::core::agent::plan::RunMode;
let mut app = test_app();
app.status = Status::Running;
- run_command(&mut app, "plan").await;
+ run_command(&mut app, "plan", &no_mcp()).await;
assert_eq!(app.run_mode, RunMode::Normal, "must not switch mid-turn");
let text: String = app.transcript.iter().map(row_text).collect();
assert!(text.contains("only settable while idle"), "note: {text}");
@@ -20936,7 +21648,7 @@ mod tests {
async fn plan_command_with_text_enters_plan_and_submits_it() {
use crate::core::agent::plan::RunMode;
let mut app = test_app();
- run_command(&mut app, "plan make a html cat slide. use 3 subagents to research").await;
+ run_command(&mut app, "plan make a html cat slide. use 3 subagents to research", &no_mcp()).await;
assert_eq!(app.run_mode, RunMode::Plan, "text arg must also enter plan mode");
assert_eq!(app.status, Status::Running, "seeded text must start a turn");
let text: String = app.transcript.iter().map(row_text).collect();
@@ -20951,7 +21663,7 @@ mod tests {
use crate::core::agent::plan::RunMode;
let mut app = test_app();
app.run_mode = RunMode::Plan;
- run_command(&mut app, "plan investigate the auth module").await;
+ run_command(&mut app, "plan investigate the auth module", &no_mcp()).await;
assert_eq!(app.run_mode, RunMode::Plan);
assert_eq!(app.status, Status::Running);
let text: String = app.transcript.iter().map(row_text).collect();
@@ -21641,7 +22353,7 @@ mod tests {
async fn todo_editor_mutations_update_the_canonical_list() {
let mut app = test_app();
// Add through the same `append` op the model uses.
- run_command(&mut app, "todo add Build | ship it").await;
+ run_command(&mut app, "todo add Build | ship it", &no_mcp()).await;
assert_eq!(app.todos.done_total(), (0, 1));
assert_eq!(app.todos.active().unwrap().1.content, "ship it");
// Mark it done via the editor helper; the projection reflects it.
@@ -21658,23 +22370,23 @@ mod tests {
#[tokio::test]
async fn todo_clear_command_empties_the_whole_list() {
let mut app = test_app();
- run_command(&mut app, "todo add Build | ship it").await;
- run_command(&mut app, "todo add Build | and this").await;
+ run_command(&mut app, "todo add Build | ship it", &no_mcp()).await;
+ run_command(&mut app, "todo add Build | and this", &no_mcp()).await;
assert_eq!(app.todos.done_total(), (0, 2));
- run_command(&mut app, "todo clear").await;
+ run_command(&mut app, "todo clear", &no_mcp()).await;
assert!(app.todos.is_empty(), "{:?}", app.todos);
// Clearing an already-empty list is a no-op note, not an error.
- run_command(&mut app, "todo clear").await;
+ run_command(&mut app, "todo clear", &no_mcp()).await;
assert!(app.todos.is_empty());
}
#[tokio::test]
async fn todo_command_bare_opens_editor_overlay() {
let mut app = test_app();
- run_command(&mut app, "todo add first").await;
- run_command(&mut app, "todo").await;
+ run_command(&mut app, "todo add first", &no_mcp()).await;
+ run_command(&mut app, "todo", &no_mcp()).await;
assert!(matches!(
app.picker.as_ref().map(|p| p.kind),
Some(PickerKind::Todo)
@@ -21827,7 +22539,7 @@ mod tests {
app.tokens = 42;
app.push(Line::raw("old content"));
- run_command(&mut app, "new").await;
+ run_command(&mut app, "new", &no_mcp()).await;
assert!(app.history.is_empty());
assert!(app.thread_id.is_none(), "must detach from the saved thread");
@@ -21843,7 +22555,7 @@ mod tests {
app.approval_phrasing = "--safe: approval needed".to_string();
app.push(Line::raw("old content"));
- run_command(&mut app, "clear").await;
+ run_command(&mut app, "clear", &no_mcp()).await;
let text: String = app.transcript.iter().map(row_text).collect();
assert!(
@@ -22312,7 +23024,7 @@ mod tests {
"---\ndescription: Build a feature\n---\nBuild: $ARGUMENTS",
);
// Plain short form.
- run_command(&mut app, "feature-dev add auth").await;
+ run_command(&mut app, "feature-dev add auth", &no_mcp()).await;
let user = app.history.iter().last().unwrap();
assert!(
user.get("content")
@@ -22326,7 +23038,7 @@ mod tests {
transcript_text(&app)
);
// Explicit qualified form.
- run_command(&mut app, "command:feature-dev:feature-dev fix tests").await;
+ run_command(&mut app, "command:feature-dev:feature-dev fix tests", &no_mcp()).await;
let user = app.history.iter().last().unwrap();
assert!(
user.get("content")
@@ -22335,7 +23047,7 @@ mod tests {
"explicit dispatch: {user}"
);
// Unknown command still notes.
- run_command(&mut app, "warp_drive").await;
+ run_command(&mut app, "warp_drive", &no_mcp()).await;
assert!(transcript_text(&app).contains("unknown command '/warp_drive'"));
let _ = std::fs::remove_dir_all(&root);
}
@@ -22448,14 +23160,14 @@ mod tests {
// the TUI); it hands the spec to the loop, which runs the install off
// the render loop. Drive the handoff: the request is recorded, a second
// is refused while one is in flight, and the loop clears it on pick-up.
- run_command(&mut app, &format!("plugin install file://{}", repo.display())).await;
+ run_command(&mut app, &format!("plugin install file://{}", repo.display()), &no_mcp()).await;
assert!(
app.plugin_install_request.is_some(),
"install spec should be handed to the loop"
);
assert!(transcript_text(&app).contains("installing plugin..."), "{}", transcript_text(&app));
app.plugin_installing = true;
- run_command(&mut app, "plugin install file://nowhere").await;
+ run_command(&mut app, "plugin install file://nowhere", &no_mcp()).await;
assert!(
transcript_text(&app).contains("already in progress"),
"a second /plugin install must be refused: {}",
@@ -22479,7 +23191,7 @@ mod tests {
crate::core::agent::skills::plugins_dir(&root).join(".installing-stale"),
)
.unwrap();
- run_command(&mut app, "plugin list").await;
+ run_command(&mut app, "plugin list", &no_mcp()).await;
let text = transcript_text(&app);
assert!(
text.contains("plugin release-tools (v1.2.0 - 1 skill)"),
@@ -22488,12 +23200,12 @@ mod tests {
assert!(!text.contains("Release automation"), "{text}");
assert!(!text.contains("release-tools:prepare"), "{text}");
- run_command(&mut app, "plugin list release-tools").await;
+ run_command(&mut app, "plugin list release-tools", &no_mcp()).await;
let detail = transcript_text(&app);
assert!(detail.contains("Release automation"), "{detail}");
assert!(detail.contains("release-tools:prepare"), "{detail}");
- run_command(&mut app, "plugin list missing").await;
+ run_command(&mut app, "plugin list missing", &no_mcp()).await;
assert!(
transcript_text(&app).contains("plugin 'missing' is not installed"),
"{}",
@@ -22502,20 +23214,20 @@ mod tests {
// The installed plugin's skill resolves and dispatches like a project
// skill (qualified form here; the short form is covered by unit tests).
- run_command(&mut app, "release-tools:prepare").await;
+ run_command(&mut app, "release-tools:prepare", &no_mcp()).await;
assert!(
transcript_text(&app).contains("[skill:release-tools:prepare]"),
"dispatch: {}",
transcript_text(&app)
);
- run_command(&mut app, "plugin remove release-tools").await;
+ run_command(&mut app, "plugin remove release-tools", &no_mcp()).await;
assert!(
transcript_text(&app).contains("removed plugin 'release-tools'"),
"remove note: {}",
transcript_text(&app)
);
- run_command(&mut app, "plugin list").await;
+ run_command(&mut app, "plugin list", &no_mcp()).await;
assert!(
transcript_text(&app).contains("no plugins installed"),
"empty list: {}",
@@ -22602,7 +23314,7 @@ mod tests {
#[tokio::test]
async fn run_command_dispatches_installed_skill() {
let (mut app, root) = skill_test_app("deploy", "How to deploy.");
- run_command(&mut app, "deploy").await;
+ run_command(&mut app, "deploy", &no_mcp()).await;
assert!(
transcript_text(&app).contains("[skill:deploy]"),
"compact row: {}",
@@ -22629,7 +23341,7 @@ mod tests {
#[tokio::test]
async fn run_command_threads_skill_args() {
let (mut app, root) = skill_test_app("deploy", "How to deploy.");
- run_command(&mut app, "deploy staging --force").await;
+ run_command(&mut app, "deploy staging --force", &no_mcp()).await;
let user = app
.history
.iter()
@@ -22653,13 +23365,13 @@ mod tests {
// A skill named like a builtin command: the short form runs the
// command; `/skill:cancel` still reaches the skill.
let (mut app, root) = skill_test_app("cancel", "Cancels things.");
- run_command(&mut app, "cancel").await;
+ run_command(&mut app, "cancel", &no_mcp()).await;
assert!(
!transcript_text(&app).contains("[skill:cancel]"),
"command wins the short form: {}",
transcript_text(&app)
);
- run_command(&mut app, "skill:cancel").await;
+ run_command(&mut app, "skill:cancel", &no_mcp()).await;
assert!(transcript_text(&app).contains("[skill:cancel]"));
let _ = std::fs::remove_dir_all(&root);
}
@@ -22710,7 +23422,7 @@ mod tests {
#[tokio::test]
async fn run_command_unknown_still_notes() {
let (mut app, root) = skill_test_app("deploy", "How to deploy.");
- run_command(&mut app, "warp_drive").await;
+ run_command(&mut app, "warp_drive", &no_mcp()).await;
assert!(transcript_text(&app).contains("unknown command '/warp_drive'"));
let _ = std::fs::remove_dir_all(&root);
}
@@ -23380,7 +24092,7 @@ mod tests {
async fn probe_blocks() {
let mut app = test_app();
app.note("conversation cleared");
- run_command(&mut app, "help").await;
+ run_command(&mut app, "help", &no_mcp()).await;
for l in render_rows(&mut app, 84, 40) { println!("|{}", l.trim_end()); }
}
@@ -23495,4 +24207,393 @@ mod tests {
"the last body row must map to the last transcript row"
);
}
+
+ // --- `/mcp` management screen -------------------------------------------
+
+ /// Write an `mcp_config.json` with the given servers into the redirected
+ /// data folder, so the `/mcp` screen reads a real config.
+ fn write_mcp_config(folder: &std::path::Path, servers: serde_json::Value) {
+ std::fs::write(
+ folder.join("mcp_config.json"),
+ serde_json::to_string(&serde_json::json!({
+ "mcpServers": servers,
+ "mcpSettings": {},
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ }
+
+ fn rt() -> tokio::runtime::Runtime {
+ tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ }
+
+ /// The regression this whole screen exists for: a fresh install used to get
+ /// a note and no screen, so `a` (add) -- the only thing that could fix the
+ /// empty state -- was unreachable.
+ #[test]
+ fn the_mcp_screen_opens_on_a_watermark_row_when_nothing_is_configured() {
+ crate::core::app::commands::with_temp_data_folder(|_| {
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_picker(&mut app, &no_mcp()));
+
+ let picker = app.picker.as_ref().expect("the screen opens even so");
+ assert_eq!(picker.kind, PickerKind::ToggleMcp);
+ assert_eq!(picker.items.len(), 1);
+ assert!(picker.items[0].label.contains("press a to add"));
+ // An empty value marks the row inert, the way the provider screen's
+ // watermark does.
+ assert!(picker.items[0].value.is_empty());
+ assert!(picker.action_hint().contains("a add"));
+ });
+ }
+
+ #[test]
+ fn the_mcp_screen_lists_configured_servers_with_their_state() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "files": { "command": "npx", "args": ["-y", "files"], "active": true },
+ "remote": { "type": "http", "url": "https://x/mcp", "active": false },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_picker(&mut app, &no_mcp()));
+
+ let items = &app.picker.as_ref().unwrap().items;
+ assert_eq!(items.len(), 2);
+ // Sorted by name, so the order is stable across runs.
+ assert_eq!(items[0].value, "files");
+ assert_eq!(items[0].checkbox, Some(true));
+ assert!(items[0].label.contains("not connected"), "{}", items[0].label);
+ assert_eq!(items[1].value, "remote");
+ assert_eq!(items[1].checkbox, Some(false));
+ assert!(items[1].label.contains("disabled"), "{}", items[1].label);
+ });
+ }
+
+ /// An http server with no stored tokens reads as `needs auth` rather than
+ /// the bare `not connected` a stdio server gets: the two have different
+ /// fixes.
+ #[test]
+ fn an_unauthenticated_remote_server_is_labelled_needs_auth() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "remote": { "type": "http", "url": "https://x/mcp", "active": true },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_picker(&mut app, &no_mcp()));
+ assert!(app.picker.as_ref().unwrap().items[0]
+ .label
+ .contains("needs auth"));
+ });
+ }
+
+ #[test]
+ fn the_detail_screen_shows_status_auth_and_where_the_config_lives() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "remote": { "type": "http", "url": "https://x/mcp", "active": true },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_detail(&mut app, "remote", &no_mcp()));
+
+ assert_eq!(app.picker.as_ref().unwrap().kind, PickerKind::McpServer);
+ let detail = app.mcp_detail.as_ref().expect("detail is held on App");
+ let text: String = super::mcp_detail_lines(detail, 120)
+ .iter()
+ .map(|l| {
+ l.spans
+ .iter()
+ .map(|s| s.content.as_ref())
+ .collect::<String>()
+ })
+ .collect::<Vec<_>>()
+ .join("\n");
+
+ assert!(text.contains("remote"), "{text}");
+ assert!(text.contains("Status:"), "{text}");
+ assert!(text.contains("not connected"), "{text}");
+ assert!(text.contains("Auth:"), "{text}");
+ assert!(text.contains("not authenticated"), "{text}");
+ assert!(text.contains("URL:"), "{text}");
+ assert!(text.contains("https://x/mcp"), "{text}");
+ assert!(text.contains("Config location:"), "{text}");
+ assert!(text.contains("mcp_config.json"), "{text}");
+ assert!(text.contains("Tools:"), "{text}");
+ });
+ }
+
+ /// A stdio server has no HTTP transport, so the auth rows are absent rather
+ /// than present-and-inert; and a disconnected server has no tools to view.
+ #[test]
+ fn detail_actions_are_filtered_to_what_the_server_can_actually_do() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "files": { "command": "npx", "args": [], "active": true },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_detail(&mut app, "files", &no_mcp()));
+
+ let values: Vec<&str> = app
+ .picker
+ .as_ref()
+ .unwrap()
+ .items
+ .iter()
+ .map(|i| i.value.as_str())
+ .collect();
+ assert!(!values.contains(&super::MCP_ACTION_AUTH), "{values:?}");
+ assert!(!values.contains(&super::MCP_ACTION_CLEAR_AUTH), "{values:?}");
+ // Not connected, so there is nothing to list.
+ assert!(!values.contains(&super::MCP_ACTION_TOOLS), "{values:?}");
+ assert!(values.contains(&super::MCP_ACTION_TOGGLE), "{values:?}");
+ assert!(values.contains(&super::MCP_ACTION_EDIT), "{values:?}");
+ assert!(values.contains(&super::MCP_ACTION_REMOVE), "{values:?}");
+ // An active server can be reconnected; the label reads Disable.
+ assert!(values.contains(&super::MCP_ACTION_RECONNECT), "{values:?}");
+ let toggle = app
+ .picker
+ .as_ref()
+ .unwrap()
+ .items
+ .iter()
+ .find(|i| i.value == super::MCP_ACTION_TOGGLE)
+ .unwrap();
+ assert_eq!(toggle.label, "Disable");
+ // Rows are numbered, as the screen is meant to read.
+ assert_eq!(app.picker.as_ref().unwrap().items[0].hint.as_deref(), Some("1."));
+ });
+ }
+
+ #[test]
+ fn a_remote_server_offers_authenticate_and_no_clear_until_there_is_something_to_clear() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "remote": { "type": "http", "url": "https://x/mcp", "active": false },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_detail(&mut app, "remote", &no_mcp()));
+
+ let items = &app.picker.as_ref().unwrap().items;
+ let auth = items
+ .iter()
+ .find(|i| i.value == super::MCP_ACTION_AUTH)
+ .expect("an unauthenticated remote can sign in");
+ assert_eq!(auth.label, "Authenticate");
+ assert!(!items.iter().any(|i| i.value == super::MCP_ACTION_CLEAR_AUTH));
+ // Inactive, so Reconnect is not offered and the toggle reads Enable.
+ assert!(!items.iter().any(|i| i.value == super::MCP_ACTION_RECONNECT));
+ assert_eq!(
+ items
+ .iter()
+ .find(|i| i.value == super::MCP_ACTION_TOGGLE)
+ .unwrap()
+ .label,
+ "Enable"
+ );
+ });
+ }
+
+ /// A hand-written `Authorization` header is the user's own credential: OAuth
+ /// must not offer to replace it, because doing so would break it.
+ #[test]
+ fn a_hand_written_authorization_header_suppresses_the_oauth_actions() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "remote": {
+ "type": "http",
+ "url": "https://x/mcp",
+ "headers": { "Authorization": "Bearer mine" },
+ "active": true,
+ },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_detail(&mut app, "remote", &no_mcp()));
+ let items = &app.picker.as_ref().unwrap().items;
+ assert!(!items.iter().any(|i| i.value == super::MCP_ACTION_AUTH));
+ assert!(!items.iter().any(|i| i.value == super::MCP_ACTION_CLEAR_AUTH));
+ });
+ }
+
+ /// The watermark row is inert: Enter must not open a detail screen for the
+ /// empty string, and Space must not try to toggle it.
+ #[test]
+ fn the_watermark_row_does_nothing_on_enter_or_space() {
+ crate::core::app::commands::with_temp_data_folder(|_| {
+ let registry: PermissionRegistry =
+ std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()));
+ let mut current: Option<CurrentRun> = None;
+ let mut app = test_app();
+ let servers = no_mcp();
+ rt().block_on(async {
+ super::open_mcp_picker(&mut app, &servers).await;
+ for code in [KeyCode::Enter, KeyCode::Char(' ')] {
+ handle_key(
+ &mut app,
+ KeyEvent::new(code, KeyModifiers::NONE),
+ &registry,
+ &mut current,
+ &servers,
+ )
+ .await;
+ assert!(app.mcp_detail.is_none(), "{code:?} opened a detail screen");
+ assert_eq!(
+ app.picker.as_ref().map(|p| p.kind),
+ Some(PickerKind::ToggleMcp),
+ "{code:?} left the list"
+ );
+ }
+ });
+ });
+ }
+
+ /// Esc on the detail screen steps back up to the list rather than closing
+ /// `/mcp` outright.
+ #[test]
+ fn esc_on_the_detail_screen_returns_to_the_server_list() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "files": { "command": "npx", "args": [], "active": true },
+ }),
+ );
+ let registry: PermissionRegistry =
+ std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashMap::new()));
+ let mut current: Option<CurrentRun> = None;
+ let mut app = test_app();
+ let servers = no_mcp();
+ rt().block_on(async {
+ super::open_mcp_detail(&mut app, "files", &servers).await;
+ assert_eq!(app.picker.as_ref().unwrap().kind, PickerKind::McpServer);
+
+ handle_key(
+ &mut app,
+ KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
+ &registry,
+ &mut current,
+ &servers,
+ )
+ .await;
+ assert_eq!(
+ app.picker.as_ref().map(|p| p.kind),
+ Some(PickerKind::ToggleMcp),
+ "Esc should step back, not close"
+ );
+ assert!(app.mcp_detail.is_none());
+ });
+ });
+ }
+
+ /// Removing a server takes its tokens with it: a later server reusing the
+ /// name must not silently inherit someone else's authorization.
+ #[test]
+ fn removing_a_server_also_forgets_its_stored_credentials() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "remote": { "type": "http", "url": "https://x/mcp", "active": false },
+ }),
+ );
+ // A credential file the removal must clean up. Spelled out rather
+ // than stubbed: an unparseable record would read as an empty store
+ // and the assertion would pass without the removal doing anything.
+ let store = folder.join("mcp_oauth.json");
+ std::fs::write(
+ &store,
+ serde_json::to_string(&serde_json::json!({
+ "remote": {
+ "client_id": "c1",
+ "tokens": {
+ "access_token": "at",
+ "token_type": "bearer",
+ "expires_in": 3600
+ },
+ "expires_at": 9_999_999_999u64,
+ "resource": "https://x/mcp"
+ }
+ }))
+ .unwrap(),
+ )
+ .unwrap();
+ // The fixture must actually load, or this test proves nothing.
+ assert!(super::super::mcp::auth_status(
+ "remote",
+ &serde_json::json!({ "type": "http", "url": "https://x/mcp" })
+ ) != crate::core::mcp::oauth::AuthStatus::Unauthenticated);
+
+ let mut app = test_app();
+ rt().block_on(super::remove_mcp_server(&mut app, "remote", &no_mcp()));
+
+ assert!(super::super::mcp::get_server("remote").is_none());
+ let left = std::fs::read_to_string(&store).unwrap_or_default();
+ assert!(!left.contains("remote"), "credentials survived: {left}");
+ });
+ }
+
+ /// The detail screen must open in one frame, so the tool list is requested
+ /// as a job rather than awaited inline.
+ #[test]
+ fn a_connected_servers_tool_list_is_requested_as_a_job_not_awaited() {
+ crate::core::app::commands::with_temp_data_folder(|folder| {
+ write_mcp_config(
+ folder,
+ serde_json::json!({
+ "files": { "command": "npx", "args": [], "active": true },
+ }),
+ );
+ let mut app = test_app();
+ rt().block_on(super::open_mcp_detail(&mut app, "files", &no_mcp()));
+ // Not connected here, so nothing is requested and the state says why.
+ assert!(app.mcp_job_request.is_none());
+ assert!(matches!(
+ app.mcp_detail.as_ref().unwrap().tools,
+ super::ToolsState::Unavailable
+ ));
+ });
+ }
+
+ #[test]
+ fn a_long_value_is_clamped_instead_of_pushing_the_border_off_the_frame() {
+ use ratatui::text::Span;
+ let line = Line::from(vec![
+ Span::raw("URL: "),
+ Span::raw("x".repeat(400)),
+ ]);
+ let clamped = super::clamp_line(line, 40);
+ let width: usize = clamped
+ .spans
+ .iter()
+ .map(|s| s.content.chars().count())
+ .sum();
+ assert!(width <= 38, "clamped to {width}");
+ assert!(clamped
+ .spans
+ .last()
+ .unwrap()
+ .content
+ .ends_with('\u{2026}'));
+ }
+
}
diff --git a/src-tauri/src/core/mcp/commands.rs b/src-tauri/src/core/mcp/commands.rs
index 89677666a..9413d5fd2 100644
--- a/src-tauri/src/core/mcp/commands.rs
+++ b/src-tauri/src/core/mcp/commands.rs
@@ -1,6 +1,7 @@
use rmcp::model::{CallToolRequestParam, CallToolResult};
use serde_json::{json, Map, Value};
use tauri::{AppHandle, Emitter, Manager, Runtime, State};
+use tauri_plugin_opener::OpenerExt;
use tokio::sync::oneshot;
use tokio::time::timeout;
@@ -11,6 +12,7 @@ use super::{
use crate::core::{
app::commands::get_jan_data_folder_path,
mcp::models::{McpSettings, ServerSummary},
+ mcp::oauth,
state::AppState,
};
use crate::core::{
@@ -555,6 +557,83 @@ fn parse_mcp_settings(value: Option<&Value>) -> McpSettings {
.unwrap_or_default()
}
+/// Read one configured server's entry out of `mcp_config.json`. Errors rather
+/// than defaulting: every caller here is acting on a server the user picked, and
+/// a silent empty config would report "not authenticated" for a typo.
+fn read_server_config<R: Runtime>(app: &AppHandle<R>, name: &str) -> Result<Value, String> {
+ let mut path = get_jan_data_folder_path(app.clone());
+ path.push("mcp_config.json");
+ let body = fs::read_to_string(&path).map_err(|e| e.to_string())?;
+ serde_json::from_str::<Value>(&body)
+ .map_err(|e| format!("Failed to parse mcp_config.json: {e}"))?
+ .get("mcpServers")
+ .and_then(|s| s.get(name))
+ .cloned()
+ .ok_or_else(|| format!("server '{name}' not found in mcp_config.json"))
+}
+
+/// The OAuth state of one configured server. Local only -- no network -- so the
+/// settings screen can call it per row without a round trip each.
+#[tauri::command]
+pub async fn get_mcp_auth_status<R: Runtime>(
+ app: AppHandle<R>,
+ name: String,
+) -> Result<oauth::AuthStatusInfo, String> {
+ let config = read_server_config(&app, &name)?;
+ let folder = get_jan_data_folder_path(app);
+ Ok(oauth::status(&folder, &name, &config).into())
+}
+
+/// Run an interactive OAuth authorization for one server: discover the
+/// provider, register a client, open the consent page, and wait for the
+/// redirect on a loopback listener.
+///
+/// Resolves only once the flow finishes (or times out after five minutes), so
+/// the caller awaits a single promise. The consent url is also emitted as
+/// `mcp-oauth-url` before the wait begins, so the UI can offer it as a link
+/// when the browser did not come up.
+#[tauri::command]
+pub async fn authorize_mcp_server<R: Runtime>(
+ app: AppHandle<R>,
+ name: String,
+) -> Result<(), String> {
+ let config = read_server_config(&app, &name)?;
+ let url = config
+ .get("url")
+ .and_then(Value::as_str)
+ .filter(|u| !u.trim().is_empty())
+ .ok_or_else(|| {
+ format!("'{name}' is a stdio server - OAuth applies to http/sse servers only")
+ })?;
+
+ let pending = oauth::begin(&name, url).await?;
+ if let Err(e) = app.emit(
+ "mcp-oauth-url",
+ json!({ "server": &name, "url": &pending.authorization_url }),
+ ) {
+ log::error!("Failed to emit mcp-oauth-url event: {e}");
+ }
+ // Best-effort: the url has already been emitted, so a session with no
+ // browser can still finish by opening it by hand.
+ if let Err(e) = app.opener().open_url(&pending.authorization_url, None::<&str>) {
+ log::warn!("Could not open the browser for '{name}': {e}");
+ }
+
+ let folder = get_jan_data_folder_path(app);
+ pending.complete(&folder).await.map(|_| ())
+}
+
+/// Forget one server's stored tokens. `false` when there were none, so the UI
+/// can tell "cleared" from "nothing to clear".
+#[tauri::command]
+pub async fn clear_mcp_auth<R: Runtime>(
+ app: AppHandle<R>,
+ name: String,
+) -> Result<bool, String> {
+ let folder = get_jan_data_folder_path(app);
+ oauth::clear(&folder, &name)
+}
+
#[tauri::command]
pub async fn get_mcp_configs<R: Runtime>(app: AppHandle<R>) -> Result<String, String> {
let mut path = get_jan_data_folder_path(app.clone());
diff --git a/src-tauri/src/core/mcp/helpers.rs b/src-tauri/src/core/mcp/helpers.rs
index b0bcbdf3b..c2584c89e 100644
--- a/src-tauri/src/core/mcp/helpers.rs
+++ b/src-tauri/src/core/mcp/helpers.rs
@@ -1,6 +1,7 @@
use rmcp::{
model::{ClientCapabilities, ClientInfo, Implementation},
transport::{
+ sse_client::SseClient, streamable_http_client::StreamableHttpClient,
streamable_http_client::StreamableHttpClientTransportConfig, SseClientTransport,
StreamableHttpClientTransport, TokioChildProcess,
},
@@ -19,6 +20,7 @@ use tokio::{
use crate::core::{
app::commands::get_jan_data_folder_path,
mcp::models::{extract_active_status, extract_command_args, McpSettings},
+ mcp::oauth,
mcp::progress::JanClientHandler,
state::{AppState, RunningMcpService, SharedMcpServers},
};
@@ -410,125 +412,42 @@ async fn schedule_mcp_start_task<R: Runtime>(
let config_params = extract_command_args(&config)
.ok_or_else(|| format!("Failed to extract command args from config for {name}"))?;
- if let (Some("http"), Some(url)) = (
+ if let (Some(transport @ ("http" | "sse")), Some(url)) = (
config_params.transport_type.as_deref(),
config_params.url.clone(),
) {
- let transport = StreamableHttpClientTransport::with_client(
- reqwest::Client::builder()
- .default_headers({
- // Map envs to request headers
- let mut headers: tauri::http::HeaderMap = reqwest::header::HeaderMap::new();
- for (key, value) in config_params.headers.iter() {
- if let Some(v_str) = value.as_str() {
- // Try to map env keys to HTTP header names (case-insensitive)
- // Most HTTP headers are Title-Case, so we try to convert
- let header_name =
- reqwest::header::HeaderName::from_bytes(key.as_bytes());
- if let Ok(header_name) = header_name {
- if let Ok(header_value) =
- reqwest::header::HeaderValue::from_str(v_str)
- {
- headers.insert(header_name, header_value);
- }
- }
- }
- }
- headers
- })
- .connect_timeout(config_params.timeout.unwrap_or(Duration::MAX))
- .build()
- .unwrap(),
- StreamableHttpClientTransportConfig {
- uri: url.into(),
- ..Default::default()
- },
- );
-
- let client_info = ClientInfo {
- protocol_version: Default::default(),
- capabilities: ClientCapabilities::default(),
- client_info: Implementation {
- name: "Jan Streamable Client".to_string(),
- version: "0.0.1".to_string(),
- title: None,
- website_url: None,
- icons: None,
- },
+ // One client for both transports, and one place the configured headers
+ // are turned into a `HeaderMap` -- the http and sse arms used to carry
+ // identical copies of that loop.
+ let base = reqwest::Client::builder()
+ .default_headers(header_map(&config_params.headers))
+ .connect_timeout(config_params.timeout.unwrap_or(Duration::MAX))
+ .build()
+ .map_err(|e| format!("Failed to build HTTP client for {name}: {e}"))?;
+
+ // Stored OAuth credentials (refreshed if stale) are wrapped around the
+ // base client so every request carries the bearer token. `None` means
+ // there is no OAuth here -- nothing stored, or the user configured their
+ // own `Authorization` header, which the base client already sends.
+ let authorized =
+ oauth::authorized_client(&app_path, &name, &url, &config, base.clone())
+ .await
+ .map_err(|detail| oauth::NEEDS_AUTH_PREFIX.to_string() + &detail)?;
+ let had_credentials = authorized.is_some();
+
+ let label = if transport == "http" {
+ "Jan Streamable Client"
+ } else {
+ "Jan SSE Client"
};
- let handler = JanClientHandler::new(client_info, name.clone(), app.clone());
- let client = handler.serve(transport).await.inspect_err(|e| {
- log::error!("client error: {e:?}");
- });
-
- match client {
- Ok(client) => {
- log::info!("Connected to server: {:?}", client.peer_info());
- servers.lock().await.insert(name.clone(), client);
+ let handler = JanClientHandler::new(client_info(label), name.clone(), app.clone());
- emit_mcp_update_event(&app, &name);
- }
- Err(e) => {
- log::error!("Failed to connect to server: {e}");
- return Err(format!("Failed to connect to server: {e}"));
- }
- }
- } else if let (Some("sse"), Some(url)) = (
- config_params.transport_type.as_deref(),
- config_params.url.clone(),
- ) {
- let transport = SseClientTransport::start_with_client(
- reqwest::Client::builder()
- .default_headers({
- // Map envs to request headers
- let mut headers = reqwest::header::HeaderMap::new();
- for (key, value) in config_params.headers.iter() {
- if let Some(v_str) = value.as_str() {
- // Try to map env keys to HTTP header names (case-insensitive)
- // Most HTTP headers are Title-Case, so we try to convert
- let header_name =
- reqwest::header::HeaderName::from_bytes(key.as_bytes());
- if let Ok(header_name) = header_name {
- if let Ok(header_value) =
- reqwest::header::HeaderValue::from_str(v_str)
- {
- headers.insert(header_name, header_value);
- }
- }
- }
- }
- headers
- })
- .connect_timeout(config_params.timeout.unwrap_or(Duration::MAX))
- .build()
- .unwrap(),
- rmcp::transport::sse_client::SseClientConfig {
- sse_endpoint: url.into(),
- ..Default::default()
- },
- )
- .await
- .map_err(|e| {
- log::error!("transport error: {e:?}");
- format!("Failed to start SSE transport: {e}")
- })?;
-
- let client_info = ClientInfo {
- protocol_version: Default::default(),
- capabilities: ClientCapabilities::default(),
- client_info: Implementation {
- name: "Jan SSE Client".to_string(),
- version: "0.0.1".to_string(),
- title: None,
- website_url: None,
- icons: None,
- },
+ let client = match (transport, authorized) {
+ ("http", Some(c)) => serve_http(c, &url, handler).await,
+ ("http", None) => serve_http(base, &url, handler).await,
+ (_, Some(c)) => serve_sse(c, &url, handler).await,
+ (_, None) => serve_sse(base, &url, handler).await,
};
- let handler = JanClientHandler::new(client_info, name.clone(), app.clone());
- let client = handler.serve(transport).await.map_err(|e| {
- log::error!("client error: {e:?}");
- e.to_string()
- });
match client {
Ok(client) => {
@@ -539,6 +458,16 @@ async fn schedule_mcp_start_task<R: Runtime>(
}
Err(e) => {
log::error!("Failed to connect to server: {e}");
+ // Only probe when no token was sent: a failure *with* credentials
+ // is either a real outage or tokens the provider revoked, and
+ // discovery cannot tell those apart. Re-authenticating is offered
+ // from the settings screen regardless.
+ if !had_credentials && oauth::advertises_oauth(&url).await {
+ return Err(format!(
+ "{}no credentials are stored ({e})",
+ oauth::NEEDS_AUTH_PREFIX
+ ));
+ }
return Err(format!("Failed to connect to server: {e}"));
}
}
@@ -834,6 +763,78 @@ fn log_mcp_stderr_line(server_name: &str, line: &str) {
}
}
+/// Turn the entry's configured `headers` map into a `HeaderMap`, skipping any
+/// pair that is not a valid header name/value. Shared by both remote transports.
+fn header_map(headers: &serde_json::Map<String, Value>) -> reqwest::header::HeaderMap {
+ let mut map = reqwest::header::HeaderMap::new();
+ for (key, value) in headers.iter() {
+ if let Some(v) = value.as_str() {
+ if let (Ok(name), Ok(val)) = (
+ reqwest::header::HeaderName::from_bytes(key.as_bytes()),
+ reqwest::header::HeaderValue::from_str(v),
+ ) {
+ map.insert(name, val);
+ }
+ }
+ }
+ map
+}
+
+fn client_info(label: &str) -> ClientInfo {
+ ClientInfo {
+ protocol_version: Default::default(),
+ capabilities: ClientCapabilities::default(),
+ client_info: Implementation {
+ name: label.to_string(),
+ version: "0.0.1".to_string(),
+ title: None,
+ website_url: None,
+ icons: None,
+ },
+ }
+}
+
+/// Serve the streamable-http transport over any client that implements it, so
+/// the plain and OAuth-wrapped clients share one transport construction.
+async fn serve_http<C>(
+ client: C,
+ url: &str,
+ handler: JanClientHandler,
+) -> Result<RunningMcpService, String>
+where
+ C: StreamableHttpClient + Send + Sync + 'static,
+{
+ let transport = StreamableHttpClientTransport::with_client(
+ client,
+ StreamableHttpClientTransportConfig {
+ uri: url.to_string().into(),
+ ..Default::default()
+ },
+ );
+ handler.serve(transport).await.map_err(|e| e.to_string())
+}
+
+/// `serve_http`'s counterpart for the legacy SSE transport.
+async fn serve_sse<C>(
+ client: C,
+ url: &str,
+ handler: JanClientHandler,
+) -> Result<RunningMcpService, String>
+where
+ C: SseClient + Send + Sync + 'static,
+{
+ let transport = SseClientTransport::start_with_client(
+ client,
+ rmcp::transport::sse_client::SseClientConfig {
+ sse_endpoint: url.to_string().into(),
+ ..Default::default()
+ },
+ )
+ .await
+ .map_err(|e| format!("Failed to start SSE transport: {e}"))?;
+ handler.serve(transport).await.map_err(|e| e.to_string())
+}
+
fn emit_mcp_update_event<R: Runtime>(app: &AppHandle<R>, name: &str) {
if let Err(e) = app.emit(
"mcp-update",
diff --git a/src-tauri/src/core/mcp/mod.rs b/src-tauri/src/core/mcp/mod.rs
index 0fd6438e7..7e28ea4a0 100644
--- a/src-tauri/src/core/mcp/mod.rs
+++ b/src-tauri/src/core/mcp/mod.rs
@@ -8,6 +8,9 @@ pub mod helpers;
#[cfg(not(feature = "cli"))]
pub mod lockfile;
pub mod models;
+// OAuth for remote MCP servers: Tauri-free so the CLI drives it today and the
+// desktop activation stack can adopt it unchanged.
+pub mod oauth;
#[cfg(not(feature = "cli"))]
pub mod progress;
diff --git a/src-tauri/src/core/mcp/oauth.rs b/src-tauri/src/core/mcp/oauth.rs
new file mode 100644
index 000000000..3c0466e5c
--- /dev/null
+++ b/src-tauri/src/core/mcp/oauth.rs
@@ -0,0 +1,880 @@
+//! OAuth 2.1 (PKCE + dynamic client registration) for remote MCP servers.
+//!
+//! Tauri-free on purpose: the CLI drives this today (`core::cli::mcp` for the
+//! transport, `core::cli::tui` for the `/mcp` screen) and the desktop
+//! activation stack is expected to adopt it unchanged.
+//!
+//! `rmcp`'s `auth` feature owns the protocol -- metadata discovery, PKCE, the
+//! token exchange and the `AuthClient` wrapper that injects the bearer token
+//! into either transport. What lives here is everything around it that rmcp
+//! leaves to the caller: a persistent token store keyed by server name, the
+//! loopback listener that receives the redirect, and absolute expiry tracking.
+//!
+//! Absolute expiry is not redundant. `rmcp`'s `get_access_token` tests
+//! `expires_in()`, which is the *original* lifetime from the token response and
+//! never decreases, so its automatic refresh never fires. `StoredCredentials`
+//! stamps `expires_at` at exchange time and `authorized_client` refreshes
+//! against the clock instead.
+
+use std::collections::BTreeMap;
+use std::net::{Ipv4Addr, SocketAddr};
+use std::path::{Path, PathBuf};
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
+
+use rmcp::transport::auth::{AuthClient, OAuthState, OAuthTokenResponse};
+use serde::{Deserialize, Serialize};
+use serde_json::Value;
+
+/// Credential store, next to `mcp_config.json` but deliberately not inside it:
+/// the config is hand-edited, copied between machines and shared with the
+/// desktop, and bearer tokens have no business travelling with it.
+const STORE_FILE: &str = "mcp_oauth.json";
+
+/// How long the loopback listener waits for the browser redirect before giving
+/// up, so an abandoned sign-in cannot pin a port for the rest of the session.
+const CALLBACK_TIMEOUT: Duration = Duration::from_secs(300);
+
+/// Refresh this long before the token actually expires, so a turn that starts
+/// just under the wire does not fail mid-request.
+const EXPIRY_SKEW: Duration = Duration::from_secs(60);
+
+/// Client name sent during dynamic registration; what the user sees on the
+/// provider's consent screen.
+const CLIENT_NAME: &str = "Jan";
+
+/// Marker the desktop's `activate_mcp_server` prefixes onto an error the user
+/// fixes by signing in, so the settings UI can offer an `Authenticate` button
+/// instead of showing a transport error nobody can act on.
+///
+/// A prefix rather than a typed error because the Tauri command boundary
+/// serializes failures as strings; the CLI has `ConnectError::NeedsAuth` for the
+/// same distinction and does not need this.
+/// Stripped back off on the frontend by `useMcpAuth`'s `needsAuthDetail`; there
+/// is deliberately no Rust splitter, since nothing on this side consumes it.
+pub const NEEDS_AUTH_PREFIX: &str = "NEEDS_AUTH: ";
+
+/// Tokens for one server, as persisted. `client_id` is part of the record
+/// because a dynamically registered client is per-installation: refreshing
+/// needs the same id the code was issued to.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct StoredCredentials {
+ pub client_id: String,
+ pub tokens: OAuthTokenResponse,
+ /// Unix seconds at which `tokens`' access token stops being valid. `None`
+ /// when the provider returned no `expires_in`, which means "until refused".
+ pub expires_at: Option<u64>,
+ /// The MCP url these tokens were issued for. Editing a server's url points
+ /// it at a different resource, so credentials for the old one are stale.
+ pub resource: String,
+}
+
+impl StoredCredentials {
+ fn from_exchange(client_id: String, tokens: OAuthTokenResponse, resource: String) -> Self {
+ let expires_at = expires_at_from(&tokens);
+ Self {
+ client_id,
+ tokens,
+ expires_at,
+ resource,
+ }
+ }
+
+ /// Whether the access token is past `expires_at` (minus the refresh skew).
+ /// A record with no expiry never reports expired.
+ pub fn is_expired(&self) -> bool {
+ let Some(at) = self.expires_at else {
+ return false;
+ };
+ now_secs() + EXPIRY_SKEW.as_secs() >= at
+ }
+
+ fn has_refresh_token(&self) -> bool {
+ use oauth2::TokenResponse;
+ self.tokens.refresh_token().is_some()
+ }
+}
+
+fn expires_at_from(tokens: &OAuthTokenResponse) -> Option<u64> {
+ use oauth2::TokenResponse;
+ tokens.expires_in().map(|d| now_secs() + d.as_secs())
+}
+
+fn now_secs() -> u64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_secs())
+ .unwrap_or(0)
+}
+
+/// What the `/mcp` screen reports on its `Auth:` line.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub enum AuthStatus {
+ /// A stdio server: the transport is a pipe, there is nothing to authorize.
+ NotApplicable,
+ /// The user configured an `Authorization` header by hand. OAuth would fight
+ /// with it, so it is never attempted and never reported as missing.
+ StaticHeader,
+ /// Tokens on disk, still valid.
+ Authenticated { expires_at: Option<u64> },
+ /// Tokens on disk but past their expiry. Renewable without the browser when
+ /// a refresh token came with them.
+ Expired {
+ renewable: bool,
+ expires_at: Option<u64>,
+ },
+ /// Tokens on disk, issued for a different url than the server now points at.
+ StaleResource,
+ /// Nothing stored. Whether that is a problem is up to the server.
+ Unauthenticated,
+}
+
+/// Read the `Auth:` state for one configured server without touching the
+/// network. `config` is the raw `mcp_config.json` entry.
+pub fn status(data_folder: &Path, name: &str, config: &Value) -> AuthStatus {
+ let transport = config
+ .get("type")
+ .and_then(Value::as_str)
+ .unwrap_or("stdio");
+ if transport == "stdio" {
+ return AuthStatus::NotApplicable;
+ }
+ if has_static_authorization(config) {
+ return AuthStatus::StaticHeader;
+ }
+ let Some(stored) = load(data_folder, name) else {
+ return AuthStatus::Unauthenticated;
+ };
+ let url = config.get("url").and_then(Value::as_str).unwrap_or("");
+ if !url.is_empty() && stored.resource != url {
+ return AuthStatus::StaleResource;
+ }
+ if stored.is_expired() {
+ return AuthStatus::Expired {
+ renewable: stored.has_refresh_token(),
+ expires_at: stored.expires_at,
+ };
+ }
+ AuthStatus::Authenticated {
+ expires_at: stored.expires_at,
+ }
+}
+
+/// `AuthStatus` flattened for the wire, so the settings UI can render a badge
+/// and decide which buttons to offer without re-deriving any of it.
+///
+/// A tagged struct rather than the enum itself: `state` is a stable string the
+/// frontend switches on, and adding a variant here cannot silently change the
+/// shape of an existing one.
+#[derive(Debug, Clone, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AuthStatusInfo {
+ /// One of `notApplicable`, `staticHeader`, `authenticated`, `expired`,
+ /// `staleResource`, `unauthenticated`.
+ pub state: &'static str,
+ /// Whether an interactive sign-in is possible and would mean something.
+ pub can_authenticate: bool,
+ /// Whether there are stored tokens to forget.
+ pub has_credentials: bool,
+ /// Whether a stored refresh token can renew this without the browser. Only
+ /// meaningful for `expired`; false everywhere else.
+ pub renewable: bool,
+ /// Unix seconds the access token expires at, when known.
+ pub expires_at: Option<u64>,
+}
+
+impl From<AuthStatus> for AuthStatusInfo {
+ fn from(status: AuthStatus) -> Self {
+ let (state, can_authenticate, has_credentials, renewable, expires_at) = match status {
+ AuthStatus::NotApplicable => ("notApplicable", false, false, false, None),
+ AuthStatus::StaticHeader => ("staticHeader", false, false, false, None),
+ AuthStatus::Authenticated { expires_at } => {
+ ("authenticated", true, true, false, expires_at)
+ }
+ AuthStatus::Expired {
+ renewable,
+ expires_at,
+ } => ("expired", true, true, renewable, expires_at),
+ AuthStatus::StaleResource => ("staleResource", true, true, false, None),
+ AuthStatus::Unauthenticated => ("unauthenticated", true, false, false, None),
+ };
+ Self {
+ state,
+ can_authenticate,
+ has_credentials,
+ renewable,
+ expires_at,
+ }
+ }
+}
+
+/// Whether the entry carries a hand-configured `Authorization` header. Matched
+/// case-insensitively: header names are case-insensitive on the wire, and a
+/// user who typed `authorization` still means the same thing.
+pub fn has_static_authorization(config: &Value) -> bool {
+ config
+ .get("headers")
+ .and_then(Value::as_object)
+ .is_some_and(|h| {
+ h.iter().any(|(k, v)| {
+ k.eq_ignore_ascii_case("authorization")
+ && v.as_str().is_some_and(|s| !s.trim().is_empty())
+ })
+ })
+}
+
+fn store_path(data_folder: &Path) -> PathBuf {
+ data_folder.join(STORE_FILE)
+}
+
+fn read_store(data_folder: &Path) -> BTreeMap<String, StoredCredentials> {
+ match std::fs::read_to_string(store_path(data_folder)) {
+ Ok(s) if !s.trim().is_empty() => serde_json::from_str(&s).unwrap_or_default(),
+ _ => BTreeMap::new(),
+ }
+}
+
+/// Persist the whole store (tmp + rename), owner-only on Unix. The file holds
+/// bearer tokens, so the mode is set on the temp file *before* the rename --
+/// writing world-readable and tightening afterwards leaves a window.
+fn write_store(
+ data_folder: &Path,
+ store: &BTreeMap<String, StoredCredentials>,
+) -> Result<(), String> {
+ let path = store_path(data_folder);
+ let body = serde_json::to_string_pretty(store).map_err(|e| e.to_string())?;
+ let tmp = path.with_extension("json.tmp");
+ std::fs::write(&tmp, body).map_err(|e| e.to_string())?;
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ std::fs::set_permissions(&tmp, std::fs::Permissions::from_mode(0o600))
+ .map_err(|e| e.to_string())?;
+ }
+ std::fs::rename(&tmp, &path).map_err(|e| e.to_string())
+}
+
+pub fn load(data_folder: &Path, name: &str) -> Option<StoredCredentials> {
+ read_store(data_folder).remove(name)
+}
+
+pub fn save(data_folder: &Path, name: &str, creds: &StoredCredentials) -> Result<(), String> {
+ let mut store = read_store(data_folder);
+ store.insert(name.to_string(), creds.clone());
+ write_store(data_folder, &store)
+}
+
+/// Forget one server's tokens. `Ok(false)` when there were none, so the caller
+/// can tell "cleared" from "nothing to clear" without a second read.
+pub fn clear(data_folder: &Path, name: &str) -> Result<bool, String> {
+ let mut store = read_store(data_folder);
+ if store.remove(name).is_none() {
+ return Ok(false);
+ }
+ write_store(data_folder, &store)?;
+ Ok(true)
+}
+
+/// Whether the server at `url` advertises OAuth, used to turn a failed connect
+/// into `needs authentication` rather than a generic transport error. Metadata
+/// discovery is exactly the probe the MCP spec defines for this, so a `true`
+/// here is the server saying so rather than us pattern-matching an error
+/// string.
+pub async fn advertises_oauth(url: &str) -> bool {
+ let Ok(state) = OAuthState::new(url.to_string(), None).await else {
+ return false;
+ };
+ let OAuthState::Unauthorized(manager) = state else {
+ return false;
+ };
+ manager.discover_metadata().await.is_ok()
+}
+
+/// An authorization in flight: the browser has somewhere to go and the loopback
+/// listener is already bound, so the redirect cannot race the port.
+pub struct PendingAuth {
+ state: OAuthState,
+ listener: tokio::net::TcpListener,
+ server: String,
+ resource: String,
+ /// Where to send the user. Always surfaced, never only handed to a browser:
+ /// a remote or headless session finishes by pasting it somewhere else.
+ pub authorization_url: String,
+ pub redirect_uri: String,
+}
+
+/// Start an authorization: bind the loopback listener, register (or reuse) a
+/// client, and build the consent url. Nothing is persisted and no browser is
+/// opened here -- the caller owns both.
+///
+/// The listener is bound *before* the redirect uri is minted because dynamic
+/// registration sends that uri to the provider; picking a port afterwards could
+/// hand out one another process just took.
+pub async fn begin(server: &str, url: &str) -> Result<PendingAuth, String> {
+ let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
+ .await
+ .map_err(|e| format!("could not open a local callback port: {e}"))?;
+ let port = listener
+ .local_addr()
+ .map_err(|e| format!("could not read the callback port: {e}"))?
+ .port();
+ // `localhost` rather than the IP literal: providers commonly allow only the
+ // hostname form in a loopback redirect, and both resolve to this listener.
+ let redirect_uri = format!("http://localhost:{port}/callback");
+
+ let mut state = OAuthState::new(url.to_string(), None)
+ .await
+ .map_err(|e| format!("could not reach '{url}' for OAuth discovery: {e}"))?;
+ state
+ .start_authorization(&[], &redirect_uri, Some(CLIENT_NAME))
+ .await
+ .map_err(|e| format!("'{server}' does not offer OAuth we can use: {e}"))?;
+ let authorization_url = state
+ .get_authorization_url()
+ .await
+ .map_err(|e| format!("could not build the sign-in url for '{server}': {e}"))?;
+
+ Ok(PendingAuth {
+ state,
+ listener,
+ server: server.to_string(),
+ resource: url.to_string(),
+ authorization_url,
+ redirect_uri,
+ })
+}
+
+impl PendingAuth {
+ /// Wait for the browser redirect, exchange the code, and persist the
+ /// tokens. Consumes the flow: the PKCE verifier and CSRF token are
+ /// single-use, so a failed exchange means starting over rather than
+ /// retrying against spent state.
+ pub async fn complete(mut self, data_folder: &Path) -> Result<StoredCredentials, String> {
+ let callback = tokio::time::timeout(CALLBACK_TIMEOUT, accept_callback(&self.listener))
+ .await
+ .map_err(|_| "timed out waiting for the browser to come back".to_string())??;
+
+ self.state
+ .handle_callback(&callback.code, &callback.state)
+ .await
+ .map_err(|e| format!("could not exchange the authorization code: {e}"))?;
+
+ let (client_id, tokens) = self
+ .state
+ .get_credentials()
+ .await
+ .map_err(|e| format!("authorization finished without usable tokens: {e}"))?;
+ let tokens =
+ tokens.ok_or_else(|| "authorization finished without an access token".to_string())?;
+
+ let creds = StoredCredentials::from_exchange(client_id, tokens, self.resource);
+ save(data_folder, &self.server, &creds)?;
+ Ok(creds)
+ }
+}
+
+/// The query parameters of a successful redirect.
+struct Callback {
+ code: String,
+ state: String,
+}
+
+/// Serve exactly one request on the loopback listener and pull `code`/`state`
+/// out of it.
+///
+/// One connection is not always one *request*: a browser may open a speculative
+/// connection, and favicon or `/` probes arrive on their own. So this loops
+/// until a request actually carries the parameters, answering anything else
+/// with a 404 rather than treating it as the redirect and failing the sign-in.
+async fn accept_callback(listener: &tokio::net::TcpListener) -> Result<Callback, String> {
+ use http_body_util::Full;
+ use hyper::body::Bytes;
+ use hyper::server::conn::http1;
+ use hyper::service::service_fn;
+ use hyper_util::rt::TokioIo;
+
+ loop {
+ let (stream, _) = listener
+ .accept()
+ .await
+ .map_err(|e| format!("callback connection failed: {e}"))?;
+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
+
+ let serve = http1::Builder::new().serve_connection(
+ TokioIo::new(stream),
+ service_fn(move |req: hyper::Request<hyper::body::Incoming>| {
+ let tx = tx.clone();
+ async move {
+ let outcome = parse_callback_query(req.uri().query().unwrap_or(""));
+ let body = callback_page(&outcome);
+ let status = match &outcome {
+ Some(_) => 200,
+ None => 404,
+ };
+ if let Some(outcome) = outcome {
+ let _ = tx.send(outcome);
+ }
+ Ok::<_, std::convert::Infallible>(
+ hyper::Response::builder()
+ .status(status)
+ .header("content-type", "text/html; charset=utf-8")
+ .body(Full::new(Bytes::from(body)))
+ .expect("static response builds"),
+ )
+ }
+ }),
+ );
+ // A browser keeps the connection alive after the redirect, so the
+ // connection future would not resolve until it times out. The response
+ // has already been written by the time the result lands in `rx`, so
+ // finishing on that instead of on the connection is what keeps the flow
+ // from stalling for the whole keep-alive window.
+ let outcome = tokio::select! {
+ served = serve => {
+ served.map_err(|e| format!("callback request failed: {e}"))?;
+ rx.try_recv().ok()
+ }
+ Some(outcome) = rx.recv() => Some(outcome),
+ };
+
+ match outcome {
+ Some(Ok(callback)) => return Ok(callback),
+ Some(Err(e)) => return Err(e),
+ // Not the redirect (a favicon probe, say): keep listening.
+ None => continue,
+ }
+ }
+}
+
+/// Pull `code`/`state` (or the provider's `error`) out of a redirect query.
+/// `None` means this request was not the redirect at all, which is the caller's
+/// signal to keep waiting rather than to fail.
+fn parse_callback_query(query: &str) -> Option<Result<Callback, String>> {
+ let mut code = None;
+ let mut state = None;
+ let mut error = None;
+ let mut description = None;
+ for (key, value) in form_urlencoded::parse(query.as_bytes()) {
+ match key.as_ref() {
+ "code" => code = Some(value.into_owned()),
+ "state" => state = Some(value.into_owned()),
+ "error" => error = Some(value.into_owned()),
+ "error_description" => description = Some(value.into_owned()),
+ _ => {}
+ }
+ }
+ // An error is only believed when it carries the `state` it was issued
+ // against: a drive-by request to the open loopback port would otherwise abort
+ // a sign-in that is still in flight. Same reasoning that refuses a `code`
+ // with no `state` below -- unverifiable either way, so neither is acted on.
+ if let (Some(error), Some(_)) = (error, state.as_ref()) {
+ let detail = description.map(|d| format!(": {d}")).unwrap_or_default();
+ return Some(Err(format!(
+ "the provider refused the sign-in ({error}){detail}"
+ )));
+ }
+ match (code, state) {
+ (Some(code), Some(state)) => Some(Ok(Callback { code, state })),
+ // A `code` with no `state` cannot be CSRF-checked, so it is refused
+ // rather than accepted with the check skipped.
+ (Some(_), None) => Some(Err(
+ "the redirect carried no 'state' parameter, so it cannot be verified".to_string(),
+ )),
+ _ => None,
+ }
+}
+
+/// What the browser tab shows once the redirect lands. Plain and self-closing
+/// in wording only -- no script, since a page served over loopback should not
+/// need any.
+fn callback_page(outcome: &Option<Result<Callback, String>>) -> String {
+ let (title, detail) = match outcome {
+ Some(Ok(_)) => ("Signed in", "You can close this tab and return to Jan."),
+ Some(Err(e)) => ("Sign-in failed", e.as_str()),
+ None => (
+ "Not found",
+ "This address is only used for the sign-in redirect.",
+ ),
+ };
+ let detail = escape_html(detail);
+ format!(
+ "<!doctype html><html><head><meta charset=\"utf-8\"><title>Jan - {title}</title></head>\
+ <body style=\"font-family:system-ui,sans-serif;margin:4rem auto;max-width:32rem\">\
+ <h1>{title}</h1><p>{detail}</p></body></html>"
+ )
+}
+
+/// The failure detail embeds `error`/`error_description` straight from the
+/// redirect query, so it is provider-controlled text going into markup.
+fn escape_html(text: &str) -> String {
+ let mut out = String::with_capacity(text.len());
+ for c in text.chars() {
+ match c {
+ '&' => out.push_str("&amp;"),
+ '<' => out.push_str("&lt;"),
+ '>' => out.push_str("&gt;"),
+ '"' => out.push_str("&quot;"),
+ '\'' => out.push_str("&#39;"),
+ _ => out.push(c),
+ }
+ }
+ out
+}
+
+/// Build a transport client that carries this server's bearer token, refreshing
+/// it first when it has expired.
+///
+/// `Ok(None)` means "no OAuth here": either nothing is stored, or the user
+/// configured their own `Authorization` header, in which case the plain client
+/// already carries it and wrapping it would put two credentials on one request.
+/// The caller connects with its unwrapped client in that case.
+pub async fn authorized_client(
+ data_folder: &Path,
+ name: &str,
+ url: &str,
+ config: &Value,
+ base: reqwest::Client,
+) -> Result<Option<AuthClient<reqwest::Client>>, String> {
+ if has_static_authorization(config) {
+ return Ok(None);
+ }
+ let Some(stored) = load(data_folder, name) else {
+ return Ok(None);
+ };
+ if stored.resource != url {
+ return Err(format!(
+ "stored credentials for '{name}' were issued for {} - re-authenticate from /mcp",
+ stored.resource
+ ));
+ }
+
+ let mut state = OAuthState::new(url.to_string(), Some(base.clone()))
+ .await
+ .map_err(|e| format!("could not prepare OAuth for '{name}': {e}"))?;
+ state
+ .set_credentials(&stored.client_id, stored.tokens.clone())
+ .await
+ .map_err(|e| format!("stored credentials for '{name}' are unusable: {e}"))?;
+
+ if stored.is_expired() {
+ if !stored.has_refresh_token() {
+ return Err(format!(
+ "the access token for '{name}' expired and there is no refresh token - re-authenticate from /mcp"
+ ));
+ }
+ state.refresh_token().await.map_err(|e| {
+ format!(
+ "could not refresh the access token for '{name}': {e} - re-authenticate from /mcp"
+ )
+ })?;
+ let (client_id, tokens) = state
+ .get_credentials()
+ .await
+ .map_err(|e| format!("refresh for '{name}' returned no tokens: {e}"))?;
+ if let Some(tokens) = tokens {
+ save(
+ data_folder,
+ name,
+ &StoredCredentials::from_exchange(client_id, tokens, url.to_string()),
+ )?;
+ }
+ }
+
+ let manager = state
+ .into_authorization_manager()
+ .ok_or_else(|| format!("OAuth for '{name}' did not reach an authorized state"))?;
+ Ok(Some(AuthClient::new(base, manager)))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use oauth2::{AccessToken, EmptyExtraTokenFields, RefreshToken, TokenResponse};
+ use serde_json::json;
+
+ fn tokens(expires_in: Option<u64>, refresh: bool) -> OAuthTokenResponse {
+ let mut t = OAuthTokenResponse::new(
+ AccessToken::new("at-1".to_string()),
+ oauth2::basic::BasicTokenType::Bearer,
+ EmptyExtraTokenFields {},
+ );
+ if let Some(secs) = expires_in {
+ t.set_expires_in(Some(&Duration::from_secs(secs)));
+ }
+ if refresh {
+ t.set_refresh_token(Some(RefreshToken::new("rt-1".to_string())));
+ }
+ t
+ }
+
+ /// The message from a `parse_callback_query` outcome that must be an error.
+ fn err_of(outcome: Option<Result<Callback, String>>) -> String {
+ match outcome {
+ Some(Err(e)) => e,
+ _ => panic!("expected a rejected callback"),
+ }
+ }
+
+ fn creds(expires_in: Option<u64>, refresh: bool, resource: &str) -> StoredCredentials {
+ StoredCredentials::from_exchange(
+ "client-1".to_string(),
+ tokens(expires_in, refresh),
+ resource.to_string(),
+ )
+ }
+
+ #[test]
+ fn store_round_trips_and_clears() {
+ let dir = tempfile::tempdir().unwrap();
+ let c = creds(Some(3600), true, "https://x/mcp");
+
+ assert!(load(dir.path(), "srv").is_none());
+ save(dir.path(), "srv", &c).unwrap();
+
+ let back = load(dir.path(), "srv").expect("stored");
+ assert_eq!(back.client_id, "client-1");
+ assert_eq!(back.tokens.access_token().secret(), "at-1");
+ assert_eq!(back.resource, "https://x/mcp");
+
+ assert!(clear(dir.path(), "srv").unwrap());
+ assert!(load(dir.path(), "srv").is_none());
+ // Nothing to clear is reported, not an error.
+ assert!(!clear(dir.path(), "srv").unwrap());
+ }
+
+ #[test]
+ fn saving_one_server_leaves_the_others_alone() {
+ let dir = tempfile::tempdir().unwrap();
+ save(dir.path(), "a", &creds(Some(60), false, "https://a")).unwrap();
+ save(dir.path(), "b", &creds(Some(60), false, "https://b")).unwrap();
+
+ clear(dir.path(), "a").unwrap();
+ assert!(load(dir.path(), "a").is_none());
+ assert_eq!(load(dir.path(), "b").unwrap().resource, "https://b");
+ }
+
+ #[cfg(unix)]
+ #[test]
+ fn the_token_store_is_owner_only() {
+ use std::os::unix::fs::PermissionsExt;
+ let dir = tempfile::tempdir().unwrap();
+ save(dir.path(), "srv", &creds(Some(60), false, "https://x")).unwrap();
+ let mode = std::fs::metadata(store_path(dir.path()))
+ .unwrap()
+ .permissions()
+ .mode();
+ assert_eq!(mode & 0o777, 0o600);
+ }
+
+ #[test]
+ fn expiry_uses_the_clock_not_the_original_lifetime() {
+ // The window rmcp's own check misses: a token whose `expires_in` still
+ // reads 3600s but whose absolute deadline has passed.
+ let mut c = creds(Some(3600), true, "https://x");
+ assert!(!c.is_expired());
+ c.expires_at = Some(now_secs());
+ assert!(c.is_expired());
+ // Inside the refresh skew counts as expired.
+ c.expires_at = Some(now_secs() + EXPIRY_SKEW.as_secs() / 2);
+ assert!(c.is_expired());
+ // A response with no `expires_in` never expires on its own.
+ c.expires_at = None;
+ assert!(!c.is_expired());
+ }
+
+ #[test]
+ fn status_reports_each_case() {
+ let dir = tempfile::tempdir().unwrap();
+ let http = json!({ "type": "http", "url": "https://x/mcp" });
+
+ assert_eq!(
+ status(dir.path(), "s", &json!({ "command": "npx", "args": [] })),
+ AuthStatus::NotApplicable
+ );
+ assert_eq!(status(dir.path(), "s", &http), AuthStatus::Unauthenticated);
+
+ assert_eq!(
+ status(
+ dir.path(),
+ "s",
+ &json!({
+ "type": "http",
+ "url": "https://x/mcp",
+ "headers": { "authorization": "Bearer hand-written" }
+ })
+ ),
+ AuthStatus::StaticHeader
+ );
+
+ save(dir.path(), "s", &creds(Some(3600), true, "https://x/mcp")).unwrap();
+ assert!(matches!(
+ status(dir.path(), "s", &http),
+ AuthStatus::Authenticated { .. }
+ ));
+
+ // Tokens issued for a url the server no longer points at.
+ assert_eq!(
+ status(
+ dir.path(),
+ "s",
+ &json!({ "type": "http", "url": "https://moved/mcp" })
+ ),
+ AuthStatus::StaleResource
+ );
+
+ save(dir.path(), "s", &creds(Some(0), true, "https://x/mcp")).unwrap();
+ assert!(matches!(
+ status(dir.path(), "s", &http),
+ AuthStatus::Expired {
+ renewable: true,
+ expires_at: Some(_)
+ }
+ ));
+ save(dir.path(), "s", &creds(Some(0), false, "https://x/mcp")).unwrap();
+ assert!(matches!(
+ status(dir.path(), "s", &http),
+ AuthStatus::Expired {
+ renewable: false,
+ expires_at: Some(_)
+ }
+ ));
+ }
+
+ #[test]
+ fn an_empty_static_header_is_not_a_credential() {
+ // A user who cleared the value out of the form still wants OAuth.
+ assert!(!has_static_authorization(
+ &json!({ "headers": { "Authorization": " " } })
+ ));
+ assert!(has_static_authorization(
+ &json!({ "headers": { "Authorization": "Bearer t" } })
+ ));
+ }
+
+ #[test]
+ fn a_static_header_short_circuits_the_authorized_client() {
+ let dir = tempfile::tempdir().unwrap();
+ save(dir.path(), "s", &creds(Some(3600), true, "https://x/mcp")).unwrap();
+ let config = json!({
+ "type": "http",
+ "url": "https://x/mcp",
+ "headers": { "Authorization": "Bearer hand-written" }
+ });
+ // No network: a static header is answered before discovery is attempted.
+ let got = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(authorized_client(
+ dir.path(),
+ "s",
+ "https://x/mcp",
+ &config,
+ reqwest::Client::new(),
+ ));
+ assert!(matches!(got, Ok(None)));
+ }
+
+ #[test]
+ fn a_url_change_refuses_the_stored_token_instead_of_sending_it() {
+ let dir = tempfile::tempdir().unwrap();
+ save(dir.path(), "s", &creds(Some(3600), true, "https://old/mcp")).unwrap();
+ let config = json!({ "type": "http", "url": "https://new/mcp" });
+ let got = tokio::runtime::Builder::new_current_thread()
+ .enable_all()
+ .build()
+ .unwrap()
+ .block_on(authorized_client(
+ dir.path(),
+ "s",
+ "https://new/mcp",
+ &config,
+ reqwest::Client::new(),
+ ));
+ let err = got.expect_err("stale resource is an error, not a silent skip");
+ assert!(err.contains("https://old/mcp"), "{err}");
+ }
+
+ #[test]
+ fn callback_query_parsing() {
+ let ok = parse_callback_query("code=abc&state=xyz").unwrap().unwrap();
+ assert_eq!(ok.code, "abc");
+ assert_eq!(ok.state, "xyz");
+
+ // Percent-encoding is decoded, not passed through.
+ let enc = parse_callback_query("code=a%2Bb&state=s%2F1")
+ .unwrap()
+ .unwrap();
+ assert_eq!(enc.code, "a+b");
+ assert_eq!(enc.state, "s/1");
+
+ // An unrelated request is not the redirect: keep waiting.
+ assert!(parse_callback_query("").is_none());
+ assert!(parse_callback_query("favicon=1").is_none());
+
+ // `Callback` deliberately has no `Debug` (it holds an authorization
+ // code), so the error cases are matched rather than `unwrap_err`'d.
+ let denied = err_of(parse_callback_query(
+ "error=access_denied&error_description=nope&state=xyz",
+ ));
+ assert!(denied.contains("access_denied"), "{denied}");
+ assert!(denied.contains("nope"), "{denied}");
+
+ let no_state = err_of(parse_callback_query("code=abc"));
+ assert!(no_state.contains("state"), "{no_state}");
+
+ // An unverifiable error must not kill a sign-in that is still in
+ // flight: any request can reach the open loopback port.
+ assert!(parse_callback_query("error=access_denied").is_none());
+ }
+
+ #[test]
+ fn the_callback_page_escapes_provider_text() {
+ let outcome = parse_callback_query(
+ "error=bad&error_description=%3Cimg%20src%3Dx%20onerror%3Dalert(1)%3E&state=s",
+ );
+ let page = callback_page(&outcome);
+ assert!(!page.contains("<img"), "{page}");
+ assert!(page.contains("&lt;img"), "{page}");
+ }
+
+ /// The redirect is answered and the code extracted over a real socket, so
+ /// the keep-alive select in `accept_callback` is exercised rather than
+ /// assumed.
+ #[test]
+ fn the_loopback_listener_answers_the_redirect_and_yields_the_code() {
+ let rt = tokio::runtime::Builder::new_multi_thread()
+ .worker_threads(2)
+ .enable_all()
+ .build()
+ .unwrap();
+ rt.block_on(async {
+ let listener =
+ tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
+ .await
+ .unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let waiter = tokio::spawn(async move { accept_callback(&listener).await });
+
+ let client = reqwest::Client::new();
+ // A probe that is not the redirect must not end the wait.
+ let probe = client
+ .get(format!("http://127.0.0.1:{port}/favicon.ico"))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(probe.status(), 404);
+
+ let hit = client
+ .get(format!("http://127.0.0.1:{port}/callback?code=c1&state=s1"))
+ .send()
+ .await
+ .unwrap();
+ assert_eq!(hit.status(), 200);
+ assert!(hit.text().await.unwrap().contains("Signed in"));
+
+ let got = waiter.await.unwrap().unwrap();
+ assert_eq!(got.code, "c1");
+ assert_eq!(got.state, "s1");
+ });
+ }
+}
diff --git a/src-tauri/src/core/state.rs b/src-tauri/src/core/state.rs
index 292fd3d11..22c4ecabd 100644
--- a/src-tauri/src/core/state.rs
+++ b/src-tauri/src/core/state.rs
@@ -94,6 +94,15 @@ impl RunningServiceEnum {
Self::WithInit(s) => s.call_tool(params).await,
}
}
+
+ /// The `initialize` response: what the server said it implements. Read by
+ /// the `/mcp` detail screen for its capabilities and version lines.
+ pub fn peer_info(&self) -> Option<rmcp::model::InitializeResult> {
+ match self {
+ Self::NoInit(s) => s.peer_info().cloned(),
+ Self::WithInit(s) => s.peer_info().cloned(),
+ }
+ }
}
/// Shared desktop application state owned by Tauri. The CLI builds its
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 12f06f2bc..65d9cb6d4 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -121,6 +121,9 @@ macro_rules! invoke_commands_with_extras {
core::mcp::commands::get_mcp_configs,
core::mcp::commands::activate_mcp_server,
core::mcp::commands::deactivate_mcp_server,
+ core::mcp::commands::get_mcp_auth_status,
+ core::mcp::commands::authorize_mcp_server,
+ core::mcp::commands::clear_mcp_auth,
core::mcp::commands::check_jan_browser_extension_connected,
// Threads
core::threads::commands::list_threads,
diff --git a/web-app/src/containers/McpServerAuth.tsx b/web-app/src/containers/McpServerAuth.tsx
new file mode 100644
index 000000000..ddb22ad6a
--- /dev/null
+++ b/web-app/src/containers/McpServerAuth.tsx
@@ -0,0 +1,122 @@
+import { Button } from '@/components/ui/button'
+import { useTranslation } from '@/i18n/react-i18next-compat'
+import { cn } from '@/lib/utils'
+import type { MCPAuthStatus } from '@/services/mcp/types'
+
+/**
+ * The `Auth:` line for one remote MCP server in the settings list: a badge for
+ * the state plus the actions that state allows.
+ *
+ * Renders nothing for `notApplicable` (a stdio server has no HTTP transport to
+ * authorize). A `staticHeader` server *is* shown, as a badge with no actions:
+ * the user configured their own credential and needs to see that it is what is
+ * being used, but replacing it with OAuth would break it.
+ */
+interface McpServerAuthProps {
+ status: MCPAuthStatus | undefined
+ authorizing: boolean
+ /** Consent url, while a flow is pending, for when the browser did not open. */
+ consentUrl?: string
+ onAuthorize: () => void
+ onClearAuth: () => void
+}
+
+/** Badge tint per state: green means usable, amber needs attention, red is absent. */
+const TONE: Record<MCPAuthStatus['state'], string> = {
+ notApplicable: 'text-muted-foreground bg-secondary',
+ staticHeader: 'text-green-700 dark:text-green-500 bg-secondary',
+ authenticated: 'text-green-700 dark:text-green-500 bg-secondary',
+ expired: 'text-amber-700 dark:text-amber-500 bg-secondary',
+ staleResource: 'text-amber-700 dark:text-amber-500 bg-secondary',
+ unauthenticated: 'text-red-700 dark:text-red-500 bg-secondary',
+}
+
+/** A coarse "42m" / "3h" distance from now; the exact second is never useful. */
+function spanLabel(seconds: number): string {
+ const left = Math.max(0, seconds)
+ if (left < 3600) return `${Math.max(1, Math.floor(left / 60))}m`
+ if (left < 86400) return `${Math.floor(left / 3600)}h`
+ return `${Math.floor(left / 86400)}d`
+}
+
+function secondsFromNow(unixSeconds: number): number {
+ return unixSeconds - Math.floor(Date.now() / 1000)
+}
+
+export function McpServerAuth({
+ status,
+ authorizing,
+ consentUrl,
+ onAuthorize,
+ onClearAuth,
+}: McpServerAuthProps) {
+ const { t } = useTranslation()
+
+ if (!status || status.state === 'notApplicable') return null
+
+ return (
+ <div className="mt-2 flex flex-wrap items-center gap-2">
+ <span className="text-muted-foreground">{t('mcp-servers:auth.label')}</span>
+ <span
+ className={cn(
+ 'rounded-sm border px-2 py-0.5 text-xs',
+ TONE[status.state]
+ )}
+ >
+ {t(`mcp-servers:auth.state.${status.state}`)}
+ </span>
+ {status.expiresAt !== null && (
+ <span className="text-xs text-muted-foreground">
+ {status.state === 'expired'
+ ? t('mcp-servers:auth.expiredAgo', {
+ duration: spanLabel(-secondsFromNow(status.expiresAt)),
+ })
+ : t('mcp-servers:auth.expiresIn', {
+ duration: spanLabel(secondsFromNow(status.expiresAt)),
+ })}
+ </span>
+ )}
+
+ {status.canAuthenticate && (
+ <Button
+ size="sm"
+ variant="link"
+ className="h-auto p-0"
+ disabled={authorizing}
+ onClick={onAuthorize}
+ >
+ {authorizing
+ ? t('mcp-servers:auth.waiting')
+ : status.renewable
+ ? t('mcp-servers:auth.renew')
+ : status.hasCredentials
+ ? t('mcp-servers:auth.reauthenticate')
+ : t('mcp-servers:auth.authenticate')}
+ </Button>
+ )}
+ {status.hasCredentials && !authorizing && (
+ <Button
+ size="sm"
+ variant="link"
+ className="h-auto p-0"
+ onClick={onClearAuth}
+ >
+ {t('mcp-servers:auth.clear')}
+ </Button>
+ )}
+
+ {/* The flow is already waiting on the redirect by the time this shows, so
+ a browser that failed to launch is still recoverable by hand. */}
+ {authorizing && consentUrl && (
+ <a
+ href={consentUrl}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-xs text-blue-500 hover:underline"
+ >
+ {t('mcp-servers:auth.openSignInPage')}
+ </a>
+ )}
+ </div>
+ )
+}
diff --git a/web-app/src/hooks/__tests__/useMcpAuth.test.ts b/web-app/src/hooks/__tests__/useMcpAuth.test.ts
new file mode 100644
index 000000000..f150cc6b8
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useMcpAuth.test.ts
@@ -0,0 +1,159 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+import { act, renderHook, waitFor } from '@testing-library/react'
+import { needsAuthDetail, useMcpAuth } from '../useMcpAuth'
+import type { MCPAuthStatus } from '@/services/mcp/types'
+
+const listeners: Array<(event: { payload: unknown }) => void> = []
+const unlisten = vi.fn()
+
+vi.mock('@tauri-apps/api/event', () => ({
+ listen: vi.fn((_event: string, cb: (e: { payload: unknown }) => void) => {
+ listeners.push(cb)
+ return Promise.resolve(unlisten)
+ }),
+}))
+
+const mcp = {
+ getMCPAuthStatus: vi.fn(),
+ authorizeMCPServer: vi.fn(),
+ clearMCPAuth: vi.fn(),
+}
+
+vi.mock('@/hooks/useServiceHub', () => ({
+ getServiceHub: () => ({ mcp: () => mcp }),
+}))
+
+const status = (over: Partial<MCPAuthStatus> = {}): MCPAuthStatus => ({
+ state: 'unauthenticated',
+ canAuthenticate: true,
+ hasCredentials: false,
+ expiresAt: null,
+ ...over,
+})
+
+describe('needsAuthDetail', () => {
+ it('splits the backend marker off an activation error', () => {
+ expect(needsAuthDetail('NEEDS_AUTH: no credentials are stored')).toBe(
+ 'no credentials are stored'
+ )
+ expect(needsAuthDetail(new Error('NEEDS_AUTH: expired'))).toBe('expired')
+ expect(needsAuthDetail({ message: 'NEEDS_AUTH: stale' })).toBe('stale')
+ })
+
+ it('leaves an ordinary failure alone', () => {
+ // The whole point of the marker: a broken server must not be reported as
+ // one that needs signing in.
+ expect(needsAuthDetail('Failed to connect to server: ECONNREFUSED')).toBeNull()
+ expect(needsAuthDetail(undefined)).toBeNull()
+ expect(needsAuthDetail({})).toBeNull()
+ })
+})
+
+describe('useMcpAuth', () => {
+ beforeEach(() => {
+ listeners.length = 0
+ vi.clearAllMocks()
+ mcp.getMCPAuthStatus.mockResolvedValue(status())
+ })
+
+ it('reads a status per server on mount', async () => {
+ const { result } = renderHook(() => useMcpAuth(['a', 'b']))
+
+ await waitFor(() => {
+ expect(Object.keys(result.current.statuses)).toEqual(['a', 'b'])
+ })
+ expect(mcp.getMCPAuthStatus).toHaveBeenCalledWith('a')
+ expect(mcp.getMCPAuthStatus).toHaveBeenCalledWith('b')
+ })
+
+ /// A new array identity on every render must not re-run the read loop.
+ it('does not refetch when the same names arrive in a new array', async () => {
+ const { result, rerender } = renderHook(({ names }) => useMcpAuth(names), {
+ initialProps: { names: ['a'] },
+ })
+ await waitFor(() => expect(result.current.statuses.a).toBeDefined())
+ const callsAfterMount = mcp.getMCPAuthStatus.mock.calls.length
+
+ rerender({ names: ['a'] })
+ await waitFor(() =>
+ expect(mcp.getMCPAuthStatus.mock.calls.length).toBe(callsAfterMount)
+ )
+
+ rerender({ names: ['a', 'b'] })
+ await waitFor(() => expect(result.current.statuses.b).toBeDefined())
+ })
+
+ it('drops a server whose status cannot be read instead of failing the batch', async () => {
+ mcp.getMCPAuthStatus.mockImplementation((name: string) =>
+ name === 'gone' ? Promise.reject(new Error('not found')) : Promise.resolve(status())
+ )
+ const { result } = renderHook(() => useMcpAuth(['ok', 'gone']))
+
+ await waitFor(() => expect(result.current.statuses.ok).toBeDefined())
+ expect(result.current.statuses.gone).toBeUndefined()
+ })
+
+ it('marks a server as authorizing for the duration and refreshes after', async () => {
+ let release: () => void = () => {}
+ mcp.authorizeMCPServer.mockReturnValue(
+ new Promise<void>((resolve) => {
+ release = resolve
+ })
+ )
+ const { result } = renderHook(() => useMcpAuth(['a']))
+ await waitFor(() => expect(result.current.statuses.a).toBeDefined())
+
+ let pending!: Promise<void>
+ act(() => {
+ pending = result.current.authorize('a')
+ })
+ await waitFor(() => expect(result.current.authorizing.a).toBe(true))
+
+ mcp.getMCPAuthStatus.mockResolvedValue(
+ status({ state: 'authenticated', hasCredentials: true })
+ )
+ await act(async () => {
+ release()
+ await pending
+ })
+
+ expect(result.current.authorizing.a).toBe(false)
+ expect(result.current.statuses.a.state).toBe('authenticated')
+ })
+
+ it('clears the authorizing flag and refreshes even when the flow fails', async () => {
+ mcp.authorizeMCPServer.mockRejectedValue(new Error('denied'))
+ const { result } = renderHook(() => useMcpAuth(['a']))
+ await waitFor(() => expect(result.current.statuses.a).toBeDefined())
+
+ await act(async () => {
+ await expect(result.current.authorize('a')).rejects.toThrow('denied')
+ })
+ expect(result.current.authorizing.a).toBe(false)
+ })
+
+ it('captures the consent url from the backend event', async () => {
+ const { result } = renderHook(() => useMcpAuth(['a']))
+ await waitFor(() => expect(listeners.length).toBeGreaterThan(0))
+
+ act(() => {
+ listeners.forEach((cb) =>
+ cb({ payload: { server: 'a', url: 'https://idp/authorize?x=1' } })
+ )
+ })
+ expect(result.current.consentUrls.a).toBe('https://idp/authorize?x=1')
+ })
+
+ it('reports whether clearing found anything, and refreshes', async () => {
+ mcp.clearMCPAuth.mockResolvedValue(true)
+ const { result } = renderHook(() => useMcpAuth(['a']))
+ await waitFor(() => expect(result.current.statuses.a).toBeDefined())
+
+ let cleared!: boolean
+ await act(async () => {
+ cleared = await result.current.clearAuth('a')
+ })
+ expect(cleared).toBe(true)
+ expect(mcp.clearMCPAuth).toHaveBeenCalledWith('a')
+ })
+})
diff --git a/web-app/src/hooks/useMcpAuth.ts b/web-app/src/hooks/useMcpAuth.ts
new file mode 100644
index 000000000..c2705f505
--- /dev/null
+++ b/web-app/src/hooks/useMcpAuth.ts
@@ -0,0 +1,123 @@
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { listen } from '@tauri-apps/api/event'
+import { getServiceHub } from '@/hooks/useServiceHub'
+import type { MCPAuthStatus } from '@/services/mcp/types'
+
+/**
+ * Marker the backend prefixes onto an activation error the user fixes by
+ * signing in. Kept in sync with `core::mcp::oauth::NEEDS_AUTH_PREFIX`.
+ */
+const NEEDS_AUTH_PREFIX = 'NEEDS_AUTH: '
+
+/**
+ * Whether a failed activation is an authorization problem rather than a broken
+ * server, and the detail behind it. The backend tags it explicitly instead of
+ * leaving the UI to pattern-match "401" out of a transport error.
+ */
+export function needsAuthDetail(error: unknown): string | null {
+ const message =
+ typeof error === 'string'
+ ? error
+ : error instanceof Error
+ ? error.message
+ : typeof (error as { message?: unknown })?.message === 'string'
+ ? ((error as { message: string }).message)
+ : ''
+ return message.startsWith(NEEDS_AUTH_PREFIX)
+ ? message.slice(NEEDS_AUTH_PREFIX.length)
+ : null
+}
+
+type AuthStatuses = Record<string, MCPAuthStatus>
+
+/**
+ * Per-server OAuth state for the MCP settings screen, plus the two actions that
+ * change it.
+ *
+ * `refresh` is cheap by design -- `getMCPAuthStatus` is a local read on the Rust
+ * side (config plus the token store, no network), so refreshing every row after
+ * any change costs nothing and keeps the badges from going stale.
+ */
+export function useMcpAuth(serverNames: string[]) {
+ const [statuses, setStatuses] = useState<AuthStatuses>({})
+ const [authorizing, setAuthorizing] = useState<Record<string, boolean>>({})
+ /** Consent url per server, so a browser that never opened is still reachable. */
+ const [consentUrls, setConsentUrls] = useState<Record<string, string>>({})
+
+ // The names are re-derived from an object on every render of the settings
+ // page, so a new array identity each time would re-run the effect forever.
+ // The joined key is what actually changed.
+ const namesKey = serverNames.join('\u0000')
+ const namesRef = useRef(serverNames)
+ namesRef.current = serverNames
+
+ const refresh = useCallback(async () => {
+ const names = namesRef.current
+ const entries = await Promise.all(
+ names.map(async (name) => {
+ try {
+ return [name, await getServiceHub().mcp().getMCPAuthStatus(name)] as const
+ } catch (error) {
+ // A server deleted between render and read is not an error worth
+ // surfacing; it simply has no auth state.
+ console.debug(`Could not read MCP auth status for ${name}:`, error)
+ return null
+ }
+ })
+ )
+ setStatuses(Object.fromEntries(entries.filter((e) => e !== null)))
+ }, [])
+
+ useEffect(() => {
+ void refresh()
+ }, [namesKey, refresh])
+
+ // The backend emits the consent url before it starts waiting on the redirect,
+ // so the link is available for the whole time the flow is pending.
+ useEffect(() => {
+ const unlisten = listen<{ server: string; url: string }>(
+ 'mcp-oauth-url',
+ (event) => {
+ setConsentUrls((prev) => ({
+ ...prev,
+ [event.payload.server]: event.payload.url,
+ }))
+ }
+ )
+ return () => {
+ void unlisten.then((off) => off())
+ }
+ }, [])
+
+ const authorize = useCallback(
+ async (name: string) => {
+ setAuthorizing((prev) => ({ ...prev, [name]: true }))
+ try {
+ await getServiceHub().mcp().authorizeMCPServer(name)
+ } finally {
+ setAuthorizing((prev) => ({ ...prev, [name]: false }))
+ setConsentUrls((prev) => {
+ if (!(name in prev)) return prev
+ const rest = { ...prev }
+ delete rest[name]
+ return rest
+ })
+ await refresh()
+ }
+ },
+ [refresh]
+ )
+
+ const clearAuth = useCallback(
+ async (name: string) => {
+ try {
+ return await getServiceHub().mcp().clearMCPAuth(name)
+ } finally {
+ await refresh()
+ }
+ },
+ [refresh]
+ )
+
+ return { statuses, authorizing, consentUrls, refresh, authorize, clearAuth }
+}
diff --git a/web-app/src/locales/en/mcp-servers.json b/web-app/src/locales/en/mcp-servers.json
index f4cbae94b..b1fa37d23 100644
--- a/web-app/src/locales/en/mcp-servers.json
+++ b/web-app/src/locales/en/mcp-servers.json
@@ -69,5 +69,31 @@
"routerModelSearchPlaceholder": "Search models…",
"routerModelEmptyList": "No lightweight models available. Add a smaller model or configure API keys in Models.",
"routerModelEmptySearch": "No matches for “{{query}}”."
+ },
+ "auth": {
+ "label": "Auth:",
+ "state": {
+ "notApplicable": "not required",
+ "staticHeader": "Authorization header",
+ "authenticated": "authenticated",
+ "expired": "expired",
+ "staleResource": "issued for another URL",
+ "unauthenticated": "not authenticated"
+ },
+ "expiresIn": "expires in {{duration}}",
+ "authenticate": "Sign in",
+ "reauthenticate": "Re-authenticate",
+ "clear": "Clear authentication",
+ "waiting": "Waiting for browser...",
+ "openSignInPage": "Open the sign-in page",
+ "needsAuth": "{{serverName}} needs authentication",
+ "needsAuthHint": "Sign in to this server to connect.",
+ "authorized": "Signed in to {{serverName}}",
+ "authorizeFailed": "Sign-in for {{serverName}} failed",
+ "cleared": "Cleared stored credentials for {{serverName}}",
+ "nothingToClear": "{{serverName}} had no stored credentials",
+ "clearFailed": "Could not clear credentials for {{serverName}}",
+ "renew": "Renew session",
+ "expiredAgo": "expired {{duration}} ago"
}
}
diff --git a/web-app/src/routes/settings/mcp-servers.tsx b/web-app/src/routes/settings/mcp-servers.tsx
index 46a19953a..76f61db50 100644
--- a/web-app/src/routes/settings/mcp-servers.tsx
+++ b/web-app/src/routes/settings/mcp-servers.tsx
@@ -15,7 +15,7 @@ import {
MCPSettings,
DEFAULT_MCP_SETTINGS,
} from '@/hooks/useMCPServers'
-import { Fragment, useEffect, useState } from 'react'
+import { Fragment, useCallback, useEffect, useState } from 'react'
import AddEditMCPServer from '@/containers/dialogs/AddEditMCPServer'
import DeleteMCPServerConfirm from '@/containers/dialogs/DeleteMCPServerConfirm'
import EditJsonMCPserver from '@/containers/dialogs/EditJsonMCPserver'
@@ -35,6 +35,8 @@ import { useModelProvider } from '@/hooks/useModelProvider'
import { McpRouterModelPicker } from '@/containers/McpRouterModelPicker'
import { isRouterModelSelectable } from '@/lib/mcp-router-model-filter'
import { normalizeAppError } from '@/utils/appError'
+import { McpServerAuth } from '@/containers/McpServerAuth'
+import { useMcpAuth, needsAuthDetail } from '@/hooks/useMcpAuth'
// Function to mask sensitive URL parameters
@@ -138,6 +140,24 @@ function MCPServersDesktop() {
const [loadingServers, setLoadingServers] = useState<{
[key: string]: boolean
}>({})
+ const {
+ statuses: authStatuses,
+ authorizing,
+ consentUrls,
+ refresh: refreshAuth,
+ authorize,
+ clearAuth,
+ } = useMcpAuth(Object.keys(mcpServers))
+
+ const refreshConnectedServers = useCallback(() => {
+ serviceHub
+ .mcp()
+ .getConnectedServers()
+ .then(setConnectedServers)
+ .catch((error) =>
+ console.error('Failed to refresh connected MCP servers:', error)
+ )
+ }, [serviceHub])
const setErrorMessage = useAppState((state) => state.setErrorMessage)
const updateToolCallTimeout = (rawValue: string) => {
@@ -328,6 +348,58 @@ function MCPServersDesktop() {
}
}
+ /**
+ * Run the interactive sign-in, then bring the server up if it is enabled: a
+ * server that failed to connect for want of a token is still marked active,
+ * so authorizing without reconnecting would leave it down until toggled.
+ */
+ const handleAuthorize = async (serverKey: string) => {
+ try {
+ await authorize(serverKey)
+ toast.success(t('mcp-servers:auth.authorized', { serverName: serverKey }))
+ if (mcpServers[serverKey]?.active) {
+ toggleServer(serverKey, true)
+ }
+ } catch (error) {
+ setErrorMessage({
+ message: t('mcp-servers:auth.authorizeFailed', {
+ serverName: serverKey,
+ }),
+ subtitle: normalizeAppError(error),
+ })
+ }
+ }
+
+ /**
+ * Forget the tokens and drop the connection: the live transport still holds
+ * the old bearer token, so leaving it up would keep working against
+ * credentials the user just asked to forget.
+ *
+ * Disconnect only -- the server stays `active` in the config, so re-authorizing
+ * brings it back without the user having to re-enable it. Matches the CLI's
+ * `MCP_ACTION_CLEAR_AUTH`, which also clears and disconnects without touching
+ * the flag.
+ */
+ const handleClearAuth = async (serverKey: string) => {
+ try {
+ const cleared = await clearAuth(serverKey)
+ toast.success(
+ cleared
+ ? t('mcp-servers:auth.cleared', { serverName: serverKey })
+ : t('mcp-servers:auth.nothingToClear', { serverName: serverKey })
+ )
+ if (cleared && connectedServers.includes(serverKey)) {
+ await serviceHub.mcp().deactivateMCPServer(serverKey)
+ refreshConnectedServers()
+ }
+ } catch (error) {
+ setErrorMessage({
+ message: t('mcp-servers:auth.clearFailed', { serverName: serverKey }),
+ subtitle: normalizeAppError(error),
+ })
+ }
+ }
+
const toggleServer = (serverKey: string, active: boolean) => {
if (serverKey) {
setLoadingServers((prev) => ({ ...prev, [serverKey]: true }))
@@ -351,19 +423,27 @@ function MCPServersDesktop() {
? t('mcp-servers:serverStatusActive', { serverKey })
: t('mcp-servers:serverStatusInactive', { serverKey })
)
- serviceHub
- .mcp()
- .getConnectedServers()
- .then(setConnectedServers)
- .catch((error) =>
- console.error('Failed to refresh connected MCP servers:', error)
- )
+ refreshConnectedServers()
})
.catch((error) => {
editServer(serverKey, {
...(config ?? (mcpServers[serverKey] as MCPServerConfig)),
active: false,
})
+ // A server that only needs signing in is not a misconfigured one:
+ // the backend tags it, so point at the fix rather than telling the
+ // user to check parameters they got right.
+ const authDetail = needsAuthDetail(error)
+ if (authDetail !== null) {
+ void refreshAuth()
+ setErrorMessage({
+ message: t('mcp-servers:auth.needsAuth', {
+ serverName: serverKey,
+ }),
+ subtitle: t('mcp-servers:auth.needsAuthHint'),
+ })
+ return
+ }
setErrorMessage({
message: normalizeAppError(error),
subtitle: t('mcp-servers:checkParams'),
@@ -382,13 +462,7 @@ function MCPServersDesktop() {
.mcp()
.deactivateMCPServer(serverKey)
.finally(() => {
- serviceHub
- .mcp()
- .getConnectedServers()
- .then(setConnectedServers)
- .catch((error) =>
- console.error('Failed to refresh connected MCP servers:', error)
- )
+ refreshConnectedServers()
setLoadingServers((prev) => ({ ...prev, [serverKey]: false }))
})
}
@@ -396,24 +470,12 @@ function MCPServersDesktop() {
}
useEffect(() => {
- serviceHub
- .mcp()
- .getConnectedServers()
- .then(setConnectedServers)
- .catch((error) =>
- console.error('Failed to fetch connected MCP servers:', error)
- )
+ refreshConnectedServers()
let unlisten: (() => void) | undefined
const setupListener = async () => {
unlisten = await listen(SystemEvent.MCP_UPDATE, () => {
- serviceHub
- .mcp()
- .getConnectedServers()
- .then(setConnectedServers)
- .catch((error) =>
- console.error('Failed to refresh MCP servers:', error)
- )
+ refreshConnectedServers()
})
}
setupListener().catch((error) =>
@@ -423,7 +485,7 @@ function MCPServersDesktop() {
return () => {
unlisten?.()
}
- }, [serviceHub, setConnectedServers])
+ }, [refreshConnectedServers])
return (
<Fragment>
@@ -698,6 +760,13 @@ function MCPServersDesktop() {
{config.timeout && (
<div>Timeout: {config.timeout}s</div>
)}
+ <McpServerAuth
+ status={authStatuses[key]}
+ authorizing={!!authorizing[key]}
+ consentUrl={consentUrls[key]}
+ onAuthorize={() => void handleAuthorize(key)}
+ onClearAuth={() => void handleClearAuth(key)}
+ />
</>
)}
</div>
diff --git a/web-app/src/services/mcp/__tests__/default.test.ts b/web-app/src/services/mcp/__tests__/default.test.ts
index 3c12cd27f..c50211cc9 100644
--- a/web-app/src/services/mcp/__tests__/default.test.ts
+++ b/web-app/src/services/mcp/__tests__/default.test.ts
@@ -114,4 +114,20 @@ describe('DefaultMCPService', () => {
expect(result).toBe(false)
})
})
+
+ describe('OAuth', () => {
+ /// Without a backend there is no token store, so nothing may advertise a
+ /// sign-in button the build cannot honour.
+ it('reports notApplicable rather than offering a sign-in', async () => {
+ await expect(svc.getMCPAuthStatus('remote')).resolves.toEqual({
+ state: 'notApplicable',
+ canAuthenticate: false,
+ hasCredentials: false,
+ renewable: false,
+ expiresAt: null,
+ })
+ await expect(svc.authorizeMCPServer('remote')).resolves.toBeUndefined()
+ await expect(svc.clearMCPAuth('remote')).resolves.toBe(false)
+ })
+ })
})
diff --git a/web-app/src/services/mcp/__tests__/tauri.coverage.test.ts b/web-app/src/services/mcp/__tests__/tauri.coverage.test.ts
index 8d692069e..75ae22d30 100644
--- a/web-app/src/services/mcp/__tests__/tauri.coverage.test.ts
+++ b/web-app/src/services/mcp/__tests__/tauri.coverage.test.ts
@@ -195,4 +195,31 @@ describe('TauriMCPService – coverage', () => {
expect(result.mcpServers).toEqual({})
})
})
+
+ describe('OAuth', () => {
+ it('forwards each command with the server name', async () => {
+ const { invoke } = await import('@tauri-apps/api/core')
+ const status = {
+ state: 'unauthenticated',
+ canAuthenticate: true,
+ hasCredentials: false,
+ expiresAt: null,
+ }
+ vi.mocked(invoke).mockResolvedValueOnce(status)
+ await expect(svc.getMCPAuthStatus('remote')).resolves.toEqual(status)
+ expect(invoke).toHaveBeenCalledWith('get_mcp_auth_status', {
+ name: 'remote',
+ })
+
+ vi.mocked(invoke).mockResolvedValueOnce(undefined)
+ await svc.authorizeMCPServer('remote')
+ expect(invoke).toHaveBeenCalledWith('authorize_mcp_server', {
+ name: 'remote',
+ })
+
+ vi.mocked(invoke).mockResolvedValueOnce(true)
+ await expect(svc.clearMCPAuth('remote')).resolves.toBe(true)
+ expect(invoke).toHaveBeenCalledWith('clear_mcp_auth', { name: 'remote' })
+ })
+ })
})
diff --git a/web-app/src/services/mcp/default.ts b/web-app/src/services/mcp/default.ts
index eaea04116..8a053e0e0 100644
--- a/web-app/src/services/mcp/default.ts
+++ b/web-app/src/services/mcp/default.ts
@@ -4,7 +4,13 @@
import { MCPTool, MCPToolCallResult } from '@janhq/core'
import type { MCPServerConfig } from '@/hooks/useMCPServers'
-import type { MCPService, MCPConfig, ServerSummary, ToolCallWithCancellationResult } from './types'
+import type {
+ MCPService,
+ MCPConfig,
+ MCPAuthStatus,
+ ServerSummary,
+ ToolCallWithCancellationResult,
+} from './types'
export class DefaultMCPService implements MCPService {
async updateMCPConfig(configs: string): Promise<void> {
@@ -79,4 +85,30 @@ export class DefaultMCPService implements MCPService {
async checkJanBrowserExtensionConnected(): Promise<boolean> {
return false
}
+
+ /**
+ * Without a backend there is no token store, so every server reports
+ * `notApplicable` rather than `unauthenticated`: the latter would put a
+ * "sign in" button on a build that cannot run the flow.
+ */
+ async getMCPAuthStatus(name: string): Promise<MCPAuthStatus> {
+ void name
+ return {
+ state: 'notApplicable',
+ canAuthenticate: false,
+ hasCredentials: false,
+ renewable: false,
+ expiresAt: null,
+ }
+ }
+
+ async authorizeMCPServer(name: string): Promise<void> {
+ console.log('authorizeMCPServer called with name:', name)
+ // No-op - not implemented in default service
+ }
+
+ async clearMCPAuth(name: string): Promise<boolean> {
+ console.log('clearMCPAuth called with name:', name)
+ return false
+ }
}
diff --git a/web-app/src/services/mcp/tauri.ts b/web-app/src/services/mcp/tauri.ts
index bb52886e1..eae859134 100644
--- a/web-app/src/services/mcp/tauri.ts
+++ b/web-app/src/services/mcp/tauri.ts
@@ -6,7 +6,7 @@ import { invoke } from '@tauri-apps/api/core'
import { MCPTool } from '@/types/completion'
import { DEFAULT_MCP_SETTINGS } from '@/hooks/useMCPServers'
import type { MCPServerConfig, MCPServers, MCPSettings } from '@/hooks/useMCPServers'
-import type { MCPConfig, ServerSummary } from './types'
+import type { MCPAuthStatus, MCPConfig, ServerSummary } from './types'
import { DefaultMCPService } from './default'
export class TauriMCPService extends DefaultMCPService {
@@ -129,6 +129,18 @@ export class TauriMCPService extends DefaultMCPService {
async checkJanBrowserExtensionConnected(): Promise<boolean> {
return await invoke('check_jan_browser_extension_connected')
}
+
+ async getMCPAuthStatus(name: string): Promise<MCPAuthStatus> {
+ return await invoke('get_mcp_auth_status', { name })
+ }
+
+ async authorizeMCPServer(name: string): Promise<void> {
+ return await invoke('authorize_mcp_server', { name })
+ }
+
+ async clearMCPAuth(name: string): Promise<boolean> {
+ return await invoke('clear_mcp_auth', { name })
+ }
}
function isPlainObject(value: unknown): value is Record<string, unknown> {
diff --git a/web-app/src/services/mcp/types.ts b/web-app/src/services/mcp/types.ts
index 8d4020a00..11bfe2541 100644
--- a/web-app/src/services/mcp/types.ts
+++ b/web-app/src/services/mcp/types.ts
@@ -23,6 +23,33 @@ export interface ServerSummary {
description: string
}
+/**
+ * OAuth state of one remote MCP server, as reported by `get_mcp_auth_status`.
+ * Derived entirely on the Rust side so the UI never re-implements the rules
+ * (a hand-written `Authorization` header, for instance, means OAuth is neither
+ * offered nor reported as missing).
+ */
+export interface MCPAuthStatus {
+ state:
+ | 'notApplicable'
+ | 'staticHeader'
+ | 'authenticated'
+ | 'expired'
+ | 'staleResource'
+ | 'unauthenticated'
+ /** Whether an interactive sign-in is possible and would mean something. */
+ canAuthenticate: boolean
+ /** Whether there are stored tokens to forget. */
+ hasCredentials: boolean
+ /**
+ * Whether a stored refresh token can renew this without the browser. Only
+ * meaningful for `expired`; false everywhere else.
+ */
+ renewable: boolean
+ /** Unix seconds the access token expires at, when known. */
+ expiresAt: number | null
+}
+
export interface MCPService {
updateMCPConfig(configs: string): Promise<void>
restartMCPServers(): Promise<void>
@@ -46,4 +73,16 @@ export interface MCPService {
activateMCPServer(name: string, config: MCPServerConfig): Promise<void>
deactivateMCPServer(name: string): Promise<void>
checkJanBrowserExtensionConnected(): Promise<boolean>
+
+ // OAuth for remote (http/sse) servers
+ /** Local read, no network: safe to call per row. */
+ getMCPAuthStatus(name: string): Promise<MCPAuthStatus>
+ /**
+ * Run the full interactive authorization. Resolves only once the browser
+ * redirect has been exchanged for tokens, so expect this to be pending for as
+ * long as the user takes (the backend gives up after five minutes).
+ */
+ authorizeMCPServer(name: string): Promise<void>
+ /** Forget stored tokens. `false` when there were none. */
+ clearMCPAuth(name: string): Promise<boolean>
}