surjection-core 1.2.0

Core library of Surjection: MCP servers, skills and secret references for AI coding clients
Documentation
//! How each client signs in to a remote MCP server that uses OAuth (#47):
//! a login command, a step inside the client, a connector the client's
//! settings add, or none. Part of each adapter's [`McpSpec`]
//! (`sign_in`); [`SignIn::for_spec`] adds the rule for clients that run no
//! remote servers.
//!
//! A command or step is marked `verified` only when the client's official
//! documentation gives it (cited where each adapter sets it). Surjection
//! runs only a `verified` command, with the entry's name as its one
//! argument, never a secret.
//!
//! [`McpSpec`]: crate::adapters::McpSpec

use std::path::PathBuf;
use std::process::{Command, Stdio};
use std::time::{Duration, Instant};

use crate::adapters::AdapterSpec;
use crate::adapters::detect::find_executable;
use crate::diagnostics::log;
use crate::env::{Env, Os};
use crate::error::{CoreError, ErrorCode};
use crate::fs::Fs;
use crate::process::hide_window;

/// How a client signs in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SignInKind {
    /// A command signs in from a terminal (`codex mcp login <name>`).
    Command,
    /// The client signs in from its own window or session (`/mcp`).
    InClient,
    /// Remote servers are added and signed in to as connectors in the
    /// client's settings, not through its config file.
    Connector,
    /// The client cannot sign in to remote servers (it runs none).
    Unsupported,
}

impl SignInKind {
    pub const fn as_str(self) -> &'static str {
        match self {
            SignInKind::Command => "command",
            SignInKind::InClient => "in_client",
            SignInKind::Connector => "connector",
            SignInKind::Unsupported => "unsupported",
        }
    }
}

/// A client's way to sign in. `{name}` in `command` and `steps` stands for
/// the server's entry name in the client's file, `{client}` in `steps` for
/// the client's name.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SignIn {
    pub kind: SignInKind,
    /// The login command, program first ([`SignInKind::Command`]).
    pub command: Option<&'static [&'static str]>,
    pub steps: &'static str,
    /// The documentation page the command or steps come from.
    pub docs_url: Option<&'static str>,
    /// `command` and `steps` are confirmed by `docs_url`.
    pub verified: bool,
}

impl SignIn {
    /// A client whose sign-in is not documented here: it may ask by itself.
    pub const UNKNOWN: Self = Self {
        kind: SignInKind::InClient,
        command: None,
        steps: "If {client} supports OAuth for remote servers, it asks you to sign in when it \
                first connects to {name}. See its documentation.",
        docs_url: None,
        verified: false,
    };

    /// A client that runs no remote servers.
    pub const NO_REMOTE: Self = Self {
        kind: SignInKind::Unsupported,
        command: None,
        steps: "{client} does not run remote servers, so it cannot sign in to {name}.",
        docs_url: None,
        verified: false,
    };

    /// The sign-in of `spec`'s client: its own, or [`SignIn::NO_REMOTE`]
    /// when it runs neither http nor sse (unless its own is a connector).
    pub fn for_spec(spec: &AdapterSpec) -> Self {
        let Some(mcp) = spec.mcp.as_ref() else {
            return Self::NO_REMOTE;
        };
        let remote = mcp.caps.transports.http || mcp.caps.transports.sse;
        if remote || mcp.sign_in.kind == SignInKind::Connector {
            mcp.sign_in
        } else {
            Self::NO_REMOTE
        }
    }

    /// The command line for entry `name`, when there is a command.
    pub fn command_line(&self, name: &str) -> Option<Vec<String>> {
        self.command.map(|words| {
            words
                .iter()
                .map(|word| word.replace("{name}", name))
                .collect()
        })
    }

    /// [`SignIn::for_spec`] for entry `name`: a command Surjection would
    /// refuse to run with that name ([`runnable_name`]) is shown as a step
    /// to run by hand ([`SignInKind::InClient`]).
    pub fn for_entry(spec: &AdapterSpec, name: &str) -> Self {
        let mut sign_in = Self::for_spec(spec);
        if sign_in.kind == SignInKind::Command && !runnable_name(name) {
            sign_in.kind = SignInKind::InClient;
        }
        sign_in
    }

