Skip to content

A self-improving RLM agent for coding workflows and long-running autonomous tasks.

Rust

add the serper key flow to mcp (#3230)

kte91b90c4ebb7
diff --git a/crates/pa-cli/src/mcp_login.rs b/crates/pa-cli/src/mcp_login.rs
index ebb509a319..1a5f20963c 100644
--- a/crates/pa-cli/src/mcp_login.rs
+++ b/crates/pa-cli/src/mcp_login.rs
@@ -1,19 +1,21 @@
//! The composition root's MCP auth flows behind the TUI's
-//! `/mcp login <name>` and `/mcp logout <name>`: resolve the server
-//! through the settings + builtin catalog, run the pa-core OAuth login
-//! against the inline auth panel (the authorization URL block and the
-//! paste fallbacks render in the TUI; the browser launch rides the
-//! request), and persist the endpoint-bound credential in the shared auth
-//! store. The TS interactive client runs the same flow in its own process
-//! (auth-flows.ts `runMcpLogin`) and reloads the session; this build
-//! surfaces the activation state instead (the skill gating resolves at
-//! session build).
+//! `/mcp login <name>` and `/mcp logout <name>` plus the `/mcp` view's
+//! api-key credential flow (`key <name>`): resolve the server through
+//! the settings + builtin catalog, run the pa-core OAuth login against
+//! the inline auth panel (the authorization URL block and the paste
+//! fallbacks render in the TUI; the browser launch rides the request),
+//! and persist the endpoint-bound credential in the shared auth store —
+//! the api-key credentials store their key in the auth slot the runtime
+//! reads (the web-search key). The TS interactive client runs the same
+//! flow in its own process (auth-flows.ts `runMcpLogin`) and reloads the
+//! session; this build surfaces the activation state instead (the skill
+//! gating resolves at session build).
use std::path::PathBuf;
use std::pin::Pin;
use anyhow::{anyhow, Context, Result};
-use pa_core::auth::AuthStorage;
+use pa_core::auth::{AuthCredential, AuthStorage};
use pa_core::mcp::{
McpLoginUi, McpManager, McpManagerOptions, McpServerConfig, OAuthHttp, ReqwestOAuthHttp,
};
@@ -170,6 +172,44 @@ impl TerminalMcpAuth {
}
}
+ /// The api-key credential flow (the `/mcp` view's key rows): prompt
+ /// for the ONE key the credential collects (the masked field never
+ /// renders the secret) and store it in the credential's auth slot —
+ /// the exact contract the runtime reads (auth.json's `serper` key,
+ /// the `AuthCredential::ApiKey` form).
+ async fn api_key_inner(
+ &self,
+ credential: &str,
+ panel: pa_tui::auth_panel::AuthPanelHandle,
+ ) -> Result<String> {
+ let label = pa_core::mcp::API_KEY_CREDENTIALS
+ .iter()
+ .find(|(id, _)| *id == credential)
+ .map(|(_, label)| *label)
+ .ok_or_else(|| anyhow!("{credential} is not a known api-key credential."))?;
+ let key = panel
+ .paste_prompt(
+ &format!("Paste the API key for {label}:"),
+ PastePromptTone::Text,
+ PasteStyle::Masked,
+ )
+ .await
+ .filter(|line| !line.is_empty())
+ .ok_or_else(|| anyhow!("Paste cancelled"))?;
+ let mut auth = AuthStorage::create(&self.agent_dir);
+ auth.set(
+ credential,
+ AuthCredential::ApiKey {
+ key,
+ prime_team: None,
+ },
+ );
+ if let Some(error) = auth.drain_errors().pop() {
+ return Err(anyhow!(error)).context("could not save the API key");
+ }
+ Ok(format!("Saved API key for {label}. Web search is ready."))
+ }
+
fn logout_inner(&self, server: &str) -> Result<String> {
let provider = format!("mcp:{server}");
let mut auth = AuthStorage::create(&self.agent_dir);
@@ -199,6 +239,11 @@ impl ClientAuthCommands for TerminalMcpAuth {
Box::pin(async move { auth.paste_inner(&server, panel).await })
}
+ fn api_key(&self, credential: &str, panel: pa_tui::auth_panel::AuthPanelHandle) -> AuthFuture {
+ let (auth, credential) = (self.clone(), credential.to_string());
+ Box::pin(async move { auth.api_key_inner(&credential, panel).await })
+ }
+
fn logout(&self, server: &str) -> AuthFuture {
let (auth, server) = (self.clone(), server.to_string());
Box::pin(async move { auth.logout_inner(&server) })
@@ -461,4 +506,77 @@ mod tests {
assert_eq!(status, "linear is not connected.");
Ok(())
}
+
+ #[tokio::test]
+ async fn the_api_key_flow_stores_the_exact_runtime_contract() -> Result<()> {
+ let dir = tempfile::tempdir()?;
+ let agent_dir = dir.path().join("agent");
+ std::fs::create_dir_all(&agent_dir)?;
+ let hook = TerminalMcpAuth::new(dir.path().to_path_buf(), agent_dir.clone());
+
+ // The flow prompts (masked) for the key, then stores it.
+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
+ let panel = pa_tui::auth_panel::AuthPanelHandle::new(tx);
+ let flow = tokio::spawn({
+ let hook = hook.clone();
+ let panel = panel.clone();
+ async move { hook.api_key_inner("serper", panel).await }
+ });
+ let request = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
+ .await
+ .expect("the paste request sends")
+ .expect("the channel stays open");
+ let pa_tui::auth_panel::AuthPanelRequest::PastePrompt { prompt, reply, .. } = request
+ else {
+ panic!("expected the paste request")
+ };
+ assert_eq!(prompt, "Paste the API key for Serper (web search):");
+ reply
+ .send(Some("the-serper-key".to_string()))
+ .expect("the reply lands");
+ assert_eq!(
+ flow.await.expect("the flow ran")?,
+ "Saved API key for Serper (web search). Web search is ready."
+ );
+
+ // The stored credential is the EXACT contract the websearch runtime
+ // reads: auth.json's `serper` slot, the `api_key` form.
+ let stored: serde_json::Value = serde_json::from_str(
+ &std::fs::read_to_string(agent_dir.join("auth.json")).expect("auth.json"),
+ )?;
+ assert_eq!(stored["serper"]["type"], "api_key");
+ assert_eq!(stored["serper"]["key"], "the-serper-key");
+
+ // An unknown credential keeps its wording.
+ let error = hook
+ .api_key_inner("nope", panel.clone())
+ .await
+ .unwrap_err()
+ .to_string();
+ assert_eq!(error, "nope is not a known api-key credential.");
+
+ // A cancelled prompt answers the cancel (the stored key stays).
+ let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
+ let panel = pa_tui::auth_panel::AuthPanelHandle::new(tx);
+ let flow = tokio::spawn({
+ let hook = hook.clone();
+ let panel = panel.clone();
+ async move { hook.api_key_inner("serper", panel).await }
+ });
+ let request = tokio::time::timeout(std::time::Duration::from_secs(2), rx.recv())
+ .await
+ .expect("the paste request sends")
+ .expect("the channel stays open");
+ let pa_tui::auth_panel::AuthPanelRequest::PastePrompt { reply, .. } = request else {
+ panic!("expected the paste request")
+ };
+ reply.send(None).expect("the cancel lands");
+ let error = flow.await.expect("the flow ran").unwrap_err().to_string();
+ assert_eq!(error, "Paste cancelled");
+ let stored: serde_json::Value = serde_json::from_str(
+ &std::fs::read_to_string(agent_dir.join("auth.json")).expect("auth.json"),
+ )?;
+ assert_eq!(stored["serper"]["key"], "the-serper-key");
+ Ok(())
+ }
}
diff --git a/crates/pa-cli/src/provider_login.rs b/crates/pa-cli/src/provider_login.rs
index 3eceeb6c60..84c7570ef4 100644
--- a/crates/pa-cli/src/provider_login.rs
+++ b/crates/pa-cli/src/provider_login.rs
@@ -10,7 +10,9 @@
use std::path::{Path, PathBuf};
-use pa_core::auth::{AuthCredential, AuthSource, AuthStatus};
+use pa_core::auth::{
+ AuthCredential, AuthSource, AuthStatus, SERPER_CREDENTIAL_ID, SERPER_CREDENTIAL_NAME,
+};
use pa_core::models::ModelRegistry;
use pa_tui::provider_auth::{
AuthFlow, AuthStatusIndicator, AuthStatusStyle, AuthType, ProviderAuthCommands,
@@ -70,8 +72,6 @@ const BUILT_IN_PROVIDER_DISPLAY_NAMES: &[(&str, &str)] = &[
];
const PRIME_INFERENCE_PROVIDER_ID: &str = "prime-inference";
-const SERPER_CREDENTIAL_ID: &str = "serper";
-const SERPER_CREDENTIAL_NAME: &str = "Serper (web search)";
/// The display name of a provider id (the TS map, else the id itself).
fn display_name(provider_id: &str) -> String {
@@ -240,9 +240,11 @@ impl ProviderAuth {
}
impl ProviderAuthCommands for ProviderAuth {
- /// TS `getLoginProviderOptions`: the subscription rows, the MCP
- /// OAuth integrations, the API-key model providers, and the web
- /// search credential, sorted TS-style with prime-inference first.
+ /// TS `getLoginProviderOptions`: the subscription rows and the
+ /// API-key model providers, sorted TS-style with prime-inference
+ /// first. The service rows (the MCP OAuth integrations, the
+ /// web-search credential) live on the `/mcp` view (the operator's
+ /// 2026-09-24 `/login`-is-providers-only directive).
fn login_options(&self) -> ProviderRowsFuture {
let provider = self.clone();
Box::pin(async move {
@@ -347,7 +349,10 @@ impl ProviderAuthCommands for ProviderAuth {
impl ProviderAuth {
/// The login row build (blocking: the auth store and MCP manager
- /// locks must stay off the async workers).
+ /// locks must stay off the async workers). The operator's 2026-09-24
+ /// directive keeps `/login` providers only: the service rows (the MCP
+ /// OAuth integrations, the web-search credential) live on the `/mcp`
+ /// view instead.
fn login_rows_blocking(self) -> Vec<ProviderRow> {
let provider = self;
{
@@ -739,271 +744,4 @@ fn logout_blocking(provider_row: &ProviderRow, agent_dir: &Path) -> ProviderAuth
}
#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn the_status_indicator_maps_the_ts_labels() {
- let stored_api_key = AuthCredential::ApiKey {
- key: "k".to_string(),
- prime_team: None,
- };
- // A matching stored credential is configured.
- assert_eq!(
- status_indicator(
- Some(&stored_api_key),
- &AuthStatus {
- source: Some(AuthSource::Stored),
- ..Default::default()
- },
- AuthType::ApiKey
- ),
- Some(AuthStatusIndicator {
- style: AuthStatusStyle::Success,
- label: "configured".to_string()
- })
- );
- // A subscription credential on an api-key row warns.
- assert_eq!(
- status_indicator(
- Some(&AuthCredential::Oauth {
- access: "a".to_string(),
- refresh: None,
- expires: 1,
- account_id: None,
- endpoint: None,
- token_endpoint: None,
- client_id: None,
- resource: None,
- issuer: None,
- enterprise_url: None,
- }),
- &AuthStatus::default(),
- AuthType::ApiKey
- ),
- Some(AuthStatusIndicator {
- style: AuthStatusStyle::Warning,
- label: "subscription configured".to_string()
- })
- );
- // An env key marks the api-key row configured.
- assert_eq!(
- status_indicator(
- None,
- &AuthStatus {
- source: Some(AuthSource::Environment),
- label: Some("OPENAI_API_KEY".to_string()),
- ..Default::default()
- },
- AuthType::ApiKey
- ),
- Some(AuthStatusIndicator {
- style: AuthStatusStyle::Success,
- label: "env: OPENAI_API_KEY".to_string()
- })
- );
- // An unconfigured subscription row stays muted.
- assert_eq!(
- status_indicator(None, &AuthStatus::default(), AuthType::Oauth),
- Some(AuthStatusIndicator {
- style: AuthStatusStyle::Muted,
- label: "unconfigured".to_string()
- })
- );
- // An unconfigured api-key row hides its meta (TS inline rule).
- assert_eq!(
- status_indicator(None, &AuthStatus::default(), AuthType::ApiKey),
- None
- );
- // A stale credential warns.
- assert_eq!(
- status_indicator(
- None,
- &AuthStatus {
- source: Some(AuthSource::Stale),
- label: Some("expired".to_string()),
- ..Default::default()
- },
- AuthType::Oauth
- ),
- Some(AuthStatusIndicator {
- style: AuthStatusStyle::Warning,
- label: "expired".to_string()
- })
- );
- }
-
- #[test]
- fn the_display_names_match_the_ts_map() {
- assert_eq!(display_name("openai"), "OpenAI");
- assert_eq!(display_name("google"), "Google Gemini");
- assert_eq!(display_name("prime-inference"), "Prime Inference");
- assert_eq!(display_name("a-custom-provider"), "a-custom-provider");
- }
-
- #[test]
- fn the_api_key_login_rule_matches_ts() {
- let mut built_in = std::collections::HashSet::new();
- built_in.insert("anthropic".to_string());
- // The display-name map marks api-key logins.
- assert!(is_api_key_login_provider("openai", &built_in));
- // A provider the built-in set does not know is a custom api-key
- // provider.
- assert!(is_api_key_login_provider("my-endpoint", &built_in));
- // A built-in provider without a display name is not an api-key
- // login (its subscription flows apply).
- assert!(!is_api_key_login_provider("faux", &{
- let mut set = std::collections::HashSet::new();
- set.insert("faux".to_string());
- set
- }));
- }
-
- #[tokio::test]
- async fn login_options_list_providers_only() {
- let dir = tempfile::tempdir().expect("temp dir");
- let agent = dir.path().join("agent");
- std::fs::create_dir_all(&agent).expect("agent dir");
- std::env::remove_var("PRIME_AGENT_TRACES_API_KEY");
- std::env::remove_var("PRIME_API_KEY");
- let auth = ProviderAuth::new(dir.path(), agent.clone());
- let rows = auth.login_options().await;
- // The TS OAuth registry rows render; every subscription flow is
- // ported, so every row selects (the flows answer through the
- // panel — never an after-selection error wall).
- for (id, name) in SUBSCRIPTION_PROVIDERS {
- let row = rows
- .iter()
- .find(|row| row.id == id && row.name == name)
- .unwrap_or_else(|| panic!("the {id} subscription row renders"));
- assert!(
- row.available,
- "the {id} row's flow is ported and selectable"
- );
- }
- // The operator's 2026-09-24 directive: /login is providers only —
- // the service rows (MCP OAuth integrations, the web search
- // credential) never appear; the /mcp view owns MCP logins.
- assert!(!rows.iter().any(|row| row.id == "serper"));
- assert!(!rows.iter().any(|row| row.id.starts_with("mcp:")));
- // Prime Inference sorts first among the api-key rows (TS rule).
- assert!(
- rows.iter()
- .position(|row| row.id == PRIME_INFERENCE_PROVIDER_ID)
- < rows.iter().position(|row| row.id == "anthropic"),
- "prime-inference sorts before the other api-key rows"
- );
- }
-
- /// Port of the TS #2645 warning detection: the ban-risk warning is
- /// reported exactly when the active Anthropic credential is the
- /// subscription (a stored OAuth login or an `sk-ant-oat` key), and
- /// its text names the risk.
- #[tokio::test]
- async fn the_anthropic_subscription_warning_matches_the_active_credential() {
- let dir = tempfile::tempdir().expect("temp dir");
- let agent = dir.path().join("agent");
- std::fs::create_dir_all(&agent).expect("agent dir");
- std::env::remove_var("ANTHROPIC_API_KEY");
- let auth = ProviderAuth::new(dir.path(), agent.clone());
-
- // No credential: no warning.
- assert_eq!(auth.anthropic_subscription_warning().await, None);
-
- // A plain API key: no warning (an API key avoids the risk).
- let mut storage = pa_core::auth::AuthStorage::create(&agent);
- storage.set(
- "anthropic",
- AuthCredential::ApiKey {
- key: "sk-ant-api03-plain".to_string(),
- prime_team: None,
- },
- );
- assert_eq!(auth.anthropic_subscription_warning().await, None);
-
- // A subscription token key (TS `isAnthropicSubscriptionAuthKey`).
- storage.set(
- "anthropic",
- AuthCredential::ApiKey {
- key: "sk-ant-oat-subscription".to_string(),
- prime_team: None,
- },
- );
- let warning = auth
- .anthropic_subscription_warning()
- .await
- .expect("a sk-ant-oat key is the subscription");
- assert!(warning.contains("identifies as Claude Code"));
- assert!(warning.contains("restricted or banned"));
- assert!(warning.contains("An Anthropic API key avoids the risk"));
-
- // A stored OAuth login is the subscription too.
- storage.set(
- "anthropic",
- AuthCredential::Oauth {
- access: "a".to_string(),
- refresh: None,
- expires: i64::MAX,
- endpoint: None,
- token_endpoint: None,
- client_id: None,
- resource: None,
- issuer: None,
- account_id: None,
- enterprise_url: None,
- },
- );
- assert!(auth.anthropic_subscription_warning().await.is_some());
-
- // An env subscription key resolves active with no stored credential.
- storage.remove("anthropic");
- std::env::set_var("ANTHROPIC_API_KEY", "sk-ant-oat-env");
- assert!(auth.anthropic_subscription_warning().await.is_some());
- std::env::remove_var("ANTHROPIC_API_KEY");
- }
-
- #[tokio::test]
- async fn login_stores_an_api_key_and_logout_removes_it() {
- let dir = tempfile::tempdir().expect("temp dir");
- let agent = dir.path().join("agent");
- std::fs::create_dir_all(&agent).expect("agent dir");
- let auth = ProviderAuth::new(dir.path(), agent);
- let row = ProviderRow {
- id: "openai".to_string(),
- name: "OpenAI".to_string(),
- auth_type: AuthType::ApiKey,
- status: None,
- flow: AuthFlow::ApiKeyPrompt,
- configured: false,
- available: true,
- };
- match auth.login(&row, Some("sk-test")).await {
- ProviderAuthOutcome::Status(message) => {
- assert!(
- message.starts_with("Saved API key for OpenAI. Credentials saved to "),
- "the store status names the credential path: {message}"
- );
- }
- other => panic!("expected the store status, got {other:?}"),
- }
- // An empty key answers the TS error.
- assert_eq!(
- auth.login(&row, Some("")).await,
- ProviderAuthOutcome::Error(
- "Failed to save API key for OpenAI: API key cannot be empty.".to_string()
- )
- );
- // The logout lists the stored credential and removes it.
- let stored = auth.logout_options().await;
- assert_eq!(stored.len(), 1);
- assert_eq!(stored[0].id, "openai");
- assert_eq!(
- auth.logout(&stored[0]).await,
- ProviderAuthOutcome::Status(
- "Removed stored API key for OpenAI. Environment variables and models.json config are unchanged."
- .to_string()
- )
- );
- assert!(auth.logout_options().await.is_empty());
- }
-}
+mod tests;
diff --git a/crates/pa-cli/src/provider_login/tests.rs b/crates/pa-cli/src/provider_login/tests.rs
new file mode 100644
index 0000000000..aeecb07bc8
--- /dev/null
+++ b/crates/pa-cli/src/provider_login/tests.rs
@@ -0,0 +1,313 @@
+//! The provider-login unit battery (moved beside its module at the
+//! 2026-09-30 file-size cap: the flows and their tests stay one tree).
+
+use super::*;
+
+#[test]
+fn the_status_indicator_maps_the_ts_labels() {
+ let stored_api_key = AuthCredential::ApiKey {
+ key: "k".to_string(),
+ prime_team: None,
+ };
+ // A matching stored credential is configured.
+ assert_eq!(
+ status_indicator(
+ Some(&stored_api_key),
+ &AuthStatus {
+ source: Some(AuthSource::Stored),
+ ..Default::default()
+ },
+ AuthType::ApiKey
+ ),
+ Some(AuthStatusIndicator {
+ style: AuthStatusStyle::Success,
+ label: "configured".to_string()
+ })
+ );
+ // A subscription credential on an api-key row warns.
+ assert_eq!(
+ status_indicator(
+ Some(&AuthCredential::Oauth {
+ access: "a".to_string(),
+ refresh: None,
+ expires: 1,
+ account_id: None,
+ endpoint: None,
+ token_endpoint: None,
+ client_id: None,
+ resource: None,
+ issuer: None,
+ enterprise_url: None,
+ }),
+ &AuthStatus::default(),
+ AuthType::ApiKey
+ ),
+ Some(AuthStatusIndicator {
+ style: AuthStatusStyle::Warning,
+ label: "subscription configured".to_string()
+ })
+ );
+ // An env key marks the api-key row configured.
+ assert_eq!(
+ status_indicator(
+ None,
+ &AuthStatus {
+ source: Some(AuthSource::Environment),
+ label: Some("OPENAI_API_KEY".to_string()),
+ ..Default::default()
+ },
+ AuthType::ApiKey
+ ),
+ Some(AuthStatusIndicator {
+ style: AuthStatusStyle::Success,
+ label: "env: OPENAI_API_KEY".to_string()
+ })
+ );
+ // An unconfigured subscription row stays muted.
+ assert_eq!(
+ status_indicator(None, &AuthStatus::default(), AuthType::Oauth),
+ Some(AuthStatusIndicator {
+ style: AuthStatusStyle::Muted,
+ label: "unconfigured".to_string()
+ })
+ );
+ // An unconfigured api-key row hides its meta (TS inline rule).
+ assert_eq!(
+ status_indicator(None, &AuthStatus::default(), AuthType::ApiKey),
+ None
+ );
+ // A stale credential warns.
+ assert_eq!(
+ status_indicator(
+ None,
+ &AuthStatus {
+ source: Some(AuthSource::Stale),
+ label: Some("expired".to_string()),
+ ..Default::default()
+ },
+ AuthType::Oauth
+ ),
+ Some(AuthStatusIndicator {
+ style: AuthStatusStyle::Warning,
+ label: "expired".to_string()
+ })
+ );
+}
+
+#[test]
+fn the_display_names_match_the_ts_map() {
+ assert_eq!(display_name("openai"), "OpenAI");
+ assert_eq!(display_name("google"), "Google Gemini");
+ assert_eq!(display_name("prime-inference"), "Prime Inference");
+ assert_eq!(display_name("a-custom-provider"), "a-custom-provider");
+}
+
+#[test]
+fn the_api_key_login_rule_matches_ts() {
+ let mut built_in = std::collections::HashSet::new();
+ built_in.insert("anthropic".to_string());
+ // The display-name map marks api-key logins.
+ assert!(is_api_key_login_provider("openai", &built_in));
+ // A provider the built-in set does not know is a custom api-key
+ // provider.
+ assert!(is_api_key_login_provider("my-endpoint", &built_in));
+ // A built-in provider without a display name is not an api-key
+ // login (its subscription flows apply).
+ assert!(!is_api_key_login_provider("faux", &{
+ let mut set = std::collections::HashSet::new();
+ set.insert("faux".to_string());
+ set
+ }));
+}
+
+#[tokio::test]
+async fn login_options_list_providers_only() {
+ let dir = tempfile::tempdir().expect("temp dir");
+ let agent = dir.path().join("agent");
+ std::fs::create_dir_all(&agent).expect("agent dir");
+ std::env::remove_var("PRIME_AGENT_TRACES_API_KEY");
+ std::env::remove_var("PRIME_API_KEY");
+ let auth = ProviderAuth::new(dir.path(), agent.clone());
+ let rows = auth.login_options().await;
+ // The TS OAuth registry rows render; every subscription flow is
+ // ported, so every row selects (the flows answer through the
+ // panel — never an after-selection error wall).
+ for (id, name) in SUBSCRIPTION_PROVIDERS {
+ let row = rows
+ .iter()
+ .find(|row| row.id == id && row.name == name)
+ .unwrap_or_else(|| panic!("the {id} subscription row renders"));
+ assert!(
+ row.available,
+ "the {id} row's flow is ported and selectable"
+ );
+ }
+ // The operator's 2026-09-24 directive: /login is providers only —
+ // the service rows (MCP OAuth integrations, the web search
+ // credential) never appear; the /mcp view owns MCP logins.
+ assert!(!rows.iter().any(|row| row.id == "serper"));
+ assert!(!rows.iter().any(|row| row.id.starts_with("mcp:")));
+ // Prime Inference sorts first among the api-key rows (TS rule).
+ assert!(
+ rows.iter()
+ .position(|row| row.id == PRIME_INFERENCE_PROVIDER_ID)
+ < rows.iter().position(|row| row.id == "anthropic"),
+ "prime-inference sorts before the other api-key rows"
+ );
+}
+
+/// Port of the TS #2645 warning detection: the ban-risk warning is
+/// reported exactly when the active Anthropic credential is the
+/// subscription (a stored OAuth login or an `sk-ant-oat` key), and
+/// its text names the risk.
+#[tokio::test]
+async fn the_anthropic_subscription_warning_matches_the_active_credential() {
+ let dir = tempfile::tempdir().expect("temp dir");
+ let agent = dir.path().join("agent");
+ std::fs::create_dir_all(&agent).expect("agent dir");
+ std::env::remove_var("ANTHROPIC_API_KEY");
+ let auth = ProviderAuth::new(dir.path(), agent.clone());
+
+ // No credential: no warning.
+ assert_eq!(auth.anthropic_subscription_warning().await, None);
+
+ // A plain API key: no warning (an API key avoids the risk).
+ let mut storage = pa_core::auth::AuthStorage::create(&agent);
+ storage.set(
+ "anthropic",
+ AuthCredential::ApiKey {
+ key: "sk-ant-api03-plain".to_string(),
+ prime_team: None,
+ },
+ );
+ assert_eq!(auth.anthropic_subscription_warning().await, None);
+
+ // A subscription token key (TS `isAnthropicSubscriptionAuthKey`).
+ storage.set(
+ "anthropic",
+ AuthCredential::ApiKey {
+ key: "sk-ant-oat-subscription".to_string(),
+ prime_team: None,
+ },
+ );
+ let warning = auth
+ .anthropic_subscription_warning()
+ .await
+ .expect("a sk-ant-oat key is the subscription");
+ assert!(warning.contains("identifies as Claude Code"));
+ assert!(warning.contains("restricted or banned"));
+ assert!(warning.contains("An Anthropic API key avoids the risk"));
+
+ // A stored OAuth login is the subscription too.
+ storage.set(
+ "anthropic",
+ AuthCredential::Oauth {
+ access: "a".to_string(),
+ refresh: None,
+ expires: i64::MAX,
+ endpoint: None,
+ token_endpoint: None,
+ client_id: None,
+ resource: None,
+ issuer: None,
+ account_id: None,
+ enterprise_url: None,
+ },
+ );
+ assert!(auth.anthropic_subscription_warning().await.is_some());
+
+ // An env subscription key resolves active with no stored credential.
+ storage.remove("anthropic");
+ std::env::set_var("ANTHROPIC_API_KEY", "sk-ant-oat-env");
+ assert!(auth.anthropic_subscription_warning().await.is_some());
+ std::env::remove_var("ANTHROPIC_API_KEY");
+}
+
+#[tokio::test]
+async fn login_stores_an_api_key_and_logout_removes_it() {
+ let dir = tempfile::tempdir().expect("temp dir");
+ let agent = dir.path().join("agent");
+ std::fs::create_dir_all(&agent).expect("agent dir");
+ let auth = ProviderAuth::new(dir.path(), agent);
+ let row = ProviderRow {
+ id: "openai".to_string(),
+ name: "OpenAI".to_string(),
+ auth_type: AuthType::ApiKey,
+ status: None,
+ flow: AuthFlow::ApiKeyPrompt,
+ configured: false,
+ available: true,
+ };
+ match auth.login(&row, Some("sk-test")).await {
+ ProviderAuthOutcome::Status(message) => {
+ assert!(
+ message.starts_with("Saved API key for OpenAI. Credentials saved to "),
+ "the store status names the credential path: {message}"
+ );
+ }
+ other => panic!("expected the store status, got {other:?}"),
+ }
+ // An empty key answers the TS error.
+ assert_eq!(
+ auth.login(&row, Some("")).await,
+ ProviderAuthOutcome::Error(
+ "Failed to save API key for OpenAI: API key cannot be empty.".to_string()
+ )
+ );
+ // The logout lists the stored credential and removes it.
+ let stored = auth.logout_options().await;
+ assert_eq!(stored.len(), 1);
+ assert_eq!(stored[0].id, "openai");
+ assert_eq!(
+ auth.logout(&stored[0]).await,
+ ProviderAuthOutcome::Status(
+ "Removed stored API key for OpenAI. Environment variables and models.json config are unchanged."
+ .to_string()
+ )
+ );
+ assert!(auth.logout_options().await.is_empty());
+}
+
+#[tokio::test]
+async fn a_stored_web_search_key_pairs_with_the_logout_row() {
+ let dir = tempfile::tempdir().expect("temp dir");
+ let agent = dir.path().join("agent");
+ std::fs::create_dir_all(&agent).expect("agent dir");
+ let auth = ProviderAuth::new(dir.path(), agent);
+ // A key stored at the runtime's slot (the `/mcp` view's key flow
+ // writes the same store through the same form).
+ let row = ProviderRow {
+ id: "serper".to_string(),
+ name: "Serper (web search)".to_string(),
+ auth_type: AuthType::ApiKey,
+ status: None,
+ flow: AuthFlow::ApiKeyPrompt,
+ configured: false,
+ available: true,
+ };
+ match auth.login(&row, Some("the-key")).await {
+ ProviderAuthOutcome::Status(message) => {
+ assert!(
+ message.starts_with("Saved API key for Serper (web search)."),
+ "the store status: {message}"
+ );
+ }
+ other => panic!("expected the store status, got {other:?}"),
+ }
+ // The logout row pairs with the stored key: the `/logout` surface
+ // lists it by its credential name and removes it.
+ let stored = auth.logout_options().await;
+ let row = stored
+ .iter()
+ .find(|row| row.id == "serper")
+ .expect("the web-search credential's logout row");
+ assert_eq!(row.name, "Serper (web search)");
+ assert_eq!(
+ auth.logout(row).await,
+ ProviderAuthOutcome::Status(
+ "Removed stored API key for Serper (web search). Environment variables and models.json config are unchanged."
+ .to_string()
+ )
+ );
+ assert!(auth.logout_options().await.is_empty());
+}
diff --git a/crates/pa-cli/tests/login_panel_pty_e2e.rs b/crates/pa-cli/tests/login_panel_pty_e2e.rs
index 349b1eb6e0..a24c73a871 100644
--- a/crates/pa-cli/tests/login_panel_pty_e2e.rs
+++ b/crates/pa-cli/tests/login_panel_pty_e2e.rs
@@ -263,6 +263,14 @@ impl pa_tui::client_auth::ClientAuthCommands for ScriptedClientAuth {
Box::pin(async move { Ok("Connected.".to_string()) })
}
+ fn api_key(
+ &self,
+ _credential: &str,
+ _panel: AuthPanelHandle,
+ ) -> Pin<Box<dyn std::future::Future<Output = anyhow::Result<String>> + Send>> {
+ Box::pin(async move { Ok("Saved API key.".to_string()) })
+ }
+
fn logout(
&self,
server: &str,
diff --git a/crates/pa-core/README.md b/crates/pa-core/README.md
index 71b9d10b11..1055520e80 100644
--- a/crates/pa-core/README.md
+++ b/crates/pa-core/README.md
@@ -74,7 +74,7 @@ only: nothing wires it to a user-facing cloud toggle yet.
No provider HTTP (pa-ai), no loop policy (pa-agent), no daemon supervision (pa-daemon), no TUI (pa-tui). No update coordination (the pa-cli coordinator owns the FSM; the update-flow seam here is the daemon-free support layer: `update::version` (semver/channel policy), `update::install` (the managed install-root layout), `update::release` (the channel manifest fetch), `update::download` (sha256-verified archive download + staging)). The package manager installs sources and resolves resource paths only. No workspace snapshot upload, transport, or remote materialization (staging and verification live here; the cloud attach surface owns the transport when it ships).
## Public API
-`SessionEngine` (message in -> events out), `export_html` (the HTML exporter plus its renderer seam: `tools_section`, `pre_render_custom_tools` + `ToolHtmlRenderer`/`RenderedToolHtml`/`RenderedToolResult`, and `ansi_to_html::ansi_lines_to_html`/`tool_render::trim_rendered_result_lines` for renderer implementers), `ToolRegistry`, kernel manager, settings (`SettingsManager`), packages (`packages::PackageManager` + source types), `platform` (process control, file locking, permissions, shell selection - usable by higher crates, e.g. pa-cli's detached spawn), `session_engine::rlm_host::RlmSubagentHost` (implemented by pa-daemon for supervisor-backed children; the default is no children), `mcp::McpManager` (the session's host-side MCP manager, exposed as `SessionEngine.mcp_manager`: auth gating for built-in integrations, the `mcpServers` setting seam, and the `mcp.*` host-request handlers - `mcp.config`/`mcp.refresh`/optional `mcp.begin_login` - the kernel's generic MCP client resolves through), `mcp::McpManager::connection_roster` + `mcp::McpConnectionEntry` (the `/mcp` view's roster: every resolved integration with its connected state, display kind, transport, and generic-listable flag), `mcp::McpManager::service_catalog_views` + `service_catalog_diagnostics` (the `/mcp` view's resolved service-catalog cards and their diagnostics, answered from local state - the TS `buildServiceCatalogViews` parity; the picker never round-trips the kernel), `models` (the registry and resolver, plus `models::order_for_picker`: the picker-catalog order the composition root applies to its snapshot), `session_engine::provider_adapter` (`switchable_stream_fn`/`ProviderTarget`: the live provider-target slot a host swaps on `set_model`; the adapter bridges the loop's abort into pa-ai's `StreamOptions::signal` cancellation token, so a turn abort cancels the in-flight HTTP fetch at the transport — closed by `ModelStream::close` and the stream's drop), `session_engine::ipython_state` (the post-compaction `ipython_state` kernel-persistence notice: the `CompactionKernelProbe` view of the kernel provisioner the engine wiring binds via `AgentSession::set_kernel_state_probe`, and the notice row that rides `CompactRun` for the surfaces to broadcast). `session_engine::session_commands` (the `/compact`/`/refine`/`/goal`/`/autonomous` executor: the durable echo/result rows with their persistence order - the echo ahead of the command so its own work sees it - the compaction/refinement/goal/autonomous arms, and the post-execution live-context rebuild that keeps the rows in the agent state; hosts own the wire surface), `session_engine::auto_refine_trigger` (the compact-trigger auto-refine machine on `AgentSession`: the arm/discard/increment accessors and `consume_compact_auto_refine`, the shared gate/review/stamp sequence every scheduling surface applies - TS `_compactAutoRefinePending`/`_lastAutoRefineReviewAt`/`_assistantTurnsSinceAutoRefine` plus `_maybeAutoRefine`'s compact arm, the serialized checkpoint's compact step, and dispose's serialized drain, with the surface parameter carrying the one behavioral difference between a boundary and a disposal). `session_engine::goal_boundary` (the goal arms of the natural turn end on `SessionEngine`: the `--goal` construction seed with its next-turn context row - TS `_pendingNextTurnMessages` on `AgentSession` - the usage accounting, the budget-limit steer mint, the natural continuation mint with its slot rollback, and the terminal-error finish; the transports - the print driver's in-loop hook, the ACP settle loop, the daemon worker's queue - drive the one goal driver through these methods). `SessionEngine::expand_skill_submission` + `AgentSession`'s prompt-path expansion (the `/skill:<name>` submission seam, TS `_expandSkillCommand`: `skills::expand_skill_command` builds the `<skill ...>` block over the shared `pa_types::skill_blocks` parse, the accepted-turn row and the admitted user message agree on the expanded text, and the `skill used` adoption event reports from the admission). `workspace_snapshot` (`create_workspace_snapshot`: bounded, secret/nested-repo/submodule/symlink-ancestor-excluding capture of a git worktree into an owner-private staging directory, with the caller-chosen `BaselineMode` (HEAD-tree content verified against HEAD's object ids, or explicit external) and a `ConcurrentMutation` error when the worktree changes under the capture; `verify_workspace_snapshot`: offline manifest/blob/baseline integrity check; the `SnapshotManifest`/`WorkspaceSnapshot`/`SnapshotLimits`/`BaselineMode`/`SnapshotError` types). All subsystem internals `pub(crate)`; the engine is the only facade - subsystems must not import each other directly (the package manager consumes the public settings API only).
+`SessionEngine` (message in -> events out), `export_html` (the HTML exporter plus its renderer seam: `tools_section`, `pre_render_custom_tools` + `ToolHtmlRenderer`/`RenderedToolHtml`/`RenderedToolResult`, and `ansi_to_html::ansi_lines_to_html`/`tool_render::trim_rendered_result_lines` for renderer implementers), `ToolRegistry`, kernel manager, settings (`SettingsManager`), packages (`packages::PackageManager` + source types), `platform` (process control, file locking, permissions, shell selection - usable by higher crates, e.g. pa-cli's detached spawn), `session_engine::rlm_host::RlmSubagentHost` (implemented by pa-daemon for supervisor-backed children; the default is no children), `mcp::McpManager` (the session's host-side MCP manager, exposed as `SessionEngine.mcp_manager`: auth gating for built-in integrations, the `mcpServers` setting seam, and the `mcp.*` host-request handlers - `mcp.config`/`mcp.refresh`/optional `mcp.begin_login` - the kernel's generic MCP client resolves through), `mcp::McpManager::connection_roster` + `mcp::McpConnectionEntry` (the `/mcp` view's roster: every resolved integration with its connected state, display kind, transport, and generic-listable flag), `mcp::McpManager::service_catalog_views` + `service_catalog_diagnostics` (the `/mcp` view's resolved service-catalog cards and their diagnostics, answered from local state - the TS `buildServiceCatalogViews` parity; the picker never round-trips the kernel), `mcp::McpManager::api_key_credential_views` + `mcp::API_KEY_CREDENTIALS`/`McpCredentialView` (the `/mcp` view's api-key credential rows - the stored keys the surface manages alongside the connections, e.g. the web-search key - configured from the shared auth store), `models` (the registry and resolver, plus `models::order_for_picker`: the picker-catalog order the composition root applies to its snapshot), `session_engine::provider_adapter` (`switchable_stream_fn`/`ProviderTarget`: the live provider-target slot a host swaps on `set_model`; the adapter bridges the loop's abort into pa-ai's `StreamOptions::signal` cancellation token, so a turn abort cancels the in-flight HTTP fetch at the transport — closed by `ModelStream::close` and the stream's drop), `session_engine::ipython_state` (the post-compaction `ipython_state` kernel-persistence notice: the `CompactionKernelProbe` view of the kernel provisioner the engine wiring binds via `AgentSession::set_kernel_state_probe`, and the notice row that rides `CompactRun` for the surfaces to broadcast). `session_engine::session_commands` (the `/compact`/`/refine`/`/goal`/`/autonomous` executor: the durable echo/result rows with their persistence order - the echo ahead of the command so its own work sees it - the compaction/refinement/goal/autonomous arms, and the post-execution live-context rebuild that keeps the rows in the agent state; hosts own the wire surface), `session_engine::auto_refine_trigger` (the compact-trigger auto-refine machine on `AgentSession`: the arm/discard/increment accessors and `consume_compact_auto_refine`, the shared gate/review/stamp sequence every scheduling surface applies - TS `_compactAutoRefinePending`/`_lastAutoRefineReviewAt`/`_assistantTurnsSinceAutoRefine` plus `_maybeAutoRefine`'s compact arm, the serialized checkpoint's compact step, and dispose's serialized drain, with the surface parameter carrying the one behavioral difference between a boundary and a disposal). `session_engine::goal_boundary` (the goal arms of the natural turn end on `SessionEngine`: the `--goal` construction seed with its next-turn context row - TS `_pendingNextTurnMessages` on `AgentSession` - the usage accounting, the budget-limit steer mint, the natural continuation mint with its slot rollback, and the terminal-error finish; the transports - the print driver's in-loop hook, the ACP settle loop, the daemon worker's queue - drive the one goal driver through these methods). `SessionEngine::expand_skill_submission` + `AgentSession`'s prompt-path expansion (the `/skill:<name>` submission seam, TS `_expandSkillCommand`: `skills::expand_skill_command` builds the `<skill ...>` block over the shared `pa_types::skill_blocks` parse, the accepted-turn row and the admitted user message agree on the expanded text, and the `skill used` adoption event reports from the admission). `workspace_snapshot` (`create_workspace_snapshot`: bounded, secret/nested-repo/submodule/symlink-ancestor-excluding capture of a git worktree into an owner-private staging directory, with the caller-chosen `BaselineMode` (HEAD-tree content verified against HEAD's object ids, or explicit external) and a `ConcurrentMutation` error when the worktree changes under the capture; `verify_workspace_snapshot`: offline manifest/blob/baseline integrity check; the `SnapshotManifest`/`WorkspaceSnapshot`/`SnapshotLimits`/`BaselineMode`/`SnapshotError` types). All subsystem internals `pub(crate)`; the engine is the only facade - subsystems must not import each other directly (the package manager consumes the public settings API only).
## Depends on
pa-types, pa-ai, pa-agent (one-way).
diff --git a/crates/pa-core/src/auth/mod.rs b/crates/pa-core/src/auth/mod.rs
index 3186948e54..c87dea7e1f 100644
--- a/crates/pa-core/src/auth/mod.rs
+++ b/crates/pa-core/src/auth/mod.rs
@@ -35,5 +35,6 @@ pub use storage::{
};
pub use types::{
AuthCredential, AuthSource, AuthSourceToken, AuthStatus, AuthStorageData, PrimeTeamAssignment,
- PrimeTeamCredential, StoredPrimeTeam, PRIME_INFERENCE_PROVIDER_ID,
+ PrimeTeamCredential, StoredPrimeTeam, PRIME_INFERENCE_PROVIDER_ID, SERPER_CREDENTIAL_ID,
+ SERPER_CREDENTIAL_NAME,
};
diff --git a/crates/pa-core/src/auth/types.rs b/crates/pa-core/src/auth/types.rs
index c9707deb92..a79790d99f 100644
--- a/crates/pa-core/src/auth/types.rs
+++ b/crates/pa-core/src/auth/types.rs
@@ -4,6 +4,14 @@ use serde::{Deserialize, Serialize};
pub const PRIME_INFERENCE_PROVIDER_ID: &str = "prime-inference";
+/// The web-search credential's auth-store slot (auth.json's `serper` key,
+/// the `AuthCredential::ApiKey` form): the websearch skill's runtime reads
+/// it on every call, and the `/mcp` view's api-key entry stores it.
+pub const SERPER_CREDENTIAL_ID: &str = "serper";
+
+/// The credential's display name (the `/mcp` row and the logout row).
+pub const SERPER_CREDENTIAL_NAME: &str = "Serper (web search)";
+
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PrimeTeamCredential {
diff --git a/crates/pa-core/src/mcp/catalog_plugin_views.rs b/crates/pa-core/src/mcp/catalog_plugin_views.rs
index 13ace94a2d..a6acbef647 100644
--- a/crates/pa-core/src/mcp/catalog_plugin_views.rs
+++ b/crates/pa-core/src/mcp/catalog_plugin_views.rs
@@ -493,6 +493,29 @@ pub struct McpConnectionView {
pub setup_hint: Option<String>,
}
+/// The `/mcp` view's api-key credential catalog: the non-provider keys the
+/// product stores in the shared auth store and offers alongside the MCP
+/// connections (the web-search key the websearch skill's runtime reads).
+pub const API_KEY_CREDENTIALS: &[(&str, &str)] = &[(
+ crate::auth::SERPER_CREDENTIAL_ID,
+ crate::auth::SERPER_CREDENTIAL_NAME,
+)];
+
+/// One row of the `/mcp` view's api-key credential section (the daemon's
+/// `get_mcp_connections` response): a stored key the surface manages. Enter
+/// opens the paste-the-key prompt; the submitted key lands in the row's auth
+/// slot (the `AuthCredential::ApiKey` form).
+#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct McpCredentialView {
+ /// The auth-store slot the credential writes and the runtime reads
+ /// (e.g. `serper`).
+ pub id: String,
+ pub label: String,
+ /// True when the shared auth store holds an API key at the slot.
+ pub configured: bool,
+}
+
/// The conflict hint of a reserved-ownership ruling (canonical and disabled
/// carry none).
fn ownership_setup_hint(ownership: &ReservedOwnership) -> Option<String> {
diff --git a/crates/pa-core/src/mcp/manager_catalog.rs b/crates/pa-core/src/mcp/manager_catalog.rs
index 22b966ed15..bc644db65c 100644
--- a/crates/pa-core/src/mcp/manager_catalog.rs
+++ b/crates/pa-core/src/mcp/manager_catalog.rs
@@ -12,7 +12,8 @@ use std::path::PathBuf;
use std::sync::Arc;
use super::catalog_plugin_views::{
- build_connection_views, build_plugin_views, AcpServerRow, BuildViewsInputs, McpPluginView,
+ build_connection_views, build_plugin_views, AcpServerRow, BuildViewsInputs, McpCredentialView,
+ McpPluginView, API_KEY_CREDENTIALS,
};
use super::catalog_schema::{AuthStrategy, SetupStatus};
use super::catalog_status_views::SnapshotCredentials;
@@ -123,6 +124,24 @@ impl McpManager {
})
}
+ /// The `/mcp` view's api-key credential rows (the credential catalog
+ /// served alongside the MCP connections): one row per catalog entry,
+ /// configured when the shared auth store holds an API key at its slot.
+ pub fn api_key_credential_views(&self) -> Vec<McpCredentialView> {
+ let credentials = self.credential_snapshot();
+ API_KEY_CREDENTIALS
+ .iter()
+ .map(|(id, label)| McpCredentialView {
+ id: (*id).to_string(),
+ label: (*label).to_string(),
+ configured: credentials
+ .credentials
+ .get(*id)
+ .is_some_and(|credential| matches!(credential, AuthCredential::ApiKey { .. })),
+ })
+ .collect()
+ }
+
/// The kernel connection inventory for `mcp.list_connections` (TS
/// `buildConnectionViews`): the resolved services plus user-declared
/// servers plus the session-scoped ACP servers, one row per
diff --git a/crates/pa-core/src/mcp/manager_catalog/tests.rs b/crates/pa-core/src/mcp/manager_catalog/tests.rs
index ca33139719..1f8e770b25 100644
--- a/crates/pa-core/src/mcp/manager_catalog/tests.rs
+++ b/crates/pa-core/src/mcp/manager_catalog/tests.rs
@@ -674,3 +674,137 @@ fn the_real_catalog_resolves_through_the_manager() {
68
);
}
+
+/// The `/mcp` view's api-key credential rows: the catalog entry renders
+/// with its honest configured state from the shared auth store (the
+/// `serper` slot the websearch runtime reads), and only a stored API key
+/// marks it configured.
+#[test]
+fn api_key_credential_views_read_the_shared_store() {
+ let agent_dir = tempfile::tempdir().expect("tempdir");
+ let mut manager = McpManager::new(McpManagerOptions {
+ auth_storage: crate::auth::AuthStorage::create(agent_dir.path()),
+ get_user_servers: no_user_servers(),
+ begin_login: None,
+ agent_dir: Some(agent_dir.path().to_path_buf()),
+ get_catalog_sources: None,
+ remote_source: None,
+ probe_override: None,
+ });
+ manager.refresh();
+ // The web-search credential's row renders, honestly unconfigured.
+ let views = manager.api_key_credential_views();
+ assert_eq!(
+ views,
+ vec![McpCredentialView {
+ id: "serper".to_string(),
+ label: "Serper (web search)".to_string(),
+ configured: false,
+ }],
+ "the api-key credential catalog serves the web-search entry"
+ );
+ // A stored API key at the slot marks the row configured.
+ {
+ let storage = manager.auth_storage_handle();
+ let mut auth = futures::executor::block_on(storage.lock());
+ auth.set(
+ "serper",
+ AuthCredential::ApiKey {
+ key: "serper-key".to_string(),
+ prime_team: None,
+ },
+ );
+ }
+ manager.refresh();
+ assert!(
+ manager
+ .api_key_credential_views()
+ .first()
+ .expect("the serper row renders")
+ .configured,
+ "a stored API key marks the credential configured"
+ );
+ // A non-API-key value at the slot never reads configured.
+ {
+ let storage = manager.auth_storage_handle();
+ let mut auth = futures::executor::block_on(storage.lock());
+ auth.set(
+ "serper",
+ AuthCredential::Oauth {
+ access: "access".to_string(),
+ refresh: None,
+ expires: 0,
+ account_id: None,
+ endpoint: None,
+ token_endpoint: None,
+ client_id: None,
+ resource: None,
+ issuer: None,
+ enterprise_url: None,
+ },
+ );
+ }
+ manager.refresh();
+ assert!(
+ !manager
+ .api_key_credential_views()
+ .first()
+ .expect("the serper row renders")
+ .configured,
+ "only an API-key credential marks the row configured"
+ );
+}
+
+#[test]
+fn api_key_credential_views_see_a_cross_instance_write_after_the_reload() {
+ let agent_dir = tempfile::tempdir().expect("tempdir");
+ let mut manager = McpManager::new(McpManagerOptions {
+ auth_storage: crate::auth::AuthStorage::create(agent_dir.path()),
+ get_user_servers: no_user_servers(),
+ begin_login: None,
+ agent_dir: Some(agent_dir.path().to_path_buf()),
+ get_catalog_sources: None,
+ remote_source: None,
+ probe_override: None,
+ });
+ manager.refresh();
+ assert!(
+ !manager
+ .api_key_credential_views()
+ .first()
+ .expect("the serper row renders")
+ .configured,
+ "the fresh store holds no key"
+ );
+ // The interactive client's `/mcp` key flow stores through its OWN
+ // storage instance (a different process writing the same auth.json).
+ {
+ let mut client_side = crate::auth::AuthStorage::create(agent_dir.path());
+ client_side.set(
+ "serper",
+ AuthCredential::ApiKey {
+ key: "serper-key".to_string(),
+ prime_team: None,
+ },
+ );
+ }
+ // Without the reload the manager's cached copy stays stale.
+ assert!(
+ !manager
+ .api_key_credential_views()
+ .first()
+ .expect("the serper row renders")
+ .configured,
+ "the cached copy does not see the other instance's write"
+ );
+ // The view open's reload picks the stored key up.
+ manager.reload_auth_storage();
+ assert!(
+ manager
+ .api_key_credential_views()
+ .first()
+ .expect("the serper row renders")
+ .configured,
+ "the reload sees the cross-instance write"
+ );
+}
diff --git a/crates/pa-core/src/mcp/mod.rs b/crates/pa-core/src/mcp/mod.rs
index 0aef745e40..c7cb55f9d9 100644
--- a/crates/pa-core/src/mcp/mod.rs
+++ b/crates/pa-core/src/mcp/mod.rs
@@ -21,6 +21,7 @@ mod remote_source;
mod service_catalog;
mod url_checks;
+pub use catalog_plugin_views::{McpCredentialView, API_KEY_CREDENTIALS};
pub use catalog_views::{
mcp_credential_field_prompt_label, mcp_paste_credential, McpPasteCredential,
};
@@ -361,6 +362,17 @@ impl McpManager {
self.resolve_integrations();
}
+ /// Reload the shared auth store (blocking lock, never on the async
+ /// runtime): a credential another process wrote — the interactive
+ /// client's `/mcp` key flow stores through its own storage instance —
+ /// becomes visible to the next view read, like the settings re-read
+ /// above.
+ pub fn reload_auth_storage(&mut self) {
+ let storage = self.auth_storage.clone();
+ let mut handle = storage.blocking_lock();
+ handle.reload();
+ }
+
/// The resolved integrations (login resolution and status displays).
pub(crate) fn integrations(&self) -> &HashMap<String, ResolvedIntegration> {
&self.integrations
diff --git a/crates/pa-core/tests/golden/corpus/system-prompt.json b/crates/pa-core/tests/golden/corpus/system-prompt.json
index 763e343b4f..8735af7adb 100644
--- a/crates/pa-core/tests/golden/corpus/system-prompt.json
+++ b/crates/pa-core/tests/golden/corpus/system-prompt.json
@@ -8,5 +8,5 @@
"skillsSource": "bundled skills directory (<skills-dir>)"
},
"skill_count": 12,
- "systemPrompt": "# prime-agent harness\n\nThe prime-agent harness has one tool: `ipython`, a persistent CPython REPL. All other tools are \"programmatic tools\", functions inside the Python REPL called via \"programmatic tool calling\" (PTC). All programmatic tools are async unless described otherwise and can be run in the background. `await` works directly and globally in the REPL.\n\nThe harness often sends messages to the agent. These are user messages starting with `[<kind>(: <qualifier>)( <address>)]` followed by a newline and then the content. They are not user-generated.\n\n## Core tools\n\n- `bash(command: str) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `ipython` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls\n - `BashHandle`:\n - `.pid: int`\n - `.running: bool`\n - `.command: str`\n - `.tail(n: int = 50) -> str`\n - `.output() -> str`\n - `.poll() -> BashResult | None`\n - `.kill(sig: int = SIGTERM, grace: float = 5.0) -> None`: SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive\n - `await handle -> BashResult`: the handle is awaitable even after command completion, so agents can run commands non-blocking and await them after being notified of them finishing\n - `BashResult`\n - `.exit_code: int`\n - `.output: str`\n - `.duration: float`\n- `edit.run(path: str, old_str: str, new_str: str) -> str`: the primary method for editing files. async, exact-unique-match; the `edit` module is callable with the same arguments (`await edit(path=..., old_str=..., new_str=...)`)\n- `websearch.run(query: str, *, max_output: int = 8192, timeout: int | None, num_results: int | None) -> str`: search the web; the `websearch` module is callable with the same arguments\n- `attach_image(*paths: str) -> str`: loads images directly into context if the agent's model is vision-capable, errors otherwise\n\n## Subagents\n\nprime-agent is a recursive harness. Each session builds a tree of agents, starting at depth 0. Each agent up to a user-configured limit can launch subagents. These subagents are persistent, just like the root session. Each agent can communicate with its nuclear family: its singular parent (except for depth 0 sessions which have no parent), its siblings (other subagents under the same parent), and its children (its own subagents).\n\nThe following programmatic tools are available in the REPL for subagent management:\n\n- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short\n- `rlm.create_session(prompt: str, name: str | None = None, model: str | None = None, thinking: str | None = None, cwd: str | None = None) -> RLMCreateSessionHandle`: creates another depth-0 session; only available to agents at depth 0 backed by a daemon; returns after the session is successfully created and the first prompt sent\n- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`\n- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles\n- `rlm.delete_subagent(target: str | RLMSubagent) -> RLMSubagent`\n- `rlm.collect(targets=None, *, timeout_ms: int = 0) -> list[RLMChildResult]`: typed snapshots of direct children (status, settled flag, answer preview, error) without steering anyone; `timeout_ms=0` returns a non-blocking snapshot; a positive timeout blocks only this call until the children settle or the deadline passes\n- `rlm.progress_note(message: str) -> dict`: report brief in-flight progress to the parent orchestrator (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply\n- `RLMSpawnHandle`\n - `rlm_child_id: str`\n - `name: str`\n - `session_dir: Path`\n - `model: str`: provider/model, full resolved model name\n- `RLMCreateSessionHandle`\n - `active_session_id: str`: live daemon-instance id\n - `session_id: str`: durable on-disk session identity\n - `name: str`\n - `session_file: Path`: path to persisted session log\n - `model: str`: provider/model, full resolved model name\n- `RLMSubagent`\n - `rlm_child_id: str`\n - `active_session_id: str | None`\n - `session_id: str | None`\n - `session_name: str`\n - `session_dir: Path`\n - `status: Literal[\"running\", \"completed\", \"error\"]`\n - rows also carry live activity detail (current activity, tool use count, duration, answer preview, latest progress note)\n- `RLMModel`\n - `provider: str`\n - `id: str`\n - `name: str`\n - `selector: str`: the exact string to spawn the model\n\nThe following programmatic tools are available in the REPL for a2a communication:\n\n- `agent_message.send(message: str, *, receiver_role: Literal[\"parent\", \"sibling\", \"child\"], receiver_name: str | None) -> dict`: send a message to the receiver; returns a receipt with the message id and a delivery status (delivered or queued); all root sessions are siblings; `send(\"all\", broadcast_message)` broadcasts to the family roster and returns `{receipts: [...]}`\n- `agent_observe.list_agents() -> dict`: list nuclear family\n- `agent_observe.get_agent(target: str) -> dict`: one agent's status detail\n- `agent_observe.recent_messages(target: str, limit: int = 8, max_chars: int = 800) -> dict`: transcript preview; `limit` errors outside [1-50], `max_chars` outside [80-2000]\n\n## Continual Harness\n\nprime-agent is a continual harness. During a session, persistent memories can be written and read. These stay available even after multiple compactions.\n\nMemories are created by two mechanisms:\n\n- Refinement\n - Mechanism:\n - Another model suggests a refinement based on the transcript\n - The suggested edits are applied to the harness state\n - The main agent is notified by a structured harness message and the applied edits are saved\n - Triggered by:\n - Calling the programmatic tool `refine.run()`\n - By the user command `/refine`\n - Effect:\n - The refinement event is always saved in the harness state's refinement history\n - A harness message is sent to the agent with the refinement result\n- Active memory management by the agent\n - `refine.run(instructions: str | None = None, global_: bool = False) -> dict`: agent-triggered refinement (see above); returns immediately and runs when the current turn ends\n- `refine.status() -> dict`: whether a refinement is already pending for this turn or currently in flight\n - `rlm.harness.create_memory(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: creates a memory; use `global_=True` for cross-session entries (Python reserves `global`, so the parameter is spelled `global_`)\n - `rlm.harness.update_memory(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_memory(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_prompt_note(title: str, content: str, *, id: str | None = None, path: str = \"policy\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_prompt_note(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_prompt_note(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_skill(title: str, content: str, *, id: str | None = None, path: str = \"general\", reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: `reference`/`arguments` describe the Python callable (`reference` requires `{\"type\": \"python\"}`, a Python import, and a callable or call pattern)\n - `rlm.harness.update_skill(id: str, title: str, content: str, *, path: str | None = None, reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_skill(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_subagent(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_subagent(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_subagent(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.record_refinement(trigger: str, changes: list[str], *, evidence: str = \"\", outcome: str = \"\", id: str | None = None, global_: bool = False) -> RefinementEvent`\n - `rlm.harness.plan_refinement(observation: str, *, failing_component: str = \"\", next_step: str = \"\") -> list[str]`: a suggested diagnose -> update -> validate plan\n - `rlm.harness.overview(*, max_entries_per_kind: int = 20, global_: bool = False) -> str`: memory overview\n - `rlm.harness.search(query: str, kind: str | None = None, limit: int = 10, *, global_: bool = False) -> list[HarnessEntry]`: ranked term search over entries\n - `rlm.get_harness_state(state_dir: str | Path | None = None, *, global_: bool = False) -> HarnessState`: full memory details for the selected scope. Can read another agent's `HarnessState` by passing the path to it in `state_dir`\n - `HarnessEntry`\n - `id: str`\n - `kind: Literal[\"prompt\", \"memory\", \"skill\", \"subagent\"]`\n - `title: str`\n - `content: str`\n - `path: str`: category path (\"general\" for memories, \"policy\" for prompt notes)\n - `scope: Literal[\"local\", \"global\"]`\n - `reference: dict[str, Any]`: for skills\n - `arguments: dict[str, Any]`: for skills\n - `metadata: dict`\n - `source: Literal[\"agent\", \"refine\"]`\n - `created_at: str`: ISO timestamp of creation\n - `updated_at: str`: ISO timestamp of latest update\n - `version: int`: increments with every update, starting at 1\n - `HarnessState`\n - `scope: Literal[\"global\", \"local\"]`\n - `file_path: Path`\n - `entries: dict[kind, dict[id, HarnessEntry]]`\n - `refinements: list[RefinementEvent]`\n - `RefinementEvent`\n - `id: str`\n - `trigger: str`: what caused the refinement\n - `changes: list[str]`: applied edits; empty if never edited\n - `evidence: str`\n - `outcome: str`\n - `created_at: str`\n\n## Compaction\n\nprime-agent compacts automatically when there is only a given number of tokens left in the context window (default: 16384), when the user triggers compaction, or when the agent triggers compaction. REPL state persists across compactions, but compaction removes individual variables whose serialized form exceeds 16 MiB.\n\n- `compact.run(instructions: str | None = None) -> dict`: schedule a compaction at the next assistant turn boundary\n- `compact.status() -> dict`: context usage & threshold before auto-compaction\n\n## Goal\n\nIn goal mode prime-agent helps an agent stay on track until a task is fully finished, and handles interruptions and other issues. Goals can be user- or agent-created.\n\n- `goal.create(objective: str, token_budget: int | None = None) -> dict`: create goal and return goal state\n- `goal.get() -> dict`: get goal status (only one goal can be active at a time)\n- `goal.complete() -> dict`: mark goal as completed and get final goal status\n\n## Heartbeat\n\nIn prime-agent, agents can create heartbeats to wake themselves up after a given period of time with remembered instructions, recurrently on a given schedule.\n\n- `rlm_heartbeat.create(instruction: str, interval: str | None = None, label: str | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`: new recurring heartbeat for this session; `interval` is a schedule string (default: every 5 minutes); `delivery_mode`: steer (default) interrupts a busy session's current turn, follow_up waits for it to finish\n- `rlm_heartbeat.list(include_inactive: bool = False) -> dict`\n- `rlm_heartbeat.update(id: str, instruction: str | None = None, interval: str | None = None, label: str | None = None, status: Literal[\"pause\", \"resume\"] | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`\n- `rlm_heartbeat.delete(id: str) -> dict`\n\n## MCP\n\nprime-agent has support for programmatic tools that are defined in the MCP format. Their schema is discovered at runtime.\n\n- `mcp.list_tools(server: str) -> list[dict]`: returns tool schemas\n- `mcp.call_tool(server: str, tool: str, arguments: dict | None = None) -> Any`\n- `mcp.list_plugins(connection_status: str | None = None, limit: int = 50, cursor: str | None = None) -> dict`: one bounded page of the supported-service catalog\n- `mcp.search_plugins(query: str, limit: int = 10) -> dict`: bounded catalog search\n- `mcp.list_connections() -> list[dict]`: the user's current connections (the dispatch ids)\n- `mcp.search_tools(query: str, connection_id: str | None = None, limit: int = 20) -> dict`: search live tool names/descriptions and report the search scope\n- `mcp.describe_tool(connection_id: str, tool: str) -> dict`: one live tool's name, description, and inputSchema\n\n## Skills\n\nprime-agent provides multiple executable skills, described by their SKILL.md and executable code. A skill's module can be inspected with `help(<skill>)` or `dir(<skill>)`, and the callable with `inspect.signature(<skill>.<function>)`, if information is missing. The executable code is always pre-imported in the REPL as a programmatic tool, and a callable skill module can be called directly (`await <skill>(...)`).\n\nAll programmatic tools described above except for `bash`, `rlm.*`, and `mcp.*` are implemented as executable skills and will be listed again in the dynamic tail of this prompt. Additional executable and non-executable skills may exist as well; non-executable (markdown) skills are documentation read from disk, and each skill is also available as a shell command by the same name.\n\nThe following are mandatory rules, only to be overridden by clear user intent.\n\n- Memories must be kept lean and up-to-date.\n- `goal.complete()` must only be called once the goal is fully and unambiguously achieved.\n- Goals must only be created at a user's request.\n- Agents run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n- `bash(\"\"\"...\"\"\")` should be used over `bash(\"...\")` because it makes using quotation marks inside bash easy.\n- Bash commands must be run in the background; if they are quick, or the agent is doing other heavy work in the same `ipython` call, they should be awaited or polled in the same `ipython` call interleaved with other work, or a subsequent one; otherwise, the agent should wait for the notification; blocking calls reduce user responsiveness.\n- Shell state does not persist between calls, but agents can use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables — both persist in the REPL and apply to later `bash()` calls through POSIX process inheritance (since each bash call is a fresh process, Python does not inherit environment variables from bash).\n- Edits of existing files must be performed using `edit` with exact old/new strings; if the text contains triple double quotes (\"\"\"), the agent should use triple single-quoted variables or build `old`/`new` from inspected file slices.\n- Agents use Python for reading files and searching in them — it gives them reusable variables they can slice, filter, and act on without re-reading; using Python variables to find or produce, and to save the strings used in `edit` is also encouraged.\n- Agents always assign read/search results to named variables so they can revisit them later.\n- Agents must report assumptions they made and constants they changed to the user.\n- When an agent is done, they stop calling tools and state their final answer.\n- When delegation is available and useful, an agent assigns independent substantive tasks to separate workers. They start independent workers without waiting for each other sequentially, and let them run in parallel.\n- Agents do not keep the turn open by polling with `time.sleep()` or shell `sleep`, and they do not replace polling with a long blocking `await`. They await only the short operation needed to start work or inspect a result that is already available; otherwise they end the turn.\n- Agents use the Python REPL to keep intermediate variables, inspect and transform outputs, and write small helper functions.\n- Since compaction removes individual variables whose serialized form exceeds 16 MiB, agents can keep large source data on disk and reload it when needed.\n- Python is the orchestration language: agents use Python for loops, conditionals, parsing, and state. They use `bash()` to invoke programs, not to write shell programs, shell loops, or heredocs; those are done directly in Python.\n- Agents do not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Agents evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n- Agents do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, they run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Agents treat failures from that native environment as the relevant result.\n- Rules for root agents (depth 0):\n - Only message siblings if you are certain that it is necessary.\n - When work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n- Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n- Agents treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: they diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. They use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so agents continue working normally after calling it. Agents do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n- Instructions to agents for multi-agent work:\n - When spawning a subagent, keep the handle to stop or inspect the child later.\n - Ask for an explicit reply when needed; not every message needs a reply.\n - Use `await rlm.list_subagents()` after kernel restart or compaction.\n - Have children write files and read those files for fan-in.\n - Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\n\nThe following guidelines to agents have been shown to improve results on average. Agents should consider using them where appropriate. Clear user instructions always override these defaults.\n\n- Agents can use the following patterns to make better use of the REPL:\n - Write wrappers around `rlm.spawn` to have quick templates for subagents with arbitrary args: for text to programmatically pass and put into the prompt, for conditional behavior prompts, etc.\n - Use f-strings (`f\"\"\"...\"\"\"` or `f\"...\"`) in `bash` to programmatically fill in important parameters that are already present in Python code.\n- When writing or explaining something:\n - Agents use simplified technical English by default for user-facing prose: short sentences, common words, and concrete verbs; one main action or fact per sentence when practical; lists for steps or conditions. Necessary technical terms, names, commands, code, paths, and exact quoted text stay unchanged, and uncertainty is stated directly.\n - Agents use ordinary or established wording. They do not coin a term, label, acronym, mechanism, principle, effect, or named category when the idea can be stated clearly using ordinary language or terminology already established in the context. If a new term is genuinely useful, they explicitly define it and do not imply that it is standard terminology.\n - Agents keep names and terms consistent. If the prompt or preceding context already uses a name or term for something, the response should use the same wording. Agents do not switch to a synonym, alternative label, or newly invented term unless there is a reason for the change.\n- Agents take care and effort to avoid the following pitfalls while coding:\n - over-engineered solutions\n - overly defensive programming\n - hyper-fixation on rare/fictitious edge cases\n - overlapping subsystem responsibilities\n - solving problems at the wrong architectural layer\n - duplication of sources of truth, then inventing machinery to synchronize them\n - prematurely generalizing one-off flows\n - timeouts on everything\n - production code that exists purely to satisfy tests\n - patching bad premises additively instead of stepping back and deleting or adjusting them\n - tests for magic strings\n - excessive tests\n - comments that describe anything already described by the code\n - comments narrating the coding process instead of supporting the written code\n - fallbacks, legacy support, compatibility shims where not strictly needed; when in doubt, these should be discussed with the user\n - in UI, descriptions on everything\n\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent&apos;s parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location><skills-dir>/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent&apos;s parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location><skills-dir>/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model&apos;s context as a viewable attachment so the model can directly SEE it — for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image&apos;s visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location><skills-dir>/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location><skills-dir>/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location><skills-dir>/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location><skills-dir>/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>mcp</name>\n <type>markdown</type>\n <description>Use external MCP services generically from Python - search the supported-service catalog, inspect the user&apos;s connections, discover live tool schemas, and call tools on any connection (Notion, Linear, Slack, and the rest of the catalog) without per-service packages.</description>\n <location><skills-dir>/mcp/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location><skills-dir>/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location><skills-dir>/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user&apos;s /heartbeat.</description>\n <location><skills-dir>/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location><skills-dir>/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location><skills-dir>/websearch/SKILL.md</location>\n </skill>\n</available_skills>\n\nCurrent date: <date>\nWorking directory: /w\nConversation log: /w/sessions/fixture-session.jsonl\n\nRecursive agent depth: 0 (root)"
+ "systemPrompt": "# prime-agent harness\n\nThe prime-agent harness has one tool: `ipython`, a persistent CPython REPL. All other tools are \"programmatic tools\", functions inside the Python REPL called via \"programmatic tool calling\" (PTC). All programmatic tools are async unless described otherwise and can be run in the background. `await` works directly and globally in the REPL.\n\nThe harness often sends messages to the agent. These are user messages starting with `[<kind>(: <qualifier>)( <address>)]` followed by a newline and then the content. They are not user-generated.\n\n## Core tools\n\n- `bash(command: str) -> BashHandle`: synchronous, returns immediately and runs the command in the background; when a command is finished outside the calling `ipython` block, a notification is sent to the agent; each `bash()` call is its own process, so shell state does not persist between calls\n - `BashHandle`:\n - `.pid: int`\n - `.running: bool`\n - `.command: str`\n - `.tail(n: int = 50) -> str`\n - `.output() -> str`\n - `.poll() -> BashResult | None`\n - `.kill(sig: int = SIGTERM, grace: float = 5.0) -> None`: SIGTERM, escalating to SIGKILL; on Windows kill() uses taskkill /T and detached or reparented descendants may survive\n - `await handle -> BashResult`: the handle is awaitable even after command completion, so agents can run commands non-blocking and await them after being notified of them finishing\n - `BashResult`\n - `.exit_code: int`\n - `.output: str`\n - `.duration: float`\n- `edit.run(path: str, old_str: str, new_str: str) -> str`: the primary method for editing files. async, exact-unique-match; the `edit` module is callable with the same arguments (`await edit(path=..., old_str=..., new_str=...)`)\n- `websearch.run(query: str, *, max_output: int = 8192, timeout: int | None, num_results: int | None) -> str`: search the web; the `websearch` module is callable with the same arguments\n- `attach_image(*paths: str) -> str`: loads images directly into context if the agent's model is vision-capable, errors otherwise\n\n## Subagents\n\nprime-agent is a recursive harness. Each session builds a tree of agents, starting at depth 0. Each agent up to a user-configured limit can launch subagents. These subagents are persistent, just like the root session. Each agent can communicate with its nuclear family: its singular parent (except for depth 0 sessions which have no parent), its siblings (other subagents under the same parent), and its children (its own subagents).\n\nThe following programmatic tools are available in the REPL for subagent management:\n\n- `rlm.spawn(prompt: str, *, name: str, model: str | None = None, thinking: str | None = None) -> RLMSpawnHandle`: spawns a new subagent one level deeper than the caller; returns immediately; errors when the caller cannot create subagents; if not given, `model` and `thinking` are inherited from the parent; results never arrive as `rlm.spawn()` return values, they arrive only via agent_message; `name` must be unique among the spawned agent's siblings, and be meaningful and descriptive but short\n- `rlm.create_session(prompt: str, name: str | None = None, model: str | None = None, thinking: str | None = None, cwd: str | None = None) -> RLMCreateSessionHandle`: creates another depth-0 session; only available to agents at depth 0 backed by a daemon; returns after the session is successfully created and the first prompt sent\n- `rlm.find_models(query: str = '', limit: int = 8) -> list[RLMModel]`\n- `rlm.list_subagents() -> list[RLMSubagent]`: direct child handles\n- `rlm.delete_subagent(target: str | RLMSubagent) -> RLMSubagent`\n- `rlm.collect(targets=None, *, timeout_ms: int = 0) -> list[RLMChildResult]`: typed snapshots of direct children (status, settled flag, answer preview, error) without steering anyone; `timeout_ms=0` returns a non-blocking snapshot; a positive timeout blocks only this call until the children settle or the deadline passes\n- `rlm.progress_note(message: str) -> dict`: report brief in-flight progress to the parent orchestrator (at most 512 characters, throttled to about one note per 10 seconds); the parent sees notes without needing a reply\n- `RLMSpawnHandle`\n - `rlm_child_id: str`\n - `name: str`\n - `session_dir: Path`\n - `model: str`: provider/model, full resolved model name\n- `RLMCreateSessionHandle`\n - `active_session_id: str`: live daemon-instance id\n - `session_id: str`: durable on-disk session identity\n - `name: str`\n - `session_file: Path`: path to persisted session log\n - `model: str`: provider/model, full resolved model name\n- `RLMSubagent`\n - `rlm_child_id: str`\n - `active_session_id: str | None`\n - `session_id: str | None`\n - `session_name: str`\n - `session_dir: Path`\n - `status: Literal[\"running\", \"completed\", \"error\"]`\n - rows also carry live activity detail (current activity, tool use count, duration, answer preview, latest progress note)\n- `RLMModel`\n - `provider: str`\n - `id: str`\n - `name: str`\n - `selector: str`: the exact string to spawn the model\n\nThe following programmatic tools are available in the REPL for a2a communication:\n\n- `agent_message.send(message: str, *, receiver_role: Literal[\"parent\", \"sibling\", \"child\"], receiver_name: str | None) -> dict`: send a message to the receiver; returns a receipt with the message id and a delivery status (delivered or queued); all root sessions are siblings; `send(\"all\", broadcast_message)` broadcasts to the family roster and returns `{receipts: [...]}`\n- `agent_observe.list_agents() -> dict`: list nuclear family\n- `agent_observe.get_agent(target: str) -> dict`: one agent's status detail\n- `agent_observe.recent_messages(target: str, limit: int = 8, max_chars: int = 800) -> dict`: transcript preview; `limit` errors outside [1-50], `max_chars` outside [80-2000]\n\n## Continual Harness\n\nprime-agent is a continual harness. During a session, persistent memories can be written and read. These stay available even after multiple compactions.\n\nMemories are created by two mechanisms:\n\n- Refinement\n - Mechanism:\n - Another model suggests a refinement based on the transcript\n - The suggested edits are applied to the harness state\n - The main agent is notified by a structured harness message and the applied edits are saved\n - Triggered by:\n - Calling the programmatic tool `refine.run()`\n - By the user command `/refine`\n - Effect:\n - The refinement event is always saved in the harness state's refinement history\n - A harness message is sent to the agent with the refinement result\n- Active memory management by the agent\n - `refine.run(instructions: str | None = None, global_: bool = False) -> dict`: agent-triggered refinement (see above); returns immediately and runs when the current turn ends\n- `refine.status() -> dict`: whether a refinement is already pending for this turn or currently in flight\n - `rlm.harness.create_memory(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: creates a memory; use `global_=True` for cross-session entries (Python reserves `global`, so the parameter is spelled `global_`)\n - `rlm.harness.update_memory(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_memory(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_prompt_note(title: str, content: str, *, id: str | None = None, path: str = \"policy\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_prompt_note(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_prompt_note(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_skill(title: str, content: str, *, id: str | None = None, path: str = \"general\", reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`: `reference`/`arguments` describe the Python callable (`reference` requires `{\"type\": \"python\"}`, a Python import, and a callable or call pattern)\n - `rlm.harness.update_skill(id: str, title: str, content: str, *, path: str | None = None, reference: dict | None = None, arguments: dict | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_skill(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.create_subagent(title: str, content: str, *, id: str | None = None, path: str = \"general\", metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.update_subagent(id: str, title: str, content: str, *, path: str | None = None, metadata: dict | None = None, global_: bool = False) -> HarnessEntry`\n - `rlm.harness.delete_subagent(id: str, *, global_: bool = False) -> bool`\n - `rlm.harness.record_refinement(trigger: str, changes: list[str], *, evidence: str = \"\", outcome: str = \"\", id: str | None = None, global_: bool = False) -> RefinementEvent`\n - `rlm.harness.plan_refinement(observation: str, *, failing_component: str = \"\", next_step: str = \"\") -> list[str]`: a suggested diagnose -> update -> validate plan\n - `rlm.harness.overview(*, max_entries_per_kind: int = 20, global_: bool = False) -> str`: memory overview\n - `rlm.harness.search(query: str, kind: str | None = None, limit: int = 10, *, global_: bool = False) -> list[HarnessEntry]`: ranked term search over entries\n - `rlm.get_harness_state(state_dir: str | Path | None = None, *, global_: bool = False) -> HarnessState`: full memory details for the selected scope. Can read another agent's `HarnessState` by passing the path to it in `state_dir`\n - `HarnessEntry`\n - `id: str`\n - `kind: Literal[\"prompt\", \"memory\", \"skill\", \"subagent\"]`\n - `title: str`\n - `content: str`\n - `path: str`: category path (\"general\" for memories, \"policy\" for prompt notes)\n - `scope: Literal[\"local\", \"global\"]`\n - `reference: dict[str, Any]`: for skills\n - `arguments: dict[str, Any]`: for skills\n - `metadata: dict`\n - `source: Literal[\"agent\", \"refine\"]`\n - `created_at: str`: ISO timestamp of creation\n - `updated_at: str`: ISO timestamp of latest update\n - `version: int`: increments with every update, starting at 1\n - `HarnessState`\n - `scope: Literal[\"global\", \"local\"]`\n - `file_path: Path`\n - `entries: dict[kind, dict[id, HarnessEntry]]`\n - `refinements: list[RefinementEvent]`\n - `RefinementEvent`\n - `id: str`\n - `trigger: str`: what caused the refinement\n - `changes: list[str]`: applied edits; empty if never edited\n - `evidence: str`\n - `outcome: str`\n - `created_at: str`\n\n## Compaction\n\nprime-agent compacts automatically when there is only a given number of tokens left in the context window (default: 16384), when the user triggers compaction, or when the agent triggers compaction. REPL state persists across compactions, but compaction removes individual variables whose serialized form exceeds 16 MiB.\n\n- `compact.run(instructions: str | None = None) -> dict`: schedule a compaction at the next assistant turn boundary\n- `compact.status() -> dict`: context usage & threshold before auto-compaction\n\n## Goal\n\nIn goal mode prime-agent helps an agent stay on track until a task is fully finished, and handles interruptions and other issues. Goals can be user- or agent-created.\n\n- `goal.create(objective: str, token_budget: int | None = None) -> dict`: create goal and return goal state\n- `goal.get() -> dict`: get goal status (only one goal can be active at a time)\n- `goal.complete() -> dict`: mark goal as completed and get final goal status\n\n## Heartbeat\n\nIn prime-agent, agents can create heartbeats to wake themselves up after a given period of time with remembered instructions, recurrently on a given schedule.\n\n- `rlm_heartbeat.create(instruction: str, interval: str | None = None, label: str | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`: new recurring heartbeat for this session; `interval` is a schedule string (default: every 5 minutes); `delivery_mode`: steer (default) interrupts a busy session's current turn, follow_up waits for it to finish\n- `rlm_heartbeat.list(include_inactive: bool = False) -> dict`\n- `rlm_heartbeat.update(id: str, instruction: str | None = None, interval: str | None = None, label: str | None = None, status: Literal[\"pause\", \"resume\"] | None = None, delivery_mode: Literal[\"steer\", \"follow_up\"] | None = None) -> dict`\n- `rlm_heartbeat.delete(id: str) -> dict`\n\n## MCP\n\nprime-agent has support for programmatic tools that are defined in the MCP format. Their schema is discovered at runtime.\n\n- `mcp.list_tools(server: str) -> list[dict]`: returns tool schemas\n- `mcp.call_tool(server: str, tool: str, arguments: dict | None = None) -> Any`\n- `mcp.list_plugins(connection_status: str | None = None, limit: int = 50, cursor: str | None = None) -> dict`: one bounded page of the supported-service catalog\n- `mcp.search_plugins(query: str, limit: int = 10) -> dict`: bounded catalog search\n- `mcp.list_connections() -> list[dict]`: the user's current connections (the dispatch ids)\n- `mcp.search_tools(query: str, connection_id: str | None = None, limit: int = 20) -> dict`: search live tool names/descriptions and report the search scope\n- `mcp.describe_tool(connection_id: str, tool: str) -> dict`: one live tool's name, description, and inputSchema\n\n## Skills\n\nprime-agent provides multiple executable skills, described by their SKILL.md and executable code. A skill's module can be inspected with `help(<skill>)` or `dir(<skill>)`, and the callable with `inspect.signature(<skill>.<function>)`, if information is missing. The executable code is always pre-imported in the REPL as a programmatic tool, and a callable skill module can be called directly (`await <skill>(...)`).\n\nAll programmatic tools described above except for `bash`, `rlm.*`, and `mcp.*` are implemented as executable skills and will be listed again in the dynamic tail of this prompt. Additional executable and non-executable skills may exist as well; non-executable (markdown) skills are documentation read from disk, and each skill is also available as a shell command by the same name.\n\nThe following are mandatory rules, only to be overridden by clear user intent.\n\n- Memories must be kept lean and up-to-date.\n- `goal.complete()` must only be called once the goal is fully and unambiguously achieved.\n- Goals must only be created at a user's request.\n- Agents run shell commands with `bash()`, not `subprocess`/`os.system`: subprocess calls block the kernel, show the user nothing while they run, and spawn processes the harness cannot see or stop.\n- `bash(\"\"\"...\"\"\")` should be used over `bash(\"...\")` because it makes using quotation marks inside bash easy.\n- Bash commands must be run in the background; if they are quick, or the agent is doing other heavy work in the same `ipython` call, they should be awaited or polled in the same `ipython` call interleaved with other work, or a subsequent one; otherwise, the agent should wait for the notification; blocking calls reduce user responsiveness.\n- Shell state does not persist between calls, but agents can use `os.chdir(...)` for the working directory and `os.environ[...]` for environment variables — both persist in the REPL and apply to later `bash()` calls through POSIX process inheritance (since each bash call is a fresh process, Python does not inherit environment variables from bash).\n- Edits of existing files must be performed using `edit` with exact old/new strings; if the text contains triple double quotes (\"\"\"), the agent should use triple single-quoted variables or build `old`/`new` from inspected file slices.\n- Agents use Python for reading files and searching in them — it gives them reusable variables they can slice, filter, and act on without re-reading; using Python variables to find or produce, and to save the strings used in `edit` is also encouraged.\n- Agents always assign read/search results to named variables so they can revisit them later.\n- Agents must report assumptions they made and constants they changed to the user.\n- When an agent is done, they stop calling tools and state their final answer.\n- When delegation is available and useful, an agent assigns independent substantive tasks to separate workers. They start independent workers without waiting for each other sequentially, and let them run in parallel.\n- Agents do not keep the turn open by polling with `time.sleep()` or shell `sleep`, and they do not replace polling with a long blocking `await`. They await only the short operation needed to start work or inspect a result that is already available; otherwise they end the turn.\n- Agents use the Python REPL to keep intermediate variables, inspect and transform outputs, and write small helper functions.\n- Since compaction removes individual variables whose serialized form exceeds 16 MiB, agents can keep large source data on disk and reload it when needed.\n- Python is the orchestration language: agents use Python for loops, conditionals, parsing, and state. They use `bash()` to invoke programs, not to write shell programs, shell loops, or heredocs; those are done directly in Python.\n- Agents do not assume the REPL is the native runtime of the external thing being investigated. A repository, package, service, dataset, paper, website, benchmark, or API may have its own environment and normal interface. Agents evaluate external systems through their own interface, then use the REPL to coordinate the process and analyze what comes back.\n- Agents do not install dependencies into the kernel just to make an external project import or run there. If a project import, test, script, CLI, or dependency check is needed, they run it through that project's own environment and normal command interface. For example, in a Python repo use its documented commands, `uv run ...`, `.venv/bin/python ...`, or the active project interpreter from the repo root. Agents treat failures from that native environment as the relevant result.\n- Rules for root agents (depth 0):\n - Only message siblings if you are certain that it is necessary.\n - When work follows a plan, uses many subagents, or spans multiple turns, proactively give regular concise progress updates so the user does not have to ask. State the current plan, what has completed, any blockers, the proposed fixes, and the next actions. Lead with user-visible outcomes rather than internal process or gate names. Mention internal details only when they explain a blocker or decision. Send an update at meaningful milestones and before ending a turn while work is still running. Do not repeat unchanged status or interrupt short work with unnecessary updates.\n- Terminology: continual harness names the persisted prompt, memory, skill, and subagent layer; RLM names the runtime, Python REPL kernel, and native call interface exposed to the model.\n- Agents treat continual harness refinement as a small, evidence-backed update after observing a repeated failure or reusable tactic: they diagnose the issue, update the smallest relevant continual harness component, validate on the next action, then record the outcome. They use `await refine.run()` to turn repeated delegation patterns into reusable subagent specs, repeated procedures into skills, durable facts/preferences into memories, and narrow behavioral policies into prompt addendums. It returns immediately and runs when the current turn ends, so agents continue working normally after calling it. Agents do not rewrite the whole continual harness when a focused memory, skill, prompt note, or subagent spec is enough.\n- Instructions to agents for multi-agent work:\n - When spawning a subagent, keep the handle to stop or inspect the child later.\n - Ask for an explicit reply when needed; not every message needs a reply.\n - Use `await rlm.list_subagents()` after kernel restart or compaction.\n - Have children write files and read those files for fan-in.\n - Delegate parallel context-heavy research or independent implementation; do a single known lookup, edit, or command inline.\n\nThe following guidelines to agents have been shown to improve results on average. Agents should consider using them where appropriate. Clear user instructions always override these defaults.\n\n- Agents can use the following patterns to make better use of the REPL:\n - Write wrappers around `rlm.spawn` to have quick templates for subagents with arbitrary args: for text to programmatically pass and put into the prompt, for conditional behavior prompts, etc.\n - Use f-strings (`f\"\"\"...\"\"\"` or `f\"...\"`) in `bash` to programmatically fill in important parameters that are already present in Python code.\n- When writing or explaining something:\n - Agents use simplified technical English by default for user-facing prose: short sentences, common words, and concrete verbs; one main action or fact per sentence when practical; lists for steps or conditions. Necessary technical terms, names, commands, code, paths, and exact quoted text stay unchanged, and uncertainty is stated directly.\n - Agents use ordinary or established wording. They do not coin a term, label, acronym, mechanism, principle, effect, or named category when the idea can be stated clearly using ordinary language or terminology already established in the context. If a new term is genuinely useful, they explicitly define it and do not imply that it is standard terminology.\n - Agents keep names and terms consistent. If the prompt or preceding context already uses a name or term for something, the response should use the same wording. Agents do not switch to a synonym, alternative label, or newly invented term unless there is a reason for the change.\n- Agents take care and effort to avoid the following pitfalls while coding:\n - over-engineered solutions\n - overly defensive programming\n - hyper-fixation on rare/fictitious edge cases\n - overlapping subsystem responsibilities\n - solving problems at the wrong architectural layer\n - duplication of sources of truth, then inventing machinery to synchronize them\n - prematurely generalizing one-off flows\n - timeouts on everything\n - production code that exists purely to satisfy tests\n - patching bad premises additively instead of stepping back and deleting or adjusting them\n - tests for magic strings\n - excessive tests\n - comments that describe anything already described by the code\n - comments narrating the coding process instead of supporting the written code\n - fallbacks, legacy support, compatibility shims where not strictly needed; when in doubt, these should be discussed with the user\n - in UI, descriptions on everything\n\nPre-installed Python packages: requests, httpx, yaml (PyYAML), tomli, dotenv (python-dotenv), pandas, numpy, scipy, bs4 (Beautiful Soup), lxml, pydantic, tyro.\nInstall additional packages with `uv pip install <pkg>` (this is a uv-managed venv with no pip module).\n\nThe following skills provide specialized instructions for specific tasks.\nUse ipython to inspect a skill's file when the task matches its description.\nSkills with a python_import are prepared in the persistent Python kernel when available and can be called directly by that import name.\nWhen a skill file references a relative path, resolve it against the skill directory (parent of SKILL.md / dirname of the path) and use that absolute path in tool commands.\n\n<available_skills>\n <skill>\n <name>agent-message</name>\n <type>python</type>\n <python_import>agent_message</python_import>\n <description>Message an agent&apos;s parent, siblings, or direct children through the daemon. Discover reachable agents with agent_observe.list_agents, then send direct text without spoofing sender identity.</description>\n <location><skills-dir>/agent-message/SKILL.md</location>\n </skill>\n <skill>\n <name>agent-observe</name>\n <type>python</type>\n <python_import>agent_observe</python_import>\n <description>Read-only roster and observation of an agent&apos;s parent, siblings, and direct children. Use to discover reachable agents and to inspect family status and bounded recent-message previews without mutating sessions.</description>\n <location><skills-dir>/agent-observe/SKILL.md</location>\n </skill>\n <skill>\n <name>attach-image</name>\n <type>python</type>\n <python_import>attach_image</python_import>\n <description>Load an on-disk image (PNG, JPEG, GIF, WebP) into the model&apos;s context as a viewable attachment so the model can directly SEE it — for screenshots, diagrams, charts, photos, or scanned pages. Use this when you need to perceive an image&apos;s visual contents. Requires a vision-capable model; errors clearly otherwise.</description>\n <location><skills-dir>/attach-image/SKILL.md</location>\n </skill>\n <skill>\n <name>compact</name>\n <type>python</type>\n <python_import>compact</python_import>\n <description>Check context usage and compact the conversation from the Python REPL. Use when context is filling up and substantial work remains, so the session is summarized and you keep working instead of stopping early.</description>\n <location><skills-dir>/compact/SKILL.md</location>\n </skill>\n <skill>\n <name>edit</name>\n <type>python</type>\n <python_import>edit</python_import>\n <description>Replace an exact, unique string in an existing file. Use for targeted single-occurrence edits to files from the Python kernel instead of rewriting the whole file.</description>\n <location><skills-dir>/edit/SKILL.md</location>\n </skill>\n <skill>\n <name>goal</name>\n <type>python</type>\n <python_import>goal</python_import>\n <description>Manage the persistent thread goal from the Python REPL. Use to read goal status and budget usage, to start a goal when the user explicitly asks for one, or to mark the active goal complete once its objective is fully achieved.</description>\n <location><skills-dir>/goal/SKILL.md</location>\n </skill>\n <skill>\n <name>mcp</name>\n <type>markdown</type>\n <description>Use external MCP services generically from Python - search the supported-service catalog, inspect the user&apos;s connections, discover live tool schemas, and call tools on any connection (Notion, Linear, Slack, and the rest of the catalog) without per-service packages.</description>\n <location><skills-dir>/mcp/SKILL.md</location>\n </skill>\n <skill>\n <name>prime-intellect</name>\n <type>markdown</type>\n <description>Work with Prime Intellect products via the prime CLI and Python SDKs - verifiers environments and the Environments Hub, evaluations (local and hosted), Hosted Training and prime-rl, code sandboxes, Prime Inference, GPU compute (pods and clusters), storage, and tunnels. Use when a task involves Prime Intellect, the prime CLI, verifiers, RL environments, evals, training, sandboxes, renting GPUs, Prime Inference models, or when the user asks what Prime Intellect is or what it offers.</description>\n <location><skills-dir>/prime-intellect/SKILL.md</location>\n </skill>\n <skill>\n <name>refine</name>\n <type>python</type>\n <python_import>refine</python_import>\n <description>Trigger continual harness refinement from the Python REPL. Use when you notice a repeated failure, reusable tactic, delegation role, or behavior policy that should be persisted as a harness entry. Returns immediately; refinement runs when the current turn ends.</description>\n <location><skills-dir>/refine/SKILL.md</location>\n </skill>\n <skill>\n <name>rlm-heartbeat</name>\n <type>python</type>\n <python_import>rlm_heartbeat</python_import>\n <description>Manage agent-owned RLM heartbeats from the Python REPL. Use when the user asks the agent to start, create, schedule, or manage a heartbeat, unless they explicitly request the user&apos;s /heartbeat.</description>\n <location><skills-dir>/rlm-heartbeat/SKILL.md</location>\n </skill>\n <skill>\n <name>skill-creator</name>\n <type>markdown</type>\n <description>Create, validate, and install Prime Agent skills - both markdown skills and Python-backed skills callable from the Python kernel. Use when the user asks to create a skill, turn a workflow, script, or prompt into a reusable skill, add a Python skill the agent can call, or asks how to write a SKILL.md and where skills live.</description>\n <location><skills-dir>/skill-creator/SKILL.md</location>\n </skill>\n <skill>\n <name>websearch</name>\n <type>python</type>\n <python_import>websearch</python_import>\n <description>Search Google via the Serper API. Configure access via /mcp, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.</description>\n <location><skills-dir>/websearch/SKILL.md</location>\n </skill>\n</available_skills>\n\nCurrent date: <date>\nWorking directory: /w\nConversation log: /w/sessions/fixture-session.jsonl\n\nRecursive agent depth: 0 (root)"
}
diff --git a/crates/pa-daemon/README.md b/crates/pa-daemon/README.md
index 8f3386182b..38d297d965 100644
--- a/crates/pa-daemon/README.md
+++ b/crates/pa-daemon/README.md
@@ -271,7 +271,7 @@ attached UIs daemon-wide).
No agent behavior inside workers beyond hosting a pa-core engine; no UI.
## Public API
-Supervisor entrypoint, worker entrypoint, `mcp_login::{WorkerMcpLoginUi, wire_worker_mcp_login}` (the worker's browser+callback login behind `mcp.begin_login`; wired by the agent engine before sessions register host handlers), client connection API for pa-tui/pa-cli, `acp::{run_acp_mode, AcpOptions}` (pa-cli dispatches `--mode acp` through it), `agent_messaging::LinkAgentMessageController` + `rlm_children::{SupervisorChildSessions, ParentIdentity, RlmChildIdentity}` (e2e verifiers construct the worker-side family controller and the children registry; the engine wires the same types), `agent_engine::AgentSessionEngine::dispose_kernel` (the session-end kernel teardown the worker invokes at kill/shutdown/orphan exit — the engine outlives the session, so the pa-core engine-drop teardown cannot run there), the worker's `get_mcp_connections` command (`mcp_connections.rs`: the `/mcp` view's roster from the session's MCP manager overlaid with the session kernel's per-server tool listing — Rust-native session-plane extension; the TS daemon has no counterpart). Supervision internals `pub(crate)`.
+Supervisor entrypoint, worker entrypoint, `mcp_login::{WorkerMcpLoginUi, wire_worker_mcp_login}` (the worker's browser+callback login behind `mcp.begin_login`; wired by the agent engine before sessions register host handlers), client connection API for pa-tui/pa-cli, `acp::{run_acp_mode, AcpOptions}` (pa-cli dispatches `--mode acp` through it), `agent_messaging::LinkAgentMessageController` + `rlm_children::{SupervisorChildSessions, ParentIdentity, RlmChildIdentity}` (e2e verifiers construct the worker-side family controller and the children registry; the engine wires the same types), `agent_engine::AgentSessionEngine::dispose_kernel` (the session-end kernel teardown the worker invokes at kill/shutdown/orphan exit — the engine outlives the session, so the pa-core engine-drop teardown cannot run there), the worker's `get_mcp_connections` command (`mcp_connections.rs`: the `/mcp` view's roster from the session's MCP manager overlaid with the session kernel's per-server tool listing, plus the api-key credential rows the same response serves — Rust-native session-plane extension; the TS daemon has no counterpart). Supervision internals `pub(crate)`.
## Depends on
diff --git a/crates/pa-daemon/src/mcp_connections.rs b/crates/pa-daemon/src/mcp_connections.rs
index 23d7981208..e8cd17692f 100644
--- a/crates/pa-daemon/src/mcp_connections.rs
+++ b/crates/pa-daemon/src/mcp_connections.rs
@@ -1,10 +1,11 @@
-//! The worker arm behind the `get_mcp_connections` command: the roster
-//! and the resolved service catalog the interactive client's `/mcp`
-//! view renders — every configured connection (built-in catalog plus
-//! user-declared servers) with its connected state, and the
-//! service-catalog cards over the same fresh local state (the TS picker
-//! builds both from local reads on every open, never a kernel
-//! round-trip; connected rows carry their record-held tool count).
+//! The worker arm behind the `get_mcp_connections` command: the roster,
+//! the resolved service catalog, and the api-key credential catalog the
+//! interactive client's `/mcp` view renders — every configured connection
+//! (built-in catalog plus user-declared servers) with its connected state,
+//! the service-catalog cards and the stored-key credentials over the same
+//! fresh local state (the TS picker builds both from local reads on every
+//! open, never a kernel round-trip; connected rows carry their record-held
+//! tool count).
use serde_json::{json, Value};
@@ -13,14 +14,17 @@ use crate::worker::Worker;
impl Worker {
/// `get_mcp_connections`: the roster from the session's MCP manager
- /// (auth gating over settings plus the built-in catalog) and the
- /// resolved service-catalog views, from ONE fresh local read — the
- /// manager re-resolves its integrations and catalog first (TS
+ /// (auth gating over settings plus the built-in catalog), the resolved
+ /// service-catalog views, and the api-key credential rows (the stored
+ /// keys the `/mcp` view manages alongside the connections), from ONE
+ /// fresh local read — the manager reloads the auth store and
+ /// re-resolves its integrations and catalog first (TS
/// `buildServiceCatalogViews` re-reads the store and re-resolves the
- /// catalog on every open), so an externally changed settings file or
- /// a record another process wrote is visible on the next open. The
- /// roster read gates through the auth store, whose snapshot takes a
- /// blocking lock — never on the runtime.
+ /// catalog on every open), so an externally changed settings file, a
+ /// record another process wrote, or a key the interactive client just
+ /// stored is visible on the next open. The roster and credential reads
+ /// gate through the auth store, whose snapshot takes a blocking lock —
+ /// never on the runtime.
pub(crate) async fn handle_get_mcp_connections(&self) -> DaemonResponse {
if let Err(response) = self.require_created("get_mcp_connections") {
return response;
@@ -34,38 +38,47 @@ impl Worker {
);
};
let roster_manager = std::sync::Arc::clone(&manager);
- let (roster, services, diagnostics) = match tokio::task::spawn_blocking(move || {
- let mut manager = roster_manager.lock().unwrap();
- manager.refresh();
- (
- manager.connection_roster(),
- manager.service_catalog_views(),
- manager.service_catalog_diagnostics().to_vec(),
- )
- })
- .await
- {
- Ok(read) => read,
- Err(error) => {
- return response_failure(
- None,
- "get_mcp_connections",
- &format!("MCP roster read failed: {error}"),
- None,
- );
- }
- };
+ let (roster, services, credentials, diagnostics) =
+ match tokio::task::spawn_blocking(move || {
+ let mut manager = roster_manager.lock().unwrap();
+ // The auth store re-read comes FIRST: the interactive client
+ // stores the api-key credentials through its own storage
+ // instance (the `/mcp` key flow runs client-side), so the
+ // view's reads must reload the store to see them.
+ manager.reload_auth_storage();
+ manager.refresh();
+ (
+ manager.connection_roster(),
+ manager.service_catalog_views(),
+ manager.api_key_credential_views(),
+ manager.service_catalog_diagnostics().to_vec(),
+ )
+ })
+ .await
+ {
+ Ok(read) => read,
+ Err(error) => {
+ return response_failure(
+ None,
+ "get_mcp_connections",
+ &format!("MCP roster read failed: {error}"),
+ None,
+ );
+ }
+ };
let connections: Vec<Value> = roster
.into_iter()
.map(|entry| serde_json::to_value(&entry).unwrap_or(Value::Null))
.collect();
let services = serde_json::to_value(&services).unwrap_or(Value::Array(Vec::new()));
+ let credentials = serde_json::to_value(&credentials).unwrap_or(Value::Array(Vec::new()));
response_success(
None,
"get_mcp_connections",
Some(json!({
"connections": connections,
"services": services,
+ "credentials": credentials,
"catalogDiagnostics": diagnostics,
})),
)
diff --git a/crates/pa-daemon/tests/mcp_catalog_e2e.rs b/crates/pa-daemon/tests/mcp_catalog_e2e.rs
index 7ba60fd3c8..73c9c6be7f 100644
--- a/crates/pa-daemon/tests/mcp_catalog_e2e.rs
+++ b/crates/pa-daemon/tests/mcp_catalog_e2e.rs
@@ -347,6 +347,21 @@ fn catalog_surfaces_and_paste_installs_through_the_daemon() {
github["pasteToken"], true,
"github is pasteable (alias pair)"
);
+ // The api-key credential section serves the stored-key rows the view
+ // manages alongside the connections: the web-search entry, honestly
+ // unconfigured in the fresh agent dir.
+ let credentials = roster["data"]["credentials"]
+ .as_array()
+ .unwrap_or_else(|| panic!("credentials array: {roster}"));
+ let serper = credentials
+ .iter()
+ .find(|credential| credential["id"] == "serper")
+ .expect("the web-search credential row");
+ assert_eq!(serper["label"], "Serper (web search)");
+ assert_eq!(
+ serper["configured"], false,
+ "a fresh agent dir holds no serper key"
+ );
// The paste flow installs end-to-end: the credential is stored bound to
// the service endpoint and a record is persisted; verification against
diff --git a/crates/pa-tui/README.md b/crates/pa-tui/README.md
index 8a02bb2e90..6d7d4c1b62 100644
--- a/crates/pa-tui/README.md
+++ b/crates/pa-tui/README.md
@@ -3,7 +3,7 @@
The terminal UI.
## Scope
-Rendering (markdown, themes, layout, tool panels, custom-message decorated rows: the agent-message summary rows render the viewer-relative notice (the shared `Agent message` label, the ↑ sent/queued and ↓ received arrows from the row's actual direction, the counterpart agent's name only, no collapsed body preview — the operator's 2026-09-25 directive), and the ipython cell renders the sent/queued receipt rows below the code, and the RLM child rows render the outcome diamond rows — accent diamond, semantic label colors, the failure error and the cancellation reason as the expandable body; the skill-invocation card — TS `SkillInvocationMessageComponent`: a user message whose text is one `<skill ...>` block renders the `[skill] <name>` card collapsed, the `**<name>**` + content markdown expanded over the shared `pa_types::skill_blocks` parse, and the trailing invocation args as their own user block), the working loader row (activity label, TS `formatWorkingElapsed`, and the tool-owned working note during python-kernel boot, sourced from `starting` tool partials), image support (the terminal-image library: capability detection, Kitty/iTerm2 protocol encoders, dimension parsing; the image component with the fullscreen compose fallback; `terminal.showImages` gating of tool-result image rows; clipboard image paste behind `app.clipboard.pasteImage` with `[image #N]` editor markers, byte-budgeted registry, and wire-image attach), editor (cursor/kill-ring/undo/history/word ops, with the live prompt highlight: argument tokens in their TS colors on every line and the first line's slash-command token in accent for any recognized builtin command (sanctioned divergence, operator ruling 2026-09-29: TS accents argument-taking commands only) — suppressed while the cursor sits inside it, TS `CustomEditor.styleDisplayText`), the transcript prompt-highlight surfaces (TS `PromptTokenMask`: the user-message block masks its accent command segment and argument tokens to same-width private-use placeholders before the markdown layout and restores them after, TS `UserMessageComponent`; the session-command echo row styles the typed command the TS `SlashCommandMessageComponent` way — accent command segment, colored tokens, styled wrap), and the suspend-to-background cycle (`app.suspend`, default ctrl+z, TS `handleCtrlZ`: SIGINT ignored for the stopped window, the TUI stopped with the terminal handed to the shell, the process group SIGTSTP'd; the SIGCONT resume re-applies raw mode, the alternate screen, and SGR mouse tracking — the terminal modes a suspend cycle can lose), keybindings (user-editable via `~/.prime/agent/keybindings.json`: TS parse/migration/merge semantics — legacy id migration on load and at startup, malformed values dropped, empty-array disables, same-scope default eviction, conflicts, case/order-insensitive matching — the effective set wired into every hint, handler, and picker), autocomplete (slash commands, path completion, and the `@` fuzzy file search: a parallel `ignore` walk with fd's semantics, off the UI thread), fullscreen/scrollback (the wheel-scroll surface: SGR mouse-report decoding, `?1002`+`?1006` tracking enabled blind at the fullscreen surface's entry and released on exit/suspend — tmux never answers DECRQM, unsupporting terminals ignore the mode-sets — wheel turns scroll the transcript three lines, consumed without scrolling while a picker owns the frame or when the `terminal.fullscreenMouse` setting disabled tracking; in-frame click/drag selection stays unported), input handling, and the double-Ctrl+C force-quit guard (the exit contract: two in-window Ctrl+C presses end the process within 1.5s of the second press regardless of daemon or loop state; cleanup inside that window is best-effort). Interactive sessions attached through the daemon: the prompt stash (TS `prompt-stash-state.ts`: the client-owned per-session draft store shared across a TUI process's chat views — a draft left behind on a session switch returns to the editor when the session's chat reopens, its pasted images rehydrated behind their markers; the capture on the agents-view handoffs (`/resume`, the rebound `app.session.resume` key, the scoped view, `/resume <selector>`) and the in-place `/switch`, the restore on reopen/switch-back, and the queued-stash semantics for multi-switch chains; the manual `app.prompt.stash` capture (default ctrl+s, TS `handlePromptStash`): the key stashes the live draft and clears the editor, restores it on the next press, and a manually stashed draft returns only on that key — never on a reopen or a switch landing), the JSONL client socket (hello handshake, command envelopes, session-event loop), slim-attach snapshot reconstruction, the direct worker link loss path (a killed/crashed worker tears the link; the UI re-attaches through the supervisor with the TS reconnect surface - the `Daemon connection lost; reconnecting…` warning, the resync, `Daemon reconnected`, the 60s TS window with TS backoff, and the terminal `⚠ Error: Daemon reconnection failed: <last>` arm with dispatch blocked so the UI never rides a silent spinner), prompt submission with streamed assistant output, live session list and switch, the inline pickers (`/model`: the TS inline menu-panel - the bordered `Search models` field, `>`-marker rows with the effort-square cluster and `current · require sign in · provider` trailing, the price detail block, and the model/effort key hint - over the catalog the daemon's `get_model_catalog` refresh supplies (bundled + models.json fallback), with the TS sort chain, the scored fuzzy filter, left/right effort adjustment, and apply through the daemon `set_model` command (plus `set_thinking_level` for a user-edited effort) with the `Model: <id>` status row; `/effort`: the session's thinking levels from `get_state`, the unsupported-model note, and apply through `set_thinking_level`; `/mcp`: the inline connections view over the daemon's `get_mcp_connections` roster - the TS MCP-Connections-tab panel (bordered `Search MCP connections` field, `›` rows with the status flush right on connected entries, the selected connection's detail block with its tool listing, the navigate/select/close hint), Enter resolving to the selected connection's login command through the interactive loop's client-command seam); `/heartbeats`: the inline management view (TS `HeartbeatManagerComponent`, inline-picker style per the lane directive): the session-scoped user and agent heartbeat catalog from the selector-less supervisor `heartbeats_list` — scoped like TS `scopeHeartbeatsToSession` to this session and its roster descendants — with the TS count label, `›` rows with status-colored trailing, the selection's detail line, the actions pane (pause/resume/stop through `heartbeat_manage`), the fetch/action error rows, the `heartbeats_changed` broadcast refresh through the update channel, and the tray heartbeat label `N heartbeats · M paused (Ctrl+R)`; ctrl+r (`app.heartbeats.open`) opens it from anywhere), the TS `showStatus` back-to-back rewrite (a status emitted with nothing after the previous one rewrites it in place), the session export and share commands (`/export [path]`: the path-argument parse, the `.jsonl` branch switch, the daemon-side `export_html`/`export_jsonl` requests, and the `Session exported to:` row; `/share`: the gh auth gate, the temp export, the background `gh gist create` run behind the bordered `Creating gist...` loader with Esc cancel, and the `Share URL:`/`Gist:` rows - the gist provider is the GitHub CLI exactly like TS), the visible follow-up queue (TS `queuedMessagesContainer`): prompts parked behind a running turn render as dim preview rows above the prompt dock with the TS prompt-highlight styling (accent on a leading slash command's `/name` segment, `success`/`mdLink` on `@path`/`--flag` argument tokens — TS `styleQueuedMessagePreview`) — `Steering:`/`Follow-up:` labels with the `╰─ <key> to browse and edit queued messages` hint, re-synced from `state.sessionActions` on attach and kept live by `session_action_update`; the queued internal prompts (heartbeat fires, agent messages, goal contexts, background-command notices) condense into one counted row below the human previews — "1 agent message, 1 heartbeat, and 1 other internal prompt queued": each origin's own count, singular/plural-correct, zero-count origins omitted (sanctioned divergence, operator requests 2026-09-24 + 2026-09-25: TS renders every internal prompt as its own preview row; the browse/edit affordances still walk every queued item, so only the strip rows condense — the four TS-internal labels classify by preview string, TS `isLabeledQueuedPreview`, the queue wire carries no provenance for them, so a human-typed prompt that begins with one of the internal labels classifies internal for the strip too: it still delivers, and the browse/edit affordance walks and shows it; the parked RLM child status notices — the `[child-exited: ...]`/`[child-failed ...]` lifecycle rows the queue-fold operator bug 2026-09-25 flooded the strip with — classify by WIRE-TYPED provenance instead, never by their text: the worker's `sessionActions.rlmChildStatus` rider carries the parked injected rows' lane indices, they count as their own origin ("N child status notices"), and a user-typed lookalike stays a human row); the collapsed conversation view (operator directive 2026-09-28, the undo of the 2026-09-25 condensed-run summary block): the collapse mode renders every activity item exactly as `details` does - every tool card, every notice, every agent-message row - with ONLY the thinking blocks hidden (the TS fork's shape), a chat starts at that collapsed level, and the Ctrl+O cycle from there is the thinking-visibility toggle (overview -> details -> all -> overview unchanged; a card click toggles only the clicked card's own expansion - TS's per-component `expanded` - and the Ctrl+O cycle resets every card to the new level) - purely render-time over the unchanged transcript model (no session jsonl schema change, no stored-event change); the follow-up key (`app.message.followUp`, default alt+enter) parks a submission on the follow-up lane (`streamingBehavior: "followUp"` + `queueIfBusy`), Enter on the steering lane; the browse affordances TS gives the rows (TS `QueueSelection` port): alt+up/alt+down walk the parked messages newest-first with the editor draft stashed and restored, the dim browse header (lane, index, key hints) renders as the editor box header row, Enter steers the edit (replace/move to steering, empty deletes), the follow-up key re-parks it, ctrl+alt+arrows reorder through `mutate_queued_message` (mirrored locally like TS — the event can land after the response), the clear key restores the draft, and queue-change statuses surface the TS status rows verbatim; and the utility slash commands (TS `dispatch_client_command` arms): `/btw`+`/side` (the side-question pane over the daemon `start_side_question`/`abort_side_question` flow — the popup-surface turns with the `/btw` header, follow-up bubbles, the slash/image rejection notices, the running/return hint rows, Esc cancel; replies while the pane is open seed follow-ups from the answered turns), `/fast` (the priority-tier toggle with the TS eligibility check and unavailable status), `/rlm-max-depth` (view/set with the `--global` arm and the TS status rows), `/name`+`/rename` (the daemon `set_session_name` rename whose persisted `session_info` entry and `session_info_changed` broadcast the daemon owns), `/settings` (the TS `SettingsList` grouped into tabs — the spaced tab strip (white-bold active tab) over label/value rows with descriptions, ←/→/Enter/Space value cycling (the arrows step a row's options in place; Tab/Shift+Tab and the number keys move the tabs), the detail block's separator rule and description-matched hint padding, the thinking/theme/warnings/service-tier submenus with the theme's live preview and restore, type-to-search; daemon switches for autocompact/steering/follow-up/transport/thinking, the client-settings seam for the persisted preferences), and `/reload` (the TS guards, the bordered reload box, the daemon reload request, keybinding/theme/catalog re-reads, and the outcome row); `/thinking` rides the registry alias into `/effort`. The client-settings seam (`client_settings::ClientSettings`, implemented by the composition root) is how pa-tui persists user preferences without a pa-core dependency; the autocomplete listing drops `/fast` when the current model is not fast-mode-eligible (the pa-types `supports_fast_mode` helper), the subagent summary line under the tray (TS `SubagentSummaryLine`: live descendant counts from the roster subscription, the dock renders in every session, all-zero included (the operator's 2026-09-28 directive; TS renders nothing at zero, a sanctioned divergence), and its Subagents group opens the scoped agents view even with no children, which shows the view's `No sessions yet.` empty state, the focus hand-off from the editor — Down at the end of the prompt or `app.subagents.focus` — the focused key contract — confirm/open into the focused group's own view, left/right stepping every rendered group (an empty one included, wrapping at the row's ends — the operator's 2026-09-26 muscle-memory directive), up/cancel/back to the editor, expand keeping the focus, other keys releasing it into the editor path — and the scoped-view hand-off; every dock panel's exit (ESC/left from the heartbeats view, the bash view, the goal panel, or the scoped agents view's back keys) restores the dock's focus on the panel's own group instead of the prompt bar — the operator's 2026-09-26 panel-exit ruling; TS has no multi-group dock, its panels close to the editor, a sanctioned divergence); and the agents view (the unified live-roster +saved-catalog session list: Running/Idle/Inactive sections, inline search(TS query language: case-insensitive substring tokens, `"quoted phrases"`,
+Rendering (markdown, themes, layout, tool panels, custom-message decorated rows: the agent-message summary rows render the viewer-relative notice (the shared `Agent message` label, the ↑ sent/queued and ↓ received arrows from the row's actual direction, the counterpart agent's name only, no collapsed body preview — the operator's 2026-09-25 directive), and the ipython cell renders the sent/queued receipt rows below the code, and the RLM child rows render the outcome diamond rows — accent diamond, semantic label colors, the failure error and the cancellation reason as the expandable body; the skill-invocation card — TS `SkillInvocationMessageComponent`: a user message whose text is one `<skill ...>` block renders the `[skill] <name>` card collapsed, the `**<name>**` + content markdown expanded over the shared `pa_types::skill_blocks` parse, and the trailing invocation args as their own user block), the working loader row (activity label, TS `formatWorkingElapsed`, and the tool-owned working note during python-kernel boot, sourced from `starting` tool partials), image support (the terminal-image library: capability detection, Kitty/iTerm2 protocol encoders, dimension parsing; the image component with the fullscreen compose fallback; `terminal.showImages` gating of tool-result image rows; clipboard image paste behind `app.clipboard.pasteImage` with `[image #N]` editor markers, byte-budgeted registry, and wire-image attach), editor (cursor/kill-ring/undo/history/word ops, with the live prompt highlight: argument tokens in their TS colors on every line and the first line's slash-command token in accent for any recognized builtin command (sanctioned divergence, operator ruling 2026-09-29: TS accents argument-taking commands only) — suppressed while the cursor sits inside it, TS `CustomEditor.styleDisplayText`), the transcript prompt-highlight surfaces (TS `PromptTokenMask`: the user-message block masks its accent command segment and argument tokens to same-width private-use placeholders before the markdown layout and restores them after, TS `UserMessageComponent`; the session-command echo row styles the typed command the TS `SlashCommandMessageComponent` way — accent command segment, colored tokens, styled wrap), and the suspend-to-background cycle (`app.suspend`, default ctrl+z, TS `handleCtrlZ`: SIGINT ignored for the stopped window, the TUI stopped with the terminal handed to the shell, the process group SIGTSTP'd; the SIGCONT resume re-applies raw mode, the alternate screen, and SGR mouse tracking — the terminal modes a suspend cycle can lose), keybindings (user-editable via `~/.prime/agent/keybindings.json`: TS parse/migration/merge semantics — legacy id migration on load and at startup, malformed values dropped, empty-array disables, same-scope default eviction, conflicts, case/order-insensitive matching — the effective set wired into every hint, handler, and picker), autocomplete (slash commands, path completion, and the `@` fuzzy file search: a parallel `ignore` walk with fd's semantics, off the UI thread), fullscreen/scrollback (the wheel-scroll surface: SGR mouse-report decoding, `?1002`+`?1006` tracking enabled blind at the fullscreen surface's entry and released on exit/suspend — tmux never answers DECRQM, unsupporting terminals ignore the mode-sets — wheel turns scroll the transcript three lines, consumed without scrolling while a picker owns the frame or when the `terminal.fullscreenMouse` setting disabled tracking; in-frame click/drag selection stays unported), input handling, and the double-Ctrl+C force-quit guard (the exit contract: two in-window Ctrl+C presses end the process within 1.5s of the second press regardless of daemon or loop state; cleanup inside that window is best-effort). Interactive sessions attached through the daemon: the prompt stash (TS `prompt-stash-state.ts`: the client-owned per-session draft store shared across a TUI process's chat views — a draft left behind on a session switch returns to the editor when the session's chat reopens, its pasted images rehydrated behind their markers; the capture on the agents-view handoffs (`/resume`, the rebound `app.session.resume` key, the scoped view, `/resume <selector>`) and the in-place `/switch`, the restore on reopen/switch-back, and the queued-stash semantics for multi-switch chains; the manual `app.prompt.stash` capture (default ctrl+s, TS `handlePromptStash`): the key stashes the live draft and clears the editor, restores it on the next press, and a manually stashed draft returns only on that key — never on a reopen or a switch landing), the JSONL client socket (hello handshake, command envelopes, session-event loop), slim-attach snapshot reconstruction, the direct worker link loss path (a killed/crashed worker tears the link; the UI re-attaches through the supervisor with the TS reconnect surface - the `Daemon connection lost; reconnecting…` warning, the resync, `Daemon reconnected`, the 60s TS window with TS backoff, and the terminal `⚠ Error: Daemon reconnection failed: <last>` arm with dispatch blocked so the UI never rides a silent spinner), prompt submission with streamed assistant output, live session list and switch, the inline pickers (`/model`: the TS inline menu-panel - the bordered `Search models` field, `>`-marker rows with the effort-square cluster and `current · require sign in · provider` trailing, the price detail block, and the model/effort key hint - over the catalog the daemon's `get_model_catalog` refresh supplies (bundled + models.json fallback), with the TS sort chain, the scored fuzzy filter, left/right effort adjustment, and apply through the daemon `set_model` command (plus `set_thinking_level` for a user-edited effort) with the `Model: <id>` status row; `/effort`: the session's thinking levels from `get_state`, the unsupported-model note, and apply through `set_thinking_level`; `/mcp`: the inline connections view over the daemon's `get_mcp_connections` roster - the TS MCP-Connections-tab panel (bordered `Search MCP connections` field, `›` rows with the status flush right on connected entries, the selected connection's detail block with its tool listing, the navigate/select/close hint), Enter resolving to the selected connection's login command through the interactive loop's client-command seam, plus the api-key credential rows the same response serves (the stored keys, e.g. the web-search one; Enter runs the paste-the-key prompt, a rust-only surface - the operator's `/login`-is-providers-only ruling moved the key here, TS still serves it on its `/login` MCP tab); `/heartbeats`: the inline management view (TS `HeartbeatManagerComponent`, inline-picker style per the lane directive): the session-scoped user and agent heartbeat catalog from the selector-less supervisor `heartbeats_list` — scoped like TS `scopeHeartbeatsToSession` to this session and its roster descendants — with the TS count label, `›` rows with status-colored trailing, the selection's detail line, the actions pane (pause/resume/stop through `heartbeat_manage`), the fetch/action error rows, the `heartbeats_changed` broadcast refresh through the update channel, and the tray heartbeat label `N heartbeats · M paused (Ctrl+R)`; ctrl+r (`app.heartbeats.open`) opens it from anywhere), the TS `showStatus` back-to-back rewrite (a status emitted with nothing after the previous one rewrites it in place), the session export and share commands (`/export [path]`: the path-argument parse, the `.jsonl` branch switch, the daemon-side `export_html`/`export_jsonl` requests, and the `Session exported to:` row; `/share`: the gh auth gate, the temp export, the background `gh gist create` run behind the bordered `Creating gist...` loader with Esc cancel, and the `Share URL:`/`Gist:` rows - the gist provider is the GitHub CLI exactly like TS), the visible follow-up queue (TS `queuedMessagesContainer`): prompts parked behind a running turn render as dim preview rows above the prompt dock with the TS prompt-highlight styling (accent on a leading slash command's `/name` segment, `success`/`mdLink` on `@path`/`--flag` argument tokens — TS `styleQueuedMessagePreview`) — `Steering:`/`Follow-up:` labels with the `╰─ <key> to browse and edit queued messages` hint, re-synced from `state.sessionActions` on attach and kept live by `session_action_update`; the queued internal prompts (heartbeat fires, agent messages, goal contexts, background-command notices) condense into one counted row below the human previews — "1 agent message, 1 heartbeat, and 1 other internal prompt queued": each origin's own count, singular/plural-correct, zero-count origins omitted (sanctioned divergence, operator requests 2026-09-24 + 2026-09-25: TS renders every internal prompt as its own preview row; the browse/edit affordances still walk every queued item, so only the strip rows condense — the four TS-internal labels classify by preview string, TS `isLabeledQueuedPreview`, the queue wire carries no provenance for them, so a human-typed prompt that begins with one of the internal labels classifies internal for the strip too: it still delivers, and the browse/edit affordance walks and shows it; the parked RLM child status notices — the `[child-exited: ...]`/`[child-failed ...]` lifecycle rows the queue-fold operator bug 2026-09-25 flooded the strip with — classify by WIRE-TYPED provenance instead, never by their text: the worker's `sessionActions.rlmChildStatus` rider carries the parked injected rows' lane indices, they count as their own origin ("N child status notices"), and a user-typed lookalike stays a human row); the collapsed conversation view (operator directive 2026-09-28, the undo of the 2026-09-25 condensed-run summary block): the collapse mode renders every activity item exactly as `details` does - every tool card, every notice, every agent-message row - with ONLY the thinking blocks hidden (the TS fork's shape), a chat starts at that collapsed level, and the Ctrl+O cycle from there is the thinking-visibility toggle (overview -> details -> all -> overview unchanged; a card click toggles only the clicked card's own expansion - TS's per-component `expanded` - and the Ctrl+O cycle resets every card to the new level) - purely render-time over the unchanged transcript model (no session jsonl schema change, no stored-event change); the follow-up key (`app.message.followUp`, default alt+enter) parks a submission on the follow-up lane (`streamingBehavior: "followUp"` + `queueIfBusy`), Enter on the steering lane; the browse affordances TS gives the rows (TS `QueueSelection` port): alt+up/alt+down walk the parked messages newest-first with the editor draft stashed and restored, the dim browse header (lane, index, key hints) renders as the editor box header row, Enter steers the edit (replace/move to steering, empty deletes), the follow-up key re-parks it, ctrl+alt+arrows reorder through `mutate_queued_message` (mirrored locally like TS — the event can land after the response), the clear key restores the draft, and queue-change statuses surface the TS status rows verbatim; and the utility slash commands (TS `dispatch_client_command` arms): `/btw`+`/side` (the side-question pane over the daemon `start_side_question`/`abort_side_question` flow — the popup-surface turns with the `/btw` header, follow-up bubbles, the slash/image rejection notices, the running/return hint rows, Esc cancel; replies while the pane is open seed follow-ups from the answered turns), `/fast` (the priority-tier toggle with the TS eligibility check and unavailable status), `/rlm-max-depth` (view/set with the `--global` arm and the TS status rows), `/name`+`/rename` (the daemon `set_session_name` rename whose persisted `session_info` entry and `session_info_changed` broadcast the daemon owns), `/settings` (the TS `SettingsList` grouped into tabs — the spaced tab strip (white-bold active tab) over label/value rows with descriptions, ←/→/Enter/Space value cycling (the arrows step a row's options in place; Tab/Shift+Tab and the number keys move the tabs), the detail block's separator rule and description-matched hint padding, the thinking/theme/warnings/service-tier submenus with the theme's live preview and restore, type-to-search; daemon switches for autocompact/steering/follow-up/transport/thinking, the client-settings seam for the persisted preferences), and `/reload` (the TS guards, the bordered reload box, the daemon reload request, keybinding/theme/catalog re-reads, and the outcome row); `/thinking` rides the registry alias into `/effort`. The client-settings seam (`client_settings::ClientSettings`, implemented by the composition root) is how pa-tui persists user preferences without a pa-core dependency; the autocomplete listing drops `/fast` when the current model is not fast-mode-eligible (the pa-types `supports_fast_mode` helper), the subagent summary line under the tray (TS `SubagentSummaryLine`: live descendant counts from the roster subscription, the dock renders in every session, all-zero included (the operator's 2026-09-28 directive; TS renders nothing at zero, a sanctioned divergence), and its Subagents group opens the scoped agents view even with no children, which shows the view's `No sessions yet.` empty state, the focus hand-off from the editor — Down at the end of the prompt or `app.subagents.focus` — the focused key contract — confirm/open into the focused group's own view, left/right stepping every rendered group (an empty one included, wrapping at the row's ends — the operator's 2026-09-26 muscle-memory directive), up/cancel/back to the editor, expand keeping the focus, other keys releasing it into the editor path — and the scoped-view hand-off; every dock panel's exit (ESC/left from the heartbeats view, the bash view, the goal panel, or the scoped agents view's back keys) restores the dock's focus on the panel's own group instead of the prompt bar — the operator's 2026-09-26 panel-exit ruling; TS has no multi-group dock, its panels close to the editor, a sanctioned divergence); and the agents view (the unified live-roster +saved-catalog session list: Running/Idle/Inactive sections, inline search(TS query language: case-insensitive substring tokens, `"quoted phrases"`,
`re:` regex, capped fuzzy fallback; the corpus is deliberately restricted to
the session name, the durable session id, and the cwd — the TS corpus fields
(first/last messages, the capped saved transcript, and
diff --git a/crates/pa-tui/src/client_auth.rs b/crates/pa-tui/src/client_auth.rs
index 5dd16ef7c5..19246dbe18 100644
--- a/crates/pa-tui/src/client_auth.rs
+++ b/crates/pa-tui/src/client_auth.rs
@@ -1,10 +1,11 @@
//! Client-side MCP auth commands: the interactive surface behind
//! `/mcp login <name>` and `/mcp logout <name>` (the TS interactive
//! client's MCP login/logout branches, which run the OAuth flow in the
-//! client process and persist through the shared auth store). The TUI
-//! owns the command UX and the inline auth panel; the composition root
-//! runs the flow against it (pa-core owns the flow — this crate stays
-//! pa-types-only).
+//! client process and persist through the shared auth store) plus the
+//! `/mcp` view's api-key credential flow (`key <id>`, the view's stored
+//! keys such as the web-search one). The TUI owns the command UX and the
+//! inline auth panel; the composition root runs the flow against it
+//! (pa-core owns the flow — this crate stays pa-types-only).
use std::pin::Pin;
use std::sync::Arc;
@@ -25,6 +26,11 @@ pub trait ClientAuthCommands: Send + Sync {
/// it bound to the service endpoint, and verify. Resolves with the
/// status line (TS: `Connected <name>.`).
fn paste_token(&self, server: &str, panel: crate::auth_panel::AuthPanelHandle) -> AuthFuture;
+ /// The api-key credential flow (the `/mcp` view's stored keys, e.g.
+ /// the web-search one): prompt (masked) for one pasted key and store
+ /// it in the credential's auth slot — the slot the runtime reads.
+ /// Resolves with the status line to show.
+ fn api_key(&self, credential: &str, panel: crate::auth_panel::AuthPanelHandle) -> AuthFuture;
/// Remove a stored MCP credential. Resolves with the status line
/// (TS: `<name> is not connected.` / `Disconnected <name>.`).
fn logout(&self, server: &str) -> AuthFuture;
@@ -41,12 +47,12 @@ impl std::fmt::Debug for ClientAuthCommandsHandle {
}
}
-/// Run `/mcp login` / `/mcp logout` against the hook and return the note
-/// line to show (status, surfaced error, or the TS usage wording).
-/// Argument shapes and wording follow the TS interactive client's
-/// `handleMcpCommand` login/logout branches. The login and paste flows
-/// drive the inline auth `panel` (the TUI mounts it before spawning the
-/// flow).
+/// Run `/mcp login` / `/mcp key` / `/mcp logout` against the hook and
+/// return the note line to show (status, surfaced error, or the TS usage
+/// wording). Argument shapes and wording follow the TS interactive
+/// client's `handleMcpCommand` login/logout branches. The login, paste,
+/// and key flows drive the inline auth `panel` (the TUI mounts it before
+/// spawning the flow).
pub async fn run_mcp_auth_command(
auth: &dyn ClientAuthCommands,
args: &str,
@@ -64,6 +70,10 @@ pub async fn run_mcp_auth_command(
Ok(status) => status,
Err(error) => format!("{error:#}"),
},
+ (Some("key"), Some(credential), true) => match auth.api_key(credential, panel).await {
+ Ok(status) => status,
+ Err(error) => format!("{error:#}"),
+ },
(Some("logout"), Some(server), true) => match auth.logout(server).await {
Ok(status) => status,
Err(error) => format!("{error:#}"),
@@ -74,10 +84,14 @@ pub async fn run_mcp_auth_command(
(Some("paste"), _, false) | (Some("paste"), None, true) => {
"Usage: /mcp paste <name> (a requires-setup token service)".to_string()
}
+ (Some("key"), _, false) | (Some("key"), None, true) => {
+ "Usage: /mcp key <name> (an api-key credential)".to_string()
+ }
(Some("logout"), _, false) | (Some("logout"), None, true) => {
"Usage: /mcp logout <name>".to_string()
}
- _ => "Usage: /mcp login <name> | /mcp paste <name> | /mcp logout <name>".to_string(),
+ _ => "Usage: /mcp login <name> | /mcp paste <name> | /mcp key <name> | /mcp logout <name>"
+ .to_string(),
}
}
@@ -121,6 +135,19 @@ mod tests {
Box::pin(async move { Ok(answer) })
}
+ fn api_key(
+ &self,
+ credential: &str,
+ _panel: crate::auth_panel::AuthPanelHandle,
+ ) -> AuthFuture {
+ self.log
+ .lock()
+ .unwrap()
+ .push(("key".to_string(), credential.to_string()));
+ let answer = format!("Saved API key for {credential}.");
+ Box::pin(async move { Ok(answer) })
+ }
+
fn logout(&self, server: &str) -> AuthFuture {
self.log
.lock()
@@ -149,6 +176,15 @@ mod tests {
Box::pin(async move { Err(error) })
}
+ fn api_key(
+ &self,
+ credential: &str,
+ _panel: crate::auth_panel::AuthPanelHandle,
+ ) -> AuthFuture {
+ let error = anyhow::anyhow!("Unknown api-key credential: {credential}");
+ Box::pin(async move { Err(error) })
+ }
+
fn logout(&self, _server: &str) -> AuthFuture {
Box::pin(async move { Err(anyhow::anyhow!("boom")) })
}
@@ -175,6 +211,19 @@ mod tests {
("logout".to_string(), "notion".to_string()),
]
);
+ // The api-key credential dispatch (the `/mcp` view's key rows).
+ assert_eq!(
+ run_mcp_auth_command(&auth, "key serper", panel()).await,
+ "Saved API key for serper."
+ );
+ assert_eq!(
+ run_mcp_auth_command(&auth, "key", panel()).await,
+ "Usage: /mcp key <name> (an api-key credential)"
+ );
+ assert_eq!(
+ run_mcp_auth_command(&auth, "key a b", panel()).await,
+ "Usage: /mcp key <name> (an api-key credential)"
+ );
// TS usage wording: missing server, extra args, unknown subcommand.
assert_eq!(
run_mcp_auth_command(&auth, "login", panel()).await,
@@ -190,16 +239,20 @@ mod tests {
);
assert_eq!(
run_mcp_auth_command(&auth, "", panel()).await,
- "Usage: /mcp login <name> | /mcp paste <name> | /mcp logout <name>"
+ "Usage: /mcp login <name> | /mcp paste <name> | /mcp key <name> | /mcp logout <name>"
);
assert_eq!(
run_mcp_auth_command(&auth, "add http://x", panel()).await,
- "Usage: /mcp login <name> | /mcp paste <name> | /mcp logout <name>"
+ "Usage: /mcp login <name> | /mcp paste <name> | /mcp key <name> | /mcp logout <name>"
);
// Errors surface with their chain.
assert_eq!(
run_mcp_auth_command(&FailingAuth, "login nope", panel()).await,
"Unknown MCP integration: nope"
);
+ assert_eq!(
+ run_mcp_auth_command(&FailingAuth, "key nope", panel()).await,
+ "Unknown api-key credential: nope"
+ );
}
}
diff --git a/crates/pa-tui/src/mcp_view.rs b/crates/pa-tui/src/mcp_view.rs
index 8244396705..1c503a9d47 100644
--- a/crates/pa-tui/src/mcp_view.rs
+++ b/crates/pa-tui/src/mcp_view.rs
@@ -1,13 +1,15 @@
//! The `/mcp` view: the TS `ServiceCatalogPickerComponent`'s catalog
//! surface — the resolved service catalog's cards (catalog services plus
-//! user-declared servers, connected-first) over the daemon's
+//! user-declared servers, connected-first) and the api-key credential
+//! rows (the stored keys, e.g. the web-search key) over the daemon's
//! `get_mcp_connections` response, with the TS picker's search bands,
//! ONE fixed detail line, and the navigate/action/close hint. Enter runs
-//! the connection's login flow (TS `onSelect` -> `authenticate`); Esc
-//! closes. The panel is the same inline shape as the `/model` picker
-//! (the bordered search field over `›`-marker rows), and its frame is
-//! budgeted so the dock can never overflow the terminal (the detail line
-//! drops when the viewport is too short, never the search field).
+//! the connection's login flow (TS `onSelect` -> `authenticate`) or the
+//! credential's paste-the-key prompt; Esc closes. The panel is the same
+//! inline shape as the `/model` picker (the bordered search field over
+//! `›`-marker rows), and its frame is budgeted so the dock can never
+//! overflow the terminal (the detail line drops when the viewport is too
+//! short, never the search field).
use crate::keybindings::{format_key_text, KeybindingsManager};
use crate::menu_panel::{menu_list_layout, search_field_lines};
@@ -17,6 +19,10 @@ use crate::{Line, Span};
use serde_json::Value;
+mod rows;
+
+use rows::{flatten_to_single_line, McpCredentialRow, McpRow, McpServiceRow};
+
/// The search field's placeholder (TS `MenuSearchInput("Search MCP
/// connections")`).
const SEARCH_PLACEHOLDER: &str = "Search MCP connections";
@@ -51,261 +57,6 @@ const MIN_ROWS_FOR_DETAIL: usize =
/// the hint): the layout must budget them before the message renders.
const EMPTY_STATE_ROWS: usize = 2;
-/// One service-catalog card (the daemon's resolved `services` array; TS
-/// `McpPluginView`): a catalog service or a user-declared server with its
-/// honestly-computed connection state.
-#[derive(Debug, Clone, PartialEq)]
-pub struct McpServiceRow {
- pub service_id: String,
- pub label: String,
- pub connection_status: String,
- pub connectable: bool,
- pub login_pending: bool,
- pub uses_oauth: bool,
- pub source: String,
- pub connection_ids: Vec<String>,
- /// The paste-panel marker: a requires-setup token service collecting
- /// exactly one credential. Never a connected/verified claim.
- pub paste_token: bool,
- pub aliases: Vec<String>,
- pub description: Option<String>,
- pub category: Option<String>,
- pub publisher: Option<String>,
- pub docs_url: Option<String>,
- pub setup_hint: Option<String>,
- pub tool_count: Option<usize>,
- pub verified_at: Option<u64>,
-}
-
-impl McpServiceRow {
- /// Parse one legacy roster entry (a daemon that predates the catalog
- /// surface serves only `connections`): the row keeps the roster's
- /// honest connected state; a not-connected row stays connectable.
- fn from_roster_entry(value: &Value) -> Option<Self> {
- let connected = value
- .get("connected")
- .and_then(Value::as_bool)
- .unwrap_or(false);
- Some(McpServiceRow {
- service_id: value.get("server")?.as_str()?.to_string(),
- label: value
- .get("label")
- .and_then(Value::as_str)
- .unwrap_or_default()
- .to_string(),
- connection_status: if connected {
- "connected"
- } else {
- "not_connected"
- }
- .to_string(),
- connectable: !connected,
- login_pending: false,
- uses_oauth: value
- .get("usesOAuth")
- .and_then(Value::as_bool)
- .unwrap_or(false),
- source: "catalog".to_string(),
- connection_ids: Vec::new(),
- paste_token: false,
- aliases: Vec::new(),
- description: None,
- category: None,
- publisher: None,
- docs_url: None,
- setup_hint: None,
- tool_count: None,
- verified_at: None,
- })
- }
-
- /// Parse one daemon `services` entry.
- fn from_value(value: &Value) -> Option<Self> {
- let connection_ids = value
- .get("connectionIds")
- .and_then(Value::as_array)
- .map(|ids| {
- ids.iter()
- .filter_map(Value::as_str)
- .map(str::to_string)
- .collect()
- })
- .unwrap_or_default();
- Some(McpServiceRow {
- service_id: value.get("serviceId")?.as_str()?.to_string(),
- label: value
- .get("label")
- .and_then(Value::as_str)
- .unwrap_or_default()
- .to_string(),
- connection_status: value
- .get("connectionStatus")
- .and_then(Value::as_str)
- .unwrap_or("not_connected")
- .to_string(),
- connectable: value
- .get("connectable")
- .and_then(Value::as_bool)
- .unwrap_or(false),
- login_pending: value
- .get("loginPending")
- .and_then(Value::as_bool)
- .unwrap_or(false),
- uses_oauth: value
- .get("usesOAuth")
- .and_then(Value::as_bool)
- .unwrap_or(false),
- source: value
- .get("source")
- .and_then(Value::as_str)
- .unwrap_or("catalog")
- .to_string(),
- connection_ids,
- paste_token: value
- .get("pasteToken")
- .and_then(Value::as_bool)
- .unwrap_or(false),
- aliases: value
- .get("aliases")
- .and_then(Value::as_array)
- .map(|aliases| {
- aliases
- .iter()
- .filter_map(Value::as_str)
- .map(str::to_string)
- .collect()
- })
- .unwrap_or_default(),
- description: value
- .get("description")
- .and_then(Value::as_str)
- .map(str::to_string),
- category: value
- .get("category")
- .and_then(Value::as_str)
- .map(str::to_string),
- publisher: value
- .get("publisher")
- .and_then(Value::as_str)
- .map(str::to_string),
- docs_url: value
- .get("docsUrl")
- .and_then(Value::as_str)
- .map(str::to_string),
- setup_hint: value
- .get("setupHint")
- .and_then(Value::as_str)
- .map(str::to_string),
- tool_count: value
- .get("toolCount")
- .and_then(Value::as_u64)
- .map(|c| c as usize),
- verified_at: value.get("verifiedAt").and_then(Value::as_u64),
- })
- }
-
- /// The trailing status text (TS `statusText`, catalog mode): the honest
- /// state vocabulary, with the record-carried tool count on connected
- /// rows (the picker reads local state only, like TS).
- fn status_text(&self) -> (ThemeColor, String) {
- if self.login_pending {
- return (ThemeColor::Warning, "Login in progress".to_string());
- }
- match self.connection_status.as_str() {
- "connected" => (
- ThemeColor::Success,
- match self.tool_count {
- Some(tool_count) => format!("Connected \u{b7} {tool_count} tools"),
- None => "Connected".to_string(),
- },
- ),
- "pending" => (ThemeColor::Warning, "Needs verification".to_string()),
- "error" => (
- ThemeColor::Error,
- if self.connectable {
- "Reconnect"
- } else {
- "Needs attention"
- }
- .to_string(),
- ),
- "setup_required" => (ThemeColor::Warning, "Requires setup".to_string()),
- "disabled" => (ThemeColor::Muted, "Disabled".to_string()),
- _ => (
- if self.connectable {
- ThemeColor::Text
- } else {
- ThemeColor::Muted
- },
- if self.connectable {
- "Connect"
- } else {
- "Not connected"
- }
- .to_string(),
- ),
- }
- }
-
- /// The selected row's detail copy (TS `secondaryText`, catalog mode):
- /// the honest setup guidance for setup-required/error rows, the
- /// description otherwise.
- fn detail_text(&self) -> Option<String> {
- if self.connection_status == "setup_required" || self.connection_status == "error" {
- self.setup_hint.clone().or_else(|| self.description.clone())
- } else {
- self.description.clone().or_else(|| self.setup_hint.clone())
- }
- }
-
- /// The rendered row's primary line (TS `MenuRow` primary: the
- /// label alone, flattened).
- fn primary_line(&self) -> String {
- flatten_to_single_line(&self.label)
- }
-
- /// The action target (the service id).
- fn target(&self) -> &str {
- self.service_id.as_str()
- }
-
- /// The paste-panel decision (TS: a requires-setup token service with
- /// exactly one credential and no installed account).
- fn wants_paste(&self) -> bool {
- self.paste_token && self.connection_ids.is_empty()
- }
-
- /// The Enter action hint (TS `actionText`, catalog mode, in the TS
- /// order): the paste step for pasteable token services, the accounts
- /// step for rows with an account, `manage` for user-declared
- /// non-OAuth servers, then the connection-state verbs.
- fn action_text(&self) -> &'static str {
- if self.paste_token && self.connection_ids.is_empty() {
- return "paste token";
- }
- if !self.connection_ids.is_empty() {
- return "manage accounts";
- }
- if self.source == "user" && !self.uses_oauth {
- return "manage";
- }
- match self.connection_status.as_str() {
- "connected" => "re-verify",
- "pending" => "verify",
- _ if !self.connectable => "setup guidance",
- "error" => "reconnect",
- _ => "connect",
- }
- }
-}
-
-/// Flatten all whitespace runs to one space (TS `flattenToSingleLine`):
-/// catalog copy routinely contains newlines, and a rendered row must stay
-/// exactly one terminal line.
-fn flatten_to_single_line(text: &str) -> String {
- text.split_whitespace().collect::<Vec<_>>().join(" ")
-}
-
// Search bands (TS `service-catalog-picker.ts`): lower scores rank
// first; identity fields (label, service id, aliases) always outrank
// description/setup-hint text. The fractional tiebreaks are the TS
@@ -428,7 +179,7 @@ fn description_match_score(text: &str, token: &str) -> Option<f64> {
/// every token must match somewhere; each token's best field score is
/// summed into the row's total. Identity fields first; the
/// description/setup-hint band only when no identity field matched.
-fn service_search_score(service: &McpServiceRow, query: &str) -> Option<f64> {
+fn row_search_score(row: &McpRow, query: &str) -> Option<f64> {
let query = query.trim().to_lowercase();
let tokens: Vec<&str> = query
.split_whitespace()
@@ -440,16 +191,13 @@ fn service_search_score(service: &McpServiceRow, query: &str) -> Option<f64> {
let mut total = 0.0;
for token in tokens {
let mut best: Option<f64> = None;
- for field in std::iter::once(&service.label)
- .chain(std::iter::once(&service.service_id))
- .chain(service.aliases.iter())
- {
+ for field in row.identity_fields() {
if let Some(score) = identity_match_score(field, token) {
best = Some(best.map_or(score, |current| current.min(score)));
}
}
if best.is_none() {
- for field in service.description.iter().chain(service.setup_hint.iter()) {
+ for field in row.description_fields() {
if let Some(score) = description_match_score(field, token) {
best = Some(best.map_or(score, |current| current.min(score)));
}
@@ -473,6 +221,12 @@ pub enum McpViewAction {
/// the paste flow (TS `actionText` "paste token"). `label` is the
/// service's display name (the panel's title reads "Connect {label}").
Paste { server: String, label: String },
+ /// Enter on an api-key credential row (the stored keys the view
+ /// manages alongside the connections): open the paste-the-key prompt
+ /// (the panel's masked paste field). `id` is the credential's auth
+ /// slot, `label` its display name (the panel's title reads "Connect
+ /// {label}").
+ Key { id: String, label: String },
/// Esc, Ctrl+C, or back: close without selecting.
Cancel,
/// Navigation or search editing only.
@@ -481,11 +235,12 @@ pub enum McpViewAction {
/// The `/mcp` service-catalog view: the resolved catalog's cards (the
/// TS `ServiceCatalogPickerComponent`'s catalog surface — every resolved
-/// service plus user-declared servers, connected-first) with the TS
-/// picker's search bands and one fixed detail line.
+/// service plus user-declared servers, connected-first) and the api-key
+/// credential rows, with the TS picker's search bands and one fixed
+/// detail line.
#[derive(Debug)]
pub struct McpView {
- rows: Vec<McpServiceRow>,
+ rows: Vec<McpRow>,
search: SearchInput,
filtered: Vec<usize>,
selected: usize,
@@ -496,9 +251,11 @@ pub struct McpView {
impl McpView {
/// Build the view over the daemon's `get_mcp_connections` response:
- /// the resolved `services` cards (the catalog surface). The response
- /// carries no live tool listing — the picker opens from this local
- /// state exactly like TS, so the open is instant.
+ /// the resolved `services` cards (the catalog surface) plus the
+ /// `credentials` rows (the api-key entries the view manages alongside
+ /// the connections). The response carries no live tool listing — the
+ /// picker opens from this local state exactly like TS, so the open is
+ /// instant.
pub fn from_response(data: &Value, viewport_rows: usize) -> Self {
let services: Vec<McpServiceRow> = data
.get("services")
@@ -510,23 +267,37 @@ impl McpView {
.collect()
})
.unwrap_or_default();
- // The catalog cards own the rows when the daemon serves them (TS
- // `buildPluginViews` already includes user-declared servers); a
- // daemon that predates the catalog surface serves only the legacy
- // `connections` roster, and its rows render from the roster.
- let rows = if services.is_empty() {
+ let credentials: Vec<McpCredentialRow> = data
+ .get("credentials")
+ .and_then(Value::as_array)
+ .map(|entries| {
+ entries
+ .iter()
+ .filter_map(McpCredentialRow::from_value)
+ .collect()
+ })
+ .unwrap_or_default();
+ // The catalog cards own the service rows when the daemon serves
+ // them (TS `buildPluginViews` already includes user-declared
+ // servers); a daemon that predates the catalog surface serves only
+ // the legacy `connections` roster, and its rows render from the
+ // roster. The credential rows ride after the cards (the api-key
+ // class the view serves alongside the connections).
+ let mut rows: Vec<McpRow> = if services.is_empty() {
data.get("connections")
.and_then(Value::as_array)
.map(|entries| {
entries
.iter()
.filter_map(McpServiceRow::from_roster_entry)
+ .map(McpRow::Service)
.collect()
})
.unwrap_or_default()
} else {
- services
+ services.into_iter().map(McpRow::Service).collect()
};
+ rows.extend(credentials.into_iter().map(McpRow::Credential));
let mut view = McpView {
rows,
search: SearchInput::new(),
@@ -540,11 +311,12 @@ impl McpView {
view
}
- /// The selected row's action target (Enter's service id).
+ /// The selected row's action target (Enter's service id, or the
+ /// credential's auth slot).
pub fn selected_server(&self) -> Option<&str> {
self.rows
.get(*self.filtered.get(self.selected)?)
- .map(McpServiceRow::target)
+ .map(McpRow::target)
}
/// One key press (TS `ServiceCatalogPickerComponent.handleInput`):
@@ -588,13 +360,19 @@ impl McpView {
.get(self.selected)
.and_then(|index| self.rows.get(*index));
return match selected_row {
- Some(row) if row.wants_paste() => McpViewAction::Paste {
- server: row.target().to_string(),
- label: row.label.clone(),
+ // The credential rows route to the paste-the-key prompt
+ // (a configured row's Enter replaces the stored key).
+ Some(McpRow::Credential(credential)) => McpViewAction::Key {
+ id: credential.id.clone(),
+ label: credential.label.clone(),
+ },
+ Some(McpRow::Service(service)) if service.wants_paste() => McpViewAction::Paste {
+ server: service.target().to_string(),
+ label: service.label.clone(),
},
- Some(row) => McpViewAction::Select {
- server: row.target().to_string(),
- label: row.label.clone(),
+ Some(McpRow::Service(service)) => McpViewAction::Select {
+ server: service.target().to_string(),
+ label: service.label.clone(),
},
None => McpViewAction::None,
};
@@ -728,7 +506,7 @@ impl McpView {
.filtered
.get(self.selected)
.and_then(|index| self.rows.get(*index))
- .map(McpServiceRow::action_text);
+ .map(McpRow::action_text);
lines.push(hint_line(theme, width, kb, action));
lines
}
@@ -798,7 +576,7 @@ impl McpView {
.rows
.iter()
.enumerate()
- .filter_map(|(index, row)| Some((service_search_score(row, &trimmed)?, index)))
+ .filter_map(|(index, row)| Some((row_search_score(row, &trimmed)?, index)))
.collect();
scored.sort_by(|left, right| left.0.total_cmp(&right.0));
scored.into_iter().map(|(_, index)| index).collect()
diff --git a/crates/pa-tui/src/mcp_view/rows.rs b/crates/pa-tui/src/mcp_view/rows.rs
new file mode 100644
index 0000000000..ce986c0714
--- /dev/null
+++ b/crates/pa-tui/src/mcp_view/rows.rs
@@ -0,0 +1,398 @@
+//! The `/mcp` view's row model: the two row classes the daemon's
+//! `get_mcp_connections` response carries — the service-catalog cards
+//! (TS `McpPluginView`) and the api-key credential rows (the stored keys
+//! the view manages alongside the connections) — with their shared
+//! render/search projection (the label line, the trailing status, the
+//! detail copy, the Enter action hint, and the search-band fields).
+
+use serde_json::Value;
+
+use crate::theme::ThemeColor;
+
+/// One service-catalog card (the daemon's resolved `services` array; TS
+/// `McpPluginView`): a catalog service or a user-declared server with its
+/// honestly-computed connection state.
+#[derive(Debug, Clone, PartialEq)]
+pub(super) struct McpServiceRow {
+ pub service_id: String,
+ pub label: String,
+ pub connection_status: String,
+ pub connectable: bool,
+ pub login_pending: bool,
+ pub uses_oauth: bool,
+ pub source: String,
+ pub connection_ids: Vec<String>,
+ /// The paste-panel marker: a requires-setup token service collecting
+ /// exactly one credential. Never a connected/verified claim.
+ pub paste_token: bool,
+ pub aliases: Vec<String>,
+ pub description: Option<String>,
+ pub category: Option<String>,
+ pub publisher: Option<String>,
+ pub docs_url: Option<String>,
+ pub setup_hint: Option<String>,
+ pub tool_count: Option<usize>,
+ pub verified_at: Option<u64>,
+}
+
+impl McpServiceRow {
+ /// Parse one legacy roster entry (a daemon that predates the catalog
+ /// surface serves only `connections`): the row keeps the roster's
+ /// honest connected state; a not-connected row stays connectable.
+ pub(super) fn from_roster_entry(value: &Value) -> Option<Self> {
+ let connected = value
+ .get("connected")
+ .and_then(Value::as_bool)
+ .unwrap_or(false);
+ Some(McpServiceRow {
+ service_id: value.get("server")?.as_str()?.to_string(),
+ label: value
+ .get("label")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string(),
+ connection_status: if connected {
+ "connected"
+ } else {
+ "not_connected"
+ }
+ .to_string(),
+ connectable: !connected,
+ login_pending: false,
+ uses_oauth: value
+ .get("usesOAuth")
+ .and_then(Value::as_bool)
+ .unwrap_or(false),
+ source: "catalog".to_string(),
+ connection_ids: Vec::new(),
+ paste_token: false,
+ aliases: Vec::new(),
+ description: None,
+ category: None,
+ publisher: None,
+ docs_url: None,
+ setup_hint: None,
+ tool_count: None,
+ verified_at: None,
+ })
+ }
+
+ /// Parse one daemon `services` entry.
+ pub(super) fn from_value(value: &Value) -> Option<Self> {
+ let connection_ids = value
+ .get("connectionIds")
+ .and_then(Value::as_array)
+ .map(|ids| {
+ ids.iter()
+ .filter_map(Value::as_str)
+ .map(str::to_string)
+ .collect()
+ })
+ .unwrap_or_default();
+ Some(McpServiceRow {
+ service_id: value.get("serviceId")?.as_str()?.to_string(),
+ label: value
+ .get("label")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string(),
+ connection_status: value
+ .get("connectionStatus")
+ .and_then(Value::as_str)
+ .unwrap_or("not_connected")
+ .to_string(),
+ connectable: value
+ .get("connectable")
+ .and_then(Value::as_bool)
+ .unwrap_or(false),
+ login_pending: value
+ .get("loginPending")
+ .and_then(Value::as_bool)
+ .unwrap_or(false),
+ uses_oauth: value
+ .get("usesOAuth")
+ .and_then(Value::as_bool)
+ .unwrap_or(false),
+ source: value
+ .get("source")
+ .and_then(Value::as_str)
+ .unwrap_or("catalog")
+ .to_string(),
+ connection_ids,
+ paste_token: value
+ .get("pasteToken")
+ .and_then(Value::as_bool)
+ .unwrap_or(false),
+ aliases: value
+ .get("aliases")
+ .and_then(Value::as_array)
+ .map(|aliases| {
+ aliases
+ .iter()
+ .filter_map(Value::as_str)
+ .map(str::to_string)
+ .collect()
+ })
+ .unwrap_or_default(),
+ description: value
+ .get("description")
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ category: value
+ .get("category")
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ publisher: value
+ .get("publisher")
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ docs_url: value
+ .get("docsUrl")
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ setup_hint: value
+ .get("setupHint")
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ tool_count: value
+ .get("toolCount")
+ .and_then(Value::as_u64)
+ .map(|c| c as usize),
+ verified_at: value.get("verifiedAt").and_then(Value::as_u64),
+ })
+ }
+
+ /// The trailing status text (TS `statusText`, catalog mode): the honest
+ /// state vocabulary, with the record-carried tool count on connected
+ /// rows (the picker reads local state only, like TS).
+ fn status_text(&self) -> (ThemeColor, String) {
+ if self.login_pending {
+ return (ThemeColor::Warning, "Login in progress".to_string());
+ }
+ match self.connection_status.as_str() {
+ "connected" => (
+ ThemeColor::Success,
+ match self.tool_count {
+ Some(tool_count) => format!("Connected \u{b7} {tool_count} tools"),
+ None => "Connected".to_string(),
+ },
+ ),
+ "pending" => (ThemeColor::Warning, "Needs verification".to_string()),
+ "error" => (
+ ThemeColor::Error,
+ if self.connectable {
+ "Reconnect"
+ } else {
+ "Needs attention"
+ }
+ .to_string(),
+ ),
+ "setup_required" => (ThemeColor::Warning, "Requires setup".to_string()),
+ "disabled" => (ThemeColor::Muted, "Disabled".to_string()),
+ _ => (
+ if self.connectable {
+ ThemeColor::Text
+ } else {
+ ThemeColor::Muted
+ },
+ if self.connectable {
+ "Connect"
+ } else {
+ "Not connected"
+ }
+ .to_string(),
+ ),
+ }
+ }
+
+ /// The selected row's detail copy (TS `secondaryText`, catalog mode):
+ /// the honest setup guidance for setup-required/error rows, the
+ /// description otherwise.
+ pub(super) fn detail_text(&self) -> Option<String> {
+ if self.connection_status == "setup_required" || self.connection_status == "error" {
+ self.setup_hint.clone().or_else(|| self.description.clone())
+ } else {
+ self.description.clone().or_else(|| self.setup_hint.clone())
+ }
+ }
+
+ /// The action target (the service id).
+ pub(super) fn target(&self) -> &str {
+ self.service_id.as_str()
+ }
+
+ /// The paste-panel decision (TS: a requires-setup token service with
+ /// exactly one credential and no installed account).
+ pub(super) fn wants_paste(&self) -> bool {
+ self.paste_token && self.connection_ids.is_empty()
+ }
+
+ /// The Enter action hint (TS `actionText`, catalog mode, in the TS
+ /// order): the paste step for pasteable token services, the accounts
+ /// step for rows with an account, `manage` for user-declared
+ /// non-OAuth servers, then the connection-state verbs.
+ fn action_text(&self) -> &'static str {
+ if self.paste_token && self.connection_ids.is_empty() {
+ return "paste token";
+ }
+ if !self.connection_ids.is_empty() {
+ return "manage accounts";
+ }
+ if self.source == "user" && !self.uses_oauth {
+ return "manage";
+ }
+ match self.connection_status.as_str() {
+ "connected" => "re-verify",
+ "pending" => "verify",
+ _ if !self.connectable => "setup guidance",
+ "error" => "reconnect",
+ _ => "connect",
+ }
+ }
+}
+
+/// One api-key credential entry (the daemon's `credentials` array): a
+/// non-provider key the product stores in the shared auth store, offered
+/// alongside the MCP connections (the web-search key the websearch skill
+/// reads). Enter opens the paste-the-key prompt; the submitted key lands
+/// in the credential's auth slot.
+#[derive(Debug, Clone, PartialEq)]
+pub(super) struct McpCredentialRow {
+ pub(super) id: String,
+ pub(super) label: String,
+ configured: bool,
+}
+
+impl McpCredentialRow {
+ /// Parse one daemon `credentials` entry.
+ pub(super) fn from_value(value: &Value) -> Option<Self> {
+ Some(McpCredentialRow {
+ id: value.get("id")?.as_str()?.to_string(),
+ label: value
+ .get("label")
+ .and_then(Value::as_str)
+ .unwrap_or_default()
+ .to_string(),
+ configured: value
+ .get("configured")
+ .and_then(Value::as_bool)
+ .unwrap_or(false),
+ })
+ }
+
+ /// The trailing status (the provider-auth vocabulary): a stored key
+ /// reads `Configured`, an empty slot `Not configured`.
+ fn status_text(&self) -> (ThemeColor, String) {
+ if self.configured {
+ (ThemeColor::Success, "Configured".to_string())
+ } else {
+ (ThemeColor::Muted, "Not configured".to_string())
+ }
+ }
+
+ /// The Enter action hint: paste the key (a configured row's Enter
+ /// replaces the stored key the same way).
+ fn action_text(&self) -> &'static str {
+ if self.configured {
+ "replace key"
+ } else {
+ "add key"
+ }
+ }
+}
+
+/// One `/mcp` view row: a service-catalog card or an api-key credential
+/// (the two row classes the daemon's `get_mcp_connections` response
+/// carries).
+#[derive(Debug, Clone, PartialEq)]
+// The service card is the wide row (its catalog metadata); the credential
+// row is deliberately small. The rows are a per-open rendered list (a
+// handful of entries), never a hot data structure — boxing would spend a
+// deref on every render path for no measurable size win.
+#[allow(clippy::large_enum_variant)]
+pub(super) enum McpRow {
+ Service(McpServiceRow),
+ Credential(McpCredentialRow),
+}
+
+impl McpRow {
+ /// The rendered row's primary line (TS `MenuRow` primary: the label
+ /// alone, flattened).
+ pub(super) fn primary_line(&self) -> String {
+ flatten_to_single_line(match self {
+ McpRow::Service(service) => &service.label,
+ McpRow::Credential(credential) => &credential.label,
+ })
+ }
+
+ /// The action target (the service id or the credential's auth slot).
+ pub(super) fn target(&self) -> &str {
+ match self {
+ McpRow::Service(service) => service.service_id.as_str(),
+ McpRow::Credential(credential) => credential.id.as_str(),
+ }
+ }
+
+ /// The trailing status text (TS `statusText`): the honest state
+ /// vocabulary of the row's class.
+ pub(super) fn status_text(&self) -> (ThemeColor, String) {
+ match self {
+ McpRow::Service(service) => service.status_text(),
+ McpRow::Credential(credential) => credential.status_text(),
+ }
+ }
+
+ /// The selected row's detail copy (TS `secondaryText`): the honest
+ /// setup guidance for setup-required/error rows, the description
+ /// otherwise. A credential row carries none — the detail falls back
+ /// to its status (TS `secondaryText ?? statusText`).
+ pub(super) fn detail_text(&self) -> Option<String> {
+ match self {
+ McpRow::Service(service) => service.detail_text(),
+ McpRow::Credential(_) => None,
+ }
+ }
+
+ /// The Enter action hint (TS `actionText`).
+ pub(super) fn action_text(&self) -> &'static str {
+ match self {
+ McpRow::Service(service) => service.action_text(),
+ McpRow::Credential(credential) => credential.action_text(),
+ }
+ }
+
+ /// The identity fields the search bands rank first.
+ pub(super) fn identity_fields(&self) -> Vec<&str> {
+ match self {
+ McpRow::Service(service) => {
+ let mut fields = vec![service.label.as_str(), service.service_id.as_str()];
+ fields.extend(service.aliases.iter().map(String::as_str));
+ fields
+ }
+ McpRow::Credential(credential) => {
+ vec![credential.label.as_str(), credential.id.as_str()]
+ }
+ }
+ }
+
+ /// The description-band fields (matched only when no identity field
+ /// matched).
+ pub(super) fn description_fields(&self) -> Vec<&str> {
+ match self {
+ McpRow::Service(service) => service
+ .description
+ .iter()
+ .chain(service.setup_hint.iter())
+ .map(String::as_str)
+ .collect(),
+ McpRow::Credential(_) => Vec::new(),
+ }
+ }
+}
+
+/// Flatten all whitespace runs to one space (TS `flattenToSingleLine`):
+/// catalog copy routinely contains newlines, and a rendered row must stay
+/// exactly one terminal line.
+pub(super) fn flatten_to_single_line(text: &str) -> String {
+ text.split_whitespace().collect::<Vec<_>>().join(" ")
+}
diff --git a/crates/pa-tui/src/mcp_view/tests.rs b/crates/pa-tui/src/mcp_view/tests.rs
index 20e1575d65..e846982fbe 100644
--- a/crates/pa-tui/src/mcp_view/tests.rs
+++ b/crates/pa-tui/src/mcp_view/tests.rs
@@ -259,6 +259,106 @@ fn enter_routes_paste_and_connect() {
);
}
+/// A response with the api-key credential section (the daemon's
+/// `credentials` array: the stored keys the view manages alongside the
+/// connections).
+fn credentials_response() -> serde_json::Value {
+ let mut response = catalog_response();
+ response["credentials"] = json!([
+ {"id": "serper", "label": "Serper (web search)", "configured": false}
+ ]);
+ response
+}
+
+/// The api-key credential rows render alongside the connections: the row
+/// rides after the service cards, carries its honest status, and Enter
+/// routes to the paste-the-key flow.
+#[test]
+fn credential_rows_render_and_route() {
+ let mut view = McpView::from_response(&credentials_response(), 19);
+ // The credential row rides after the service cards.
+ assert_eq!(view.selected_server(), Some("fixture-echo"));
+ for _ in 0..4 {
+ view.handle_key("down", &kb());
+ }
+ assert_eq!(view.selected_server(), Some("serper"));
+ let rows = frame_text(&mut view);
+ let selected = rows
+ .iter()
+ .find(|row| row.starts_with("\u{203a}"))
+ .expect("selected row");
+ assert!(
+ selected.starts_with("\u{203a} Serper (web search)"),
+ "the credential row renders its label: {selected}"
+ );
+ assert!(
+ selected.ends_with("Not configured"),
+ "the unconfigured credential row keeps the honest status: {selected}"
+ );
+ // A credential row carries no description: the detail line falls back
+ // to its status (TS `secondaryText ?? statusText`).
+ assert!(
+ rows.iter().any(|row| row == " Not configured"),
+ "the detail line: {rows:?}"
+ );
+ assert_eq!(
+ rows.last().map(String::as_str),
+ Some(" \u{2191}/\u{2193} navigate \u{b7} Enter add key \u{b7} Esc close"),
+ "the hint names the add-key step"
+ );
+ assert_eq!(
+ view.handle_key("enter", &kb()),
+ McpViewAction::Key {
+ id: "serper".to_string(),
+ label: "Serper (web search)".to_string(),
+ }
+ );
+}
+
+/// A configured credential row reads `Configured` and its hint names the
+/// replace step (the same prompt replaces the stored key).
+#[test]
+fn a_configured_credential_names_the_replace_step() {
+ let mut response = credentials_response();
+ response["credentials"] = json!([
+ {"id": "serper", "label": "Serper (web search)", "configured": true}
+ ]);
+ let mut view = McpView::from_response(&response, 19);
+ for _ in 0..4 {
+ view.handle_key("down", &kb());
+ }
+ let rows = frame_text(&mut view);
+ let selected = rows
+ .iter()
+ .find(|row| row.starts_with("\u{203a}"))
+ .expect("selected row");
+ assert!(
+ selected.ends_with("Configured"),
+ "the configured status: {selected}"
+ );
+ assert_eq!(
+ rows.last().map(String::as_str),
+ Some(" \u{2191}/\u{2193} navigate \u{b7} Enter replace key \u{b7} Esc close"),
+ "the hint names the replace-key step"
+ );
+}
+
+/// The credential rows join the search: the identity fields (label, id)
+/// match, and a non-matching query filters them out.
+#[test]
+fn the_credential_rows_join_the_search() {
+ let mut view = McpView::from_response(&credentials_response(), 19);
+ view.set_search("serper");
+ assert_eq!(view.selected_server(), Some("serper"));
+ let rows = frame_text(&mut view);
+ assert!(
+ rows.iter().any(|row| row.contains("Serper (web search)")),
+ "the credential row matches its id: {rows:?}"
+ );
+ view.set_search("zzz");
+ assert_eq!(view.selected_server(), None);
+}
+
/// The TS navigation: arrows clamp at the list's bounds — up at the
/// first row stays there, down at the last row stays there (never the
/// wrap-around the port had).
@@ -373,18 +473,15 @@ fn search_scores_match_the_ts_bands() {
let row = |id: &str| {
view.rows
.iter()
- .find(|row| row.service_id == id)
+ .find(|row| row.target() == id)
.expect("row")
};
// The exact band.
- assert_eq!(
- service_search_score(row("linear"), "linear"),
- Some(SCORE_EXACT)
- );
+ assert_eq!(row_search_score(row("linear"), "linear"), Some(SCORE_EXACT));
// The prefix band: "linear" prefixes both; the remaining-length
// tiebreak scores the longer label.
assert_eq!(
- service_search_score(row("linear-support"), "linear"),
+ row_search_score(row("linear-support"), "linear"),
Some(SCORE_PREFIX + 8.0 * 0.01)
);
// The description band only when no identity field matched: a
@@ -395,7 +492,7 @@ fn search_scores_match_the_ts_bands() {
});
let github = McpServiceRow::from_value(&github).expect("row");
assert_eq!(
- service_search_score(&github, "linear"),
+ row_search_score(&McpRow::Service(github), "linear"),
Some(SCORE_DESCRIPTION_SUBSTRING + 4.0 * 0.01)
);
// The subsequence fallback with its run floor: "crdb"-style
@@ -405,10 +502,11 @@ fn search_scores_match_the_ts_bands() {
"description": "the SQL database"
});
let cockroach = McpServiceRow::from_value(&cockroach).expect("row");
- let score = service_search_score(&cockroach, "crdb");
+ let cockroach = McpRow::Service(cockroach);
+ let score = row_search_score(&cockroach, "crdb");
assert!(score.is_some(), "the tight abbreviation matches");
assert_eq!(
- service_search_score(&cockroach, "cxxx"),
+ row_search_score(&cockroach, "cxxx"),
None,
"the scattered match is rejected"
);
@@ -419,7 +517,7 @@ fn search_scores_match_the_ts_bands() {
});
let notion = McpServiceRow::from_value(&notion).expect("row");
assert_eq!(
- service_search_score(&notion, "notion workflows"),
+ row_search_score(&McpRow::Service(notion), "notion workflows"),
Some(SCORE_EXACT + SCORE_DESCRIPTION_WORD_START)
);
}
diff --git a/crates/pa-tui/src/session_ui/auth.rs b/crates/pa-tui/src/session_ui/auth.rs
index 2db2d95674..06be602b8b 100644
--- a/crates/pa-tui/src/session_ui/auth.rs
+++ b/crates/pa-tui/src/session_ui/auth.rs
@@ -551,6 +551,22 @@ impl SessionUi {
title: format!("Connect {label}"),
});
}
+ Some(crate::mcp_view::McpViewAction::Key { id, label }) => {
+ view.mcp_view = None;
+ self.dirty = true;
+ if self.picker_restored_draft {
+ self.picker_restored_draft = false;
+ } else {
+ view.editor.set_text("");
+ }
+ // The api-key credential's client surface: prompt for the
+ // key (masked), store it in the credential's auth slot —
+ // the exact contract the runtime reads.
+ self.pending_mcp_auth = Some(McpAuthIntent {
+ args: format!("key {id}"),
+ title: format!("Connect {label}"),
+ });
+ }
}
Ok(())
}
diff --git a/skills/websearch/SKILL.md b/skills/websearch/SKILL.md
index e919f5e41b..72f852a142 100644
--- a/skills/websearch/SKILL.md
+++ b/skills/websearch/SKILL.md
@@ -1,6 +1,6 @@
---
name: websearch
-description: Search Google via the Serper API. Configure access via /login, then MCP Connections, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.
+description: Search Google via the Serper API. Configure access via /mcp, then Serper (web search). Takes one query and returns titles, URLs, snippets, and knowledge-graph data.
---
# Web Search
@@ -9,8 +9,8 @@ Search the web via the Serper Google Search API.
## Setup
-Get a free API key at https://serper.dev, then run `/login` in Prime Agent,
-switch to **MCP Connections**, and choose **Serper (web search)** to paste it.
+Get a free API key at https://serper.dev, then run `/mcp` in Prime Agent and
+choose **Serper (web search)** to paste it.
The key is stored in Prime Agent and made available to this skill automatically.
If web search reports a missing key, walk the user through those two steps;
diff --git a/skills/websearch/src/websearch/websearch.py b/skills/websearch/src/websearch/websearch.py
index a4f5c14e1f..560233d12b 100644
--- a/skills/websearch/src/websearch/websearch.py
+++ b/skills/websearch/src/websearch/websearch.py
@@ -161,7 +161,7 @@ async def run(
"Web search is not set up yet: no Serper API key is configured.\n"
"Tell the user how to enable it:\n"
" 1. Get a free API key at https://serper.dev (sign up, copy the key).\n"
- " 2. In Prime Agent, run /login, switch to MCP Connections, choose \"Serper (web search)\", and paste the key.\n"
+ " 2. In Prime Agent, run /mcp, choose \"Serper (web search)\", and paste the key.\n"
"Do not ask the user to set environment variables. Once the key is saved, web search works automatically."
)