    /// The command as a person types it on `os`, the entry name quoted
    /// when it holds more than letters, digits, `.`, `_` and `-`.
    pub fn command_text(&self, name: &str, os: Os) -> Option<String> {
        self.command_line(&quoted(name, os))
            .map(|words| words.join(" "))
    }

    /// The steps for entry `name` of `client` (its display name), the
    /// name quoted as in [`SignIn::command_text`].
    pub fn steps_for(&self, client: &str, name: &str, os: Os) -> String {
        self.steps
            .replace("{client}", client)
            .replace("{name}", &quoted(name, os))
    }
}

/// A name a login command can take as it is: letters, digits, `.`, `_`
/// and `-`. Surjection runs a command only with such a name.
pub fn runnable_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
}

/// `name` quoted for a shell on `os` when it is not [`runnable_name`]:
/// `"..."` on Windows (`"` doubled), `'...'` elsewhere (`'` as `'\''`).
fn quoted(name: &str, os: Os) -> String {
    if runnable_name(name) {
        name.to_owned()
    } else if os == Os::Windows {
        format!("\"{}\"", name.replace('"', "\"\""))
    } else {
        format!("'{}'", name.replace('\'', "'\\''"))
    }
}

/// Stops a login that ran too long, with the processes it started: on
/// Windows an npm shim (`codex.cmd`) runs under `cmd.exe`, so the whole
/// tree is ended (`taskkill /T /F`); elsewhere the process itself.
fn kill_tree(taskkill: &Option<PathBuf>, child: &mut std::process::Child) {
    #[cfg(windows)]
    if let Some(taskkill) = taskkill {
        let _ = hide_window(&mut Command::new(taskkill))
            .args(["/T", "/F", "/PID", &child.id().to_string()])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .status();
    }
    #[cfg(not(windows))]
    let _ = taskkill;
    let _ = child.kill();
    let _ = child.wait();
}

/// Codex: `codex mcp login <server-name>` runs the OAuth login of a
/// configured server. Source: "For a server that supports OAuth, run
/// `codex mcp login <server-name>`" (<https://developers.openai.com/codex/mcp>,
/// read 2026-12-03).
pub const CODEX: SignIn = SignIn {
    kind: SignInKind::Command,
    command: Some(&["codex", "mcp", "login", "{name}"]),
    steps: "Run `codex mcp login {name}` in a terminal. It opens your browser to sign in.",
    docs_url: Some("https://developers.openai.com/codex/mcp"),
    verified: true,
};

/// Claude Code: `claude mcp login <name>` runs a configured server's OAuth
/// flow from the shell; `/mcp` in a session does the same. Source:
/// "Authenticate from the command line"
/// (<https://code.claude.com/docs/en/mcp>, read 2026-12-03).
pub const CLAUDE_CODE: SignIn = SignIn {
    kind: SignInKind::Command,
    command: Some(&["claude", "mcp", "login", "{name}"]),
    steps: "Run `claude mcp login {name}` in a terminal, or type /mcp in a Claude Code session, \
            pick {name} and choose Authenticate. It opens your browser to sign in.",
    docs_url: Some("https://code.claude.com/docs/en/mcp"),
    verified: true,
};

/// OpenCode: `opencode mcp auth <name>` (or `/mcps` in the app). Source:
/// "The CLI can start the same flow: opencode mcp auth sentry"
/// (<https://opencode.ai/docs/mcp-servers/>, read 2026-12-03).
pub const OPENCODE: SignIn = SignIn {
    kind: SignInKind::Command,
    command: Some(&["opencode", "mcp", "auth", "{name}"]),
    steps: "Run `opencode mcp auth {name}` in a terminal, or open /mcps in OpenCode and \
            authenticate {name}. It opens your browser to sign in.",
    docs_url: Some("https://opencode.ai/docs/mcp-servers/"),
    verified: true,
};

/// Gemini CLI: `/mcp auth <serverName>` inside a session. Source: "Use the
/// `/mcp auth` command to manage OAuth authentication"
/// (<https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md>,
/// read 2026-12-03).
pub const GEMINI: SignIn = SignIn {
    kind: SignInKind::InClient,
    command: None,
    steps: "In a Gemini CLI session, run `/mcp auth {name}`. It opens your browser to sign in.",
    docs_url: Some(
        "https://github.com/google-gemini/gemini-cli/blob/main/docs/tools/mcp-server.md",
    ),
    verified: true,
};

/// Claude Desktop reads only local (stdio) servers from its config file;
/// remote servers are custom connectors in its settings. Not confirmed
/// against its documentation here, so not `verified`.
pub const CLAUDE_DESKTOP: SignIn = SignIn {
    kind: SignInKind::Connector,
    command: None,
    steps: "Claude Desktop does not read remote servers from its config file. Add the address \
            as a custom connector in its settings (Connectors), then connect to sign in.",
    docs_url: None,
    verified: false,
};

/// How long a started login is waited for (the user signs in in the
/// browser) before it is stopped.
pub const SIGN_IN_TIMEOUT: Duration = Duration::from_secs(15 * 60);

/// A started login command.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StartedSignIn {
    /// The program that runs (resolved on `PATH`).
    pub program: PathBuf,
    /// The command as a person types it (`codex mcp login n8n`).
    pub command_line: String,
}

/// Starts `spec`'s verified login command for entry `name`, without a
/// console window and without waiting: the client opens the browser. The
/// only argument Surjection adds is the entry name (no secret, no
/// environment change). The start and, from a background thread, the
/// exit (or a stop after `timeout`) are logged. `not_found` when the
/// client has no verified command or its program is not on `PATH`;
/// `invalid_value` for a name that is not a plain entry name.
pub fn start(
    env: &Env,
    fs: &dyn Fs,
    spec: &AdapterSpec,
    name: &str,
    timeout: Duration,
) -> Result<StartedSignIn, CoreError> {
    let sign_in = SignIn::for_spec(spec);
    let words = match sign_in.command_line(name) {
        Some(words) if sign_in.kind == SignInKind::Command && sign_in.verified => words,
        _ => {
            return Err(CoreError::new(
                ErrorCode::NotFound,
                format!(
                    "{} has no login command Surjection can run",
                    spec.display_name
                ),
            ));
        }
    };
    if !runnable_name(name) {
        return Err(CoreError::new(
            ErrorCode::InvalidValue,
            format!("{name:?} is not an entry name a login command can take"),
        ));
    }
    let (program_name, args) = words.split_first().expect("a command has a program");
    let program = find_executable(env, fs, program_name).ok_or_else(|| {
        CoreError::new(
            ErrorCode::NotFound,
            format!(
                "{program_name} was not found on PATH; run `{}` in a terminal instead",
                words.join(" ")
            ),
        )
    })?;
    let command_line = words.join(" ");
    let mut child = hide_window(&mut Command::new(&program))
        .args(args)
        .stdin(Stdio::null())
        .stdout(Stdio::null())
        .stderr(Stdio::null())
        .spawn()
        .map_err(|err| {
            CoreError::new(
                ErrorCode::IoError,
                format!("cannot start {program_name}: {err}"),
            )
        })?;
    let client = spec.id;
    let taskkill = env
        .var("SystemRoot")
        .map(|root| PathBuf::from(root).join("System32").join("taskkill.exe"));
    log::event(
        "sign_in_started",
        &[("client", &client), ("command", &command_line)],
    );
    let started = Instant::now();
    std::thread::spawn(move || {
        let outcome = loop {
            match child.try_wait() {
                Ok(Some(status)) => {
                    break status
                        .code()
                        .map_or_else(|| "ended".to_owned(), |code| format!("exit {code}"));
                }
                Ok(None) if started.elapsed() >= timeout => {
                    kill_tree(&taskkill, &mut child);
                    break "stopped (timed out)".to_owned();
                }
                Ok(None) => std::thread::sleep(Duration::from_millis(250)),
                Err(err) => break format!("unknown ({err})"),
            }
        };
        let seconds = started.elapsed().as_secs();
        log::event(
            "sign_in_finished",
            &[
                ("client", &client),
                ("outcome", &outcome),
                ("secs", &seconds),
            ],
        );
    });
    Ok(StartedSignIn {
        program,
        command_line,
    })
}