diff --git a/Cargo.toml b/Cargo.toml
index 2c04d40..b032efe 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -18,7 +18,7 @@ crate-type = ["cdylib", "rlib"]
[features]
default = []
-cli = ["dep:clap", "dep:comfy-table", "dep:dialoguer", "dep:dirs"]
+cli = ["dep:clap", "dep:comfy-table", "dep:dialoguer", "dep:dirs", "dep:toml", "dep:webbrowser"]
python = ["dep:pyo3", "dep:pythonize"]
[dependencies]
@@ -34,6 +34,8 @@ clap = { version = "4", features = ["derive"], optional = true }
comfy-table = { version = "7", optional = true }
dialoguer = { version = "0.11", optional = true }
dirs = { version = "6", optional = true }
+toml = { version = "0.8", optional = true }
+webbrowser = { version = "1", optional = true }
# Python bindings (optional)
pyo3 = { version = "0.23", features = ["extension-module"], optional = true }
diff --git a/README.md b/README.md
index b750d2e..d6fc95d 100644
--- a/README.md
+++ b/README.md
@@ -8,13 +8,35 @@ It also works standalone: as a CLI tool, a Python library, or a Rust crate.
| Mode | What it does | Guide |
|------|-------------|-------|
-| **MCP server** (`scix serve`) | Expose SciX tools to Claude, Cursor, Zed, etc. | [docs/mcp-server.md](docs/mcp-server.md) |
+| **MCP server** (`scix serve`) | Expose SciX tools to Claude, Cursor, Zed, Gemini CLI, Codex CLI, Windsurf | [docs/mcp-server.md](docs/mcp-server.md) |
+| **Chat REPL** (`scix chat`) | Built-in tool-use loop against any model (Anthropic, OpenAI, Gemini, Ollama) — no MCP host needed | below |
| **CLI** (`scix`) | Command-line tool for your terminal | [docs/cli.md](docs/cli.md) |
| **Python library** (`scix_client`) | Native Python module — `pip install scix-client` | [docs/python.md](docs/python.md) |
| **Rust library** (`scix_client`) | Async Rust crate — `cargo add scix-client` | [docs/rust.md](docs/rust.md) |
One binary (`scix`) does everything. Python bindings are auto-generated from the Rust types — zero extra maintenance.
+## Install
+
+```bash
+# One-line installer (no Rust toolchain required)
+curl -sSf https://raw.githubusercontent.com/yipihey/scix-client/main/install.sh | sh
+
+# From PyPI (also gives you the Python module)
+pip install scix-client # or: uvx scix-client, pipx install scix-client
+
+# From crates.io (compiles locally)
+cargo install scix-client --features cli
+# or, prebuilt binary via cargo-binstall:
+cargo binstall scix-client
+```
+
+Verify your setup at any time with:
+
+```bash
+scix doctor
+```
+
## Prerequisites
You need a SciX / ADS API token. Get one (free) at:
@@ -30,14 +52,7 @@ export ADS_API_TOKEN="your-token-here"
## Quick Start: MCP
-Give your AI assistant access to the entire SciX database.
-
-### Install
-
-```bash
-cargo install scix-client --features cli
-# or: cargo binstall scix-client
-```
+Give your AI assistant access to the entire SciX database. (Install with any method from [Install](#install) above.)
### Automatic setup (recommended)
@@ -45,10 +60,10 @@ cargo install scix-client --features cli
scix setup
```
-This detects your installed editors (Claude Code, Claude Desktop, Cursor, Zed), prompts for your API token, validates it, and writes the correct config for each one. Run it once and you're done.
+This detects your installed editors (Claude Code, Claude Desktop, Cursor, Zed, Gemini CLI, Codex CLI, Windsurf), prompts for your API token (offering to open the token page in your browser), validates it, and writes the correct config for each one. Run it once and you're done.
Options:
-- `scix setup claude-code` — configure only Claude Code
+- `scix setup claude-code` — configure only one editor
- `scix setup --yes` — non-interactive (uses env token, configures all detected editors)
- `scix setup --skip-validation` — skip token validation
@@ -84,11 +99,28 @@ See [docs/mcp-server.md](docs/mcp-server.md) for Cursor, Zed, full tool referenc
---
-## Quick Start: CLI
+## Quick Start: Chat REPL
+
+Drive scix from any tool-use-capable LLM, with no MCP host required. Set one provider's API key and go.
```bash
-cargo install scix-client --features cli
+export ANTHROPIC_API_KEY="sk-ant-..." # or OPENAI_API_KEY, GEMINI_API_KEY, OLLAMA_HOST
+export SCIX_API_TOKEN="your-ads-token"
+scix chat # auto-detects provider
+
+# Or pick explicitly:
+scix chat --provider openai --model gpt-5
+scix chat --provider gemini --model gemini-2.5-pro
+scix chat --provider ollama --model llama3.1:70b
+```
+Inside the REPL, just ask questions. The model uses the same SciX tools the MCP server exposes (search, export, metrics, libraries, citation/reference networks, object name resolution, paper details).
+
+---
+
+## Quick Start: CLI
+
+```bash
scix search 'first_author:"Perlmutter" supernova' --sort "citation_count desc"
scix export 1999ApJ...517..565P --format bibtex
scix cites 1999ApJ...517..565P --rows 50
diff --git a/docs/chat.md b/docs/chat.md
new file mode 100644
index 0000000..5e268c4
--- /dev/null
+++ b/docs/chat.md
@@ -0,0 +1,81 @@
+# Chat REPL Guide
+
+[Back to README](../README.md)
+
+`scix chat` is a built-in tool-use REPL that drives any tool-use-capable LLM
+against the SciX tool set — no MCP host required. Set one provider's API key
+and a SciX API token, and go.
+
+## Quick Start
+
+```bash
+export SCIX_API_TOKEN="your-ads-token"
+export ANTHROPIC_API_KEY="sk-ant-..."
+
+scix chat
+```
+
+Inside the REPL you'll see a `>` prompt. Type a question; press Enter. The
+model has access to the full SciX tool set; tool calls and results are
+printed inline as they happen.
+
+```
+> Find the three most-cited papers by Vera Rubin on galaxy rotation curves
+ [tool] scix_search({"query":"author:\"Rubin, V\" title:\"rotation curve\"","sort":"citation_count desc","rows":3})
+
+The three most-cited papers by Vera Rubin on galaxy rotation curves are:
+ 1. ...
+> exit
+```
+
+## Providers
+
+Provider is selected with `--provider`, or auto-detected from the first env
+var present in this order: `ANTHROPIC_API_KEY` → `OPENAI_API_KEY` →
+`GEMINI_API_KEY` → `OLLAMA_HOST`.
+
+| Provider | Env var | Default model | Notes |
+|--------------|--------------------------------|-----------------------|-------|
+| `anthropic` | `ANTHROPIC_API_KEY` | `claude-sonnet-4-6` | |
+| `openai` | `OPENAI_API_KEY` | `gpt-5` | Optional `OPENAI_BASE_URL` for compatible APIs |
+| `gemini` | `GEMINI_API_KEY` / `GOOGLE_API_KEY` | `gemini-2.5-pro` | |
+| `ollama` | `OLLAMA_HOST` (default `http://localhost:11434`) | `llama3.1:8b` | Uses Ollama's OpenAI-compatible `/v1` endpoint |
+
+Override the model with `--model`:
+
+```bash
+scix chat --provider openai --model gpt-5
+scix chat --provider gemini --model gemini-2.5-flash
+scix chat --provider ollama --model llama3.1:70b
+```
+
+## Options
+
+```
+scix chat [OPTIONS]
+
+ --provider
anthropic | openai | gemini | ollama
+ --model Override the default model
+ --max-turns Maximum tool-call iterations per user message (default 25)
+```
+
+## How It Compares to MCP
+
+| Aspect | `scix serve` (MCP) | `scix chat` |
+|-------------------|--------------------------------|-----------------------------------|
+| Host required | Yes (Claude Code, Cursor, ...) | No — direct API call |
+| Bring your own key | Host's key | Yours (one of four providers) |
+| Streaming | Host-dependent | Not yet |
+| Best for | Daily use in an IDE/editor | Scripting, CI, headless servers, models without an MCP host |
+
+Both modes share the same tool implementations, so behavior is identical.
+
+## Troubleshooting
+
+- **"No LLM provider detected"** — set one of `ANTHROPIC_API_KEY`,
+ `OPENAI_API_KEY`, `GEMINI_API_KEY`, or `OLLAMA_HOST`, or pass `--provider`.
+- **"401 unauthorized"** — your provider key is missing or wrong.
+- **"Authentication required"** — your SciX API token is missing
+ (`SCIX_API_TOKEN`).
+- **Tool calls failing repeatedly** — increase `--max-turns`, or run
+ `scix doctor` to verify connectivity.
diff --git a/docs/mcp-server.md b/docs/mcp-server.md
index 41a3f8c..675405e 100644
--- a/docs/mcp-server.md
+++ b/docs/mcp-server.md
@@ -17,7 +17,13 @@ Once connected, you can ask your AI assistant things like:
## Installation
```bash
-# From crates.io (recommended)
+# One-line installer (prebuilt binary, no Rust toolchain)
+curl -sSf https://raw.githubusercontent.com/yipihey/scix-client/main/install.sh | sh
+
+# From PyPI
+pip install scix-client # or: uvx scix-client, pipx install scix-client
+
+# From crates.io
cargo install scix-client --features cli
# Pre-built binary (via cargo-binstall — no compile needed)
@@ -55,6 +61,9 @@ scix setup claude-code # Configure only Claude Code
scix setup claude-desktop # Configure only Claude Desktop
scix setup cursor # Configure only Cursor
scix setup zed # Configure only Zed
+scix setup gemini-cli # Configure only Gemini CLI
+scix setup codex-cli # Configure only Codex CLI (OpenAI)
+scix setup windsurf # Configure only Windsurf (Codeium)
Flags:
--skip-validation Don't test the API token
diff --git a/install.sh b/install.sh
new file mode 100755
index 0000000..026e7fb
--- /dev/null
+++ b/install.sh
@@ -0,0 +1,145 @@
+#!/bin/sh
+# scix-client installer
+#
+# Downloads the latest prebuilt `scix` binary for your platform from
+# https://github.com/yipihey/scix-client/releases and installs it to
+# ~/.local/bin (or $SCIX_INSTALL_DIR if set).
+#
+# Usage:
+# curl -sSf https://raw.githubusercontent.com/yipihey/scix-client/main/install.sh | sh
+#
+# Environment:
+# SCIX_INSTALL_DIR Install directory (default: $HOME/.local/bin)
+# SCIX_VERSION Version to install (default: latest)
+# GITHUB_TOKEN Optional, for higher rate limits on api.github.com
+#
+# Exit codes:
+# 1 usage / unsupported platform
+# 2 download failed
+# 3 install failed
+
+set -eu
+
+REPO="yipihey/scix-client"
+INSTALL_DIR="${SCIX_INSTALL_DIR:-$HOME/.local/bin}"
+VERSION="${SCIX_VERSION:-latest}"
+
+err() { printf 'error: %s\n' "$*" >&2; exit "${2:-1}"; }
+info() { printf '%s\n' "$*"; }
+
+need_cmd() {
+ if ! command -v "$1" >/dev/null 2>&1; then
+ err "missing required command: $1"
+ fi
+}
+
+# Pick curl or wget for downloads.
+if command -v curl >/dev/null 2>&1; then
+ DL='curl -fsSL'
+ DL_OUT='curl -fsSL -o'
+elif command -v wget >/dev/null 2>&1; then
+ DL='wget -qO-'
+ DL_OUT='wget -qO'
+else
+ err "need curl or wget"
+fi
+
+need_cmd uname
+need_cmd tar
+need_cmd mkdir
+need_cmd chmod
+need_cmd mv
+
+# Detect platform target triple matching the release artifact names.
+detect_target() {
+ os="$(uname -s)"
+ arch="$(uname -m)"
+ case "$os" in
+ Linux)
+ case "$arch" in
+ x86_64|amd64) echo "x86_64-unknown-linux-gnu" ;;
+ aarch64|arm64) echo "aarch64-unknown-linux-gnu" ;;
+ *) err "unsupported linux arch: $arch" ;;
+ esac
+ ;;
+ Darwin)
+ case "$arch" in
+ x86_64) echo "x86_64-apple-darwin" ;;
+ arm64) echo "aarch64-apple-darwin" ;;
+ *) err "unsupported macos arch: $arch" ;;
+ esac
+ ;;
+ MINGW*|MSYS*|CYGWIN*)
+ err "windows: please download from https://github.com/$REPO/releases" 1
+ ;;
+ *)
+ err "unsupported OS: $os"
+ ;;
+ esac
+}
+
+resolve_version() {
+ if [ "$VERSION" = "latest" ]; then
+ api_url="https://api.github.com/repos/$REPO/releases/latest"
+ if [ -n "${GITHUB_TOKEN:-}" ]; then
+ tag=$($DL -H "Authorization: Bearer $GITHUB_TOKEN" "$api_url" 2>/dev/null \
+ | sed -n 's/.*"tag_name":[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)
+ else
+ tag=$($DL "$api_url" 2>/dev/null \
+ | sed -n 's/.*"tag_name":[[:space:]]*"\([^"]*\)".*/\1/p' | head -n1)
+ fi
+ [ -n "$tag" ] || err "could not resolve latest release tag" 2
+ echo "$tag"
+ elif [ "${VERSION#v}" = "$VERSION" ]; then
+ echo "v$VERSION"
+ else
+ echo "$VERSION"
+ fi
+}
+
+TARGET="$(detect_target)"
+TAG="$(resolve_version)"
+VER="${TAG#v}"
+ARCHIVE="scix-v${VER}-${TARGET}.tar.gz"
+URL="https://github.com/$REPO/releases/download/$TAG/$ARCHIVE"
+
+info "scix-client installer"
+info " repo: $REPO"
+info " version: $TAG"
+info " target: $TARGET"
+info " prefix: $INSTALL_DIR"
+info ""
+
+TMP=$(mktemp -d 2>/dev/null || mktemp -d -t scix)
+trap 'rm -rf "$TMP"' EXIT INT TERM
+
+info "Downloading $ARCHIVE..."
+$DL_OUT "$TMP/$ARCHIVE" "$URL" || err "download failed: $URL" 2
+
+info "Extracting..."
+tar -xzf "$TMP/$ARCHIVE" -C "$TMP" || err "extract failed" 2
+
+[ -f "$TMP/scix" ] || err "archive did not contain expected binary 'scix'" 2
+
+mkdir -p "$INSTALL_DIR" || err "cannot create $INSTALL_DIR" 3
+chmod +x "$TMP/scix"
+mv "$TMP/scix" "$INSTALL_DIR/scix" || err "cannot install to $INSTALL_DIR" 3
+
+info ""
+info "Installed: $INSTALL_DIR/scix"
+
+# Friendly PATH check.
+case ":$PATH:" in
+ *":$INSTALL_DIR:"*)
+ info ""
+ info "Next: scix setup"
+ ;;
+ *)
+ info ""
+ info "Warning: $INSTALL_DIR is not on your PATH."
+ info "Add this to your shell profile (.bashrc / .zshrc):"
+ info " export PATH=\"\$HOME/.local/bin:\$PATH\""
+ info ""
+ info "Then run: scix setup"
+ ;;
+esac
diff --git a/src/bin/scix.rs b/src/bin/scix.rs
index 88ef6d4..1b65199 100644
--- a/src/bin/scix.rs
+++ b/src/bin/scix.rs
@@ -115,6 +115,20 @@ mod cli {
#[arg(long, short = 'y')]
yes: bool,
},
+ /// Diagnose installation, token, API connectivity, and editor detection
+ Doctor,
+ /// Interactive chat REPL with any tool-use-capable LLM
+ Chat {
+ /// LLM provider (default: auto-detect from environment)
+ #[arg(long, value_enum)]
+ provider: Option,
+ /// Model name (default: provider-specific)
+ #[arg(long)]
+ model: Option,
+ /// Max tool-call iterations per user message
+ #[arg(long)]
+ max_turns: Option,
+ },
}
#[derive(Subcommand)]
@@ -245,7 +259,7 @@ mod cli {
pub async fn run() -> scix_client::error::Result<()> {
let cli = Cli::parse();
- // Setup doesn't need a pre-built client.
+ // Setup / Doctor run before any client is built.
if let Commands::Setup {
editor,
skip_validation,
@@ -254,6 +268,9 @@ mod cli {
{
return scix_client::setup::run_setup(editor, skip_validation, yes).await;
}
+ if matches!(cli.command, Commands::Doctor) {
+ return scix_client::doctor::run_doctor().await;
+ }
let client = make_client(cli.token)?;
@@ -459,7 +476,15 @@ mod cli {
scix_client::mcp::run_server(client).await?;
}
- Commands::Setup { .. } => unreachable!(),
+ Commands::Chat {
+ provider,
+ model,
+ max_turns,
+ } => {
+ scix_client::chat::run_chat(provider, model, max_turns, client).await?;
+ }
+
+ Commands::Setup { .. } | Commands::Doctor => unreachable!(),
}
Ok(())
diff --git a/src/chat.rs b/src/chat.rs
new file mode 100644
index 0000000..99ab9dc
--- /dev/null
+++ b/src/chat.rs
@@ -0,0 +1,626 @@
+//! `scix chat` — built-in REPL that drives any tool-use-capable LLM against
+//! the scix tool set.
+//!
+//! Auto-detects a provider from the environment (Anthropic, OpenAI, Gemini,
+//! Ollama) or accepts an explicit `--provider`. Tool definitions and dispatch
+//! are reused from the MCP server, so the same tools work everywhere.
+
+use crate::error::{Result, SciXError};
+use crate::mcp::{dispatch_tool_call, tool_definitions_value};
+use crate::SciXClient;
+use reqwest::Client as HttpClient;
+use serde_json::{json, Value};
+use std::time::Duration;
+
+const SYSTEM_PROMPT: &str = r#"You are a research assistant with access to the SciX / NASA ADS astronomy literature database via a set of tools (search, export, metrics, library management, object name resolution, paper details, and citation/reference network analysis).
+
+When a user asks about scientific papers, authors, citations, libraries, or astronomical objects, prefer using the tools to fetch live data rather than relying on your training. Be concise. When showing search results, include bibcodes so the user can reference them later. When the user asks for citations or references in a specific format (BibTeX, AASTeX, MNRAS, etc.), use the scix_export tool."#;
+
+const DEFAULT_MAX_TURNS: u32 = 25;
+
+/// Provider selection.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
+pub enum Provider {
+ Anthropic,
+ Openai,
+ Gemini,
+ Ollama,
+}
+
+impl std::fmt::Display for Provider {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::Anthropic => write!(f, "anthropic"),
+ Self::Openai => write!(f, "openai"),
+ Self::Gemini => write!(f, "gemini"),
+ Self::Ollama => write!(f, "ollama"),
+ }
+ }
+}
+
+impl Provider {
+ fn default_model(&self) -> &'static str {
+ match self {
+ Self::Anthropic => "claude-sonnet-4-6",
+ Self::Openai => "gpt-5",
+ Self::Gemini => "gemini-2.5-pro",
+ Self::Ollama => "llama3.1:8b",
+ }
+ }
+}
+
+/// Auto-detect a provider from environment variables.
+fn detect_provider() -> Option {
+ if std::env::var("ANTHROPIC_API_KEY").is_ok() {
+ return Some(Provider::Anthropic);
+ }
+ if std::env::var("OPENAI_API_KEY").is_ok() {
+ return Some(Provider::Openai);
+ }
+ if std::env::var("GEMINI_API_KEY").is_ok() || std::env::var("GOOGLE_API_KEY").is_ok() {
+ return Some(Provider::Gemini);
+ }
+ if std::env::var("OLLAMA_HOST").is_ok() {
+ return Some(Provider::Ollama);
+ }
+ None
+}
+
+/// One assistant turn: any text output plus any tool calls the model issued.
+#[derive(Default)]
+struct AssistantTurn {
+ text: String,
+ tool_calls: Vec,
+}
+
+#[derive(Clone)]
+struct ToolCall {
+ id: String,
+ name: String,
+ arguments: Value,
+}
+
+/// Canonical conversation message (Anthropic-shaped; each provider converts
+/// from this on the way out).
+#[derive(Clone)]
+struct Message {
+ role: Role,
+ blocks: Vec,
+}
+
+#[derive(Clone, PartialEq)]
+enum Role {
+ User,
+ Assistant,
+}
+
+#[derive(Clone)]
+enum Block {
+ Text(String),
+ ToolUse(ToolCall),
+ ToolResult {
+ id: String,
+ content: String,
+ is_error: bool,
+ },
+}
+
+// --- Tool-schema translation ---------------------------------------------
+
+fn tools_for_anthropic() -> Value {
+ let defs = tool_definitions_value();
+ let mut out = Vec::new();
+ for t in defs.as_array().cloned().unwrap_or_default() {
+ out.push(json!({
+ "name": t["name"],
+ "description": t["description"],
+ "input_schema": t["inputSchema"],
+ }));
+ }
+ Value::Array(out)
+}
+
+fn tools_for_openai() -> Value {
+ let defs = tool_definitions_value();
+ let mut out = Vec::new();
+ for t in defs.as_array().cloned().unwrap_or_default() {
+ out.push(json!({
+ "type": "function",
+ "function": {
+ "name": t["name"],
+ "description": t["description"],
+ "parameters": t["inputSchema"],
+ }
+ }));
+ }
+ Value::Array(out)
+}
+
+fn tools_for_gemini() -> Value {
+ let defs = tool_definitions_value();
+ let mut decls = Vec::new();
+ for t in defs.as_array().cloned().unwrap_or_default() {
+ decls.push(json!({
+ "name": t["name"],
+ "description": t["description"],
+ "parameters": t["inputSchema"],
+ }));
+ }
+ json!([{ "functionDeclarations": decls }])
+}
+
+// --- Provider HTTP calls --------------------------------------------------
+
+async fn complete_anthropic(
+ http: &HttpClient,
+ api_key: &str,
+ model: &str,
+ messages: &[Message],
+) -> std::result::Result {
+ let mut native_messages = Vec::new();
+ for m in messages {
+ let role = match m.role {
+ Role::User => "user",
+ Role::Assistant => "assistant",
+ };
+ let mut content = Vec::new();
+ for b in &m.blocks {
+ match b {
+ Block::Text(t) => content.push(json!({"type": "text", "text": t})),
+ Block::ToolUse(tc) => content.push(json!({
+ "type": "tool_use",
+ "id": tc.id,
+ "name": tc.name,
+ "input": tc.arguments,
+ })),
+ Block::ToolResult {
+ id,
+ content: c,
+ is_error,
+ } => content.push(json!({
+ "type": "tool_result",
+ "tool_use_id": id,
+ "content": c,
+ "is_error": is_error,
+ })),
+ }
+ }
+ native_messages.push(json!({"role": role, "content": content}));
+ }
+
+ let body = json!({
+ "model": model,
+ "max_tokens": 4096,
+ "system": SYSTEM_PROMPT,
+ "tools": tools_for_anthropic(),
+ "messages": native_messages,
+ });
+
+ let resp = http
+ .post("https://api.anthropic.com/v1/messages")
+ .header("x-api-key", api_key)
+ .header("anthropic-version", "2023-06-01")
+ .json(&body)
+ .send()
+ .await
+ .map_err(SciXError::Http)?;
+
+ if !resp.status().is_success() {
+ let status = resp.status().as_u16();
+ let text = resp.text().await.unwrap_or_default();
+ return Err(SciXError::Api {
+ status,
+ message: format!("Anthropic: {}", text),
+ });
+ }
+ let v: Value = resp.json().await.map_err(SciXError::Http)?;
+
+ let mut turn = AssistantTurn::default();
+ if let Some(blocks) = v["content"].as_array() {
+ for b in blocks {
+ match b["type"].as_str() {
+ Some("text") => {
+ if let Some(t) = b["text"].as_str() {
+ turn.text.push_str(t);
+ }
+ }
+ Some("tool_use") => {
+ turn.tool_calls.push(ToolCall {
+ id: b["id"].as_str().unwrap_or("").to_string(),
+ name: b["name"].as_str().unwrap_or("").to_string(),
+ arguments: b["input"].clone(),
+ });
+ }
+ _ => {}
+ }
+ }
+ }
+ Ok(turn)
+}
+
+async fn complete_openai(
+ http: &HttpClient,
+ api_key: &str,
+ base_url: &str,
+ model: &str,
+ messages: &[Message],
+) -> std::result::Result {
+ let mut native_messages = vec![json!({"role": "system", "content": SYSTEM_PROMPT})];
+
+ for m in messages {
+ match m.role {
+ Role::User => {
+ // OpenAI distinguishes "user" text from "tool" results.
+ // Tool results are role:"tool" with tool_call_id.
+ let mut text_parts = Vec::new();
+ let mut tool_results = Vec::new();
+ for b in &m.blocks {
+ match b {
+ Block::Text(t) => text_parts.push(t.clone()),
+ Block::ToolResult { id, content, .. } => {
+ tool_results.push((id.clone(), content.clone()));
+ }
+ Block::ToolUse(_) => {} // never on user role
+ }
+ }
+ if !text_parts.is_empty() {
+ native_messages.push(json!({"role": "user", "content": text_parts.join("\n")}));
+ }
+ for (id, content) in tool_results {
+ native_messages.push(json!({
+ "role": "tool",
+ "tool_call_id": id,
+ "content": content,
+ }));
+ }
+ }
+ Role::Assistant => {
+ let mut text = String::new();
+ let mut tool_calls = Vec::new();
+ for b in &m.blocks {
+ match b {
+ Block::Text(t) => text.push_str(t),
+ Block::ToolUse(tc) => tool_calls.push(json!({
+ "id": tc.id,
+ "type": "function",
+ "function": {
+ "name": tc.name,
+ "arguments": serde_json::to_string(&tc.arguments).unwrap_or_default(),
+ }
+ })),
+ Block::ToolResult { .. } => {}
+ }
+ }
+ let mut msg = json!({"role": "assistant"});
+ if !text.is_empty() {
+ msg["content"] = json!(text);
+ } else {
+ msg["content"] = Value::Null;
+ }
+ if !tool_calls.is_empty() {
+ msg["tool_calls"] = Value::Array(tool_calls);
+ }
+ native_messages.push(msg);
+ }
+ }
+ }
+
+ let body = json!({
+ "model": model,
+ "messages": native_messages,
+ "tools": tools_for_openai(),
+ });
+
+ let endpoint = format!("{}/chat/completions", base_url.trim_end_matches('/'));
+ let mut req = http.post(&endpoint).json(&body);
+ if !api_key.is_empty() {
+ req = req.header("Authorization", format!("Bearer {}", api_key));
+ }
+ let resp = req.send().await.map_err(SciXError::Http)?;
+
+ if !resp.status().is_success() {
+ let status = resp.status().as_u16();
+ let text = resp.text().await.unwrap_or_default();
+ return Err(SciXError::Api {
+ status,
+ message: format!("OpenAI ({}): {}", endpoint, text),
+ });
+ }
+ let v: Value = resp.json().await.map_err(SciXError::Http)?;
+
+ let mut turn = AssistantTurn::default();
+ let msg = &v["choices"][0]["message"];
+ if let Some(t) = msg["content"].as_str() {
+ turn.text.push_str(t);
+ }
+ if let Some(calls) = msg["tool_calls"].as_array() {
+ for c in calls {
+ let id = c["id"].as_str().unwrap_or("").to_string();
+ let name = c["function"]["name"].as_str().unwrap_or("").to_string();
+ let raw_args = c["function"]["arguments"].as_str().unwrap_or("{}");
+ let arguments: Value = serde_json::from_str(raw_args).unwrap_or_else(|_| json!({}));
+ turn.tool_calls.push(ToolCall {
+ id,
+ name,
+ arguments,
+ });
+ }
+ }
+ Ok(turn)
+}
+
+async fn complete_gemini(
+ http: &HttpClient,
+ api_key: &str,
+ model: &str,
+ messages: &[Message],
+) -> std::result::Result {
+ let mut contents = Vec::new();
+ for m in messages {
+ let role = match m.role {
+ Role::User => "user",
+ Role::Assistant => "model",
+ };
+ let mut parts = Vec::new();
+ for b in &m.blocks {
+ match b {
+ Block::Text(t) => parts.push(json!({"text": t})),
+ Block::ToolUse(tc) => parts.push(json!({
+ "functionCall": { "name": tc.name, "args": tc.arguments }
+ })),
+ Block::ToolResult { id: _, content, .. } => parts.push(json!({
+ "functionResponse": {
+ "name": "tool_result",
+ "response": { "content": content }
+ }
+ })),
+ }
+ }
+ contents.push(json!({"role": role, "parts": parts}));
+ }
+
+ let body = json!({
+ "system_instruction": { "parts": [{"text": SYSTEM_PROMPT}] },
+ "contents": contents,
+ "tools": tools_for_gemini(),
+ });
+
+ let url = format!(
+ "https://generativelanguage.googleapis.com/v1beta/models/{}:generateContent?key={}",
+ model, api_key
+ );
+ let resp = http
+ .post(&url)
+ .json(&body)
+ .send()
+ .await
+ .map_err(SciXError::Http)?;
+
+ if !resp.status().is_success() {
+ let status = resp.status().as_u16();
+ let text = resp.text().await.unwrap_or_default();
+ return Err(SciXError::Api {
+ status,
+ message: format!("Gemini: {}", text),
+ });
+ }
+ let v: Value = resp.json().await.map_err(SciXError::Http)?;
+
+ let mut turn = AssistantTurn::default();
+ if let Some(parts) = v["candidates"][0]["content"]["parts"].as_array() {
+ for p in parts {
+ if let Some(t) = p["text"].as_str() {
+ turn.text.push_str(t);
+ }
+ if let Some(fc) = p.get("functionCall") {
+ let id = format!("call_{}", turn.tool_calls.len());
+ turn.tool_calls.push(ToolCall {
+ id,
+ name: fc["name"].as_str().unwrap_or("").to_string(),
+ arguments: fc.get("args").cloned().unwrap_or(json!({})),
+ });
+ }
+ }
+ }
+ Ok(turn)
+}
+
+// --- REPL -----------------------------------------------------------------
+
+#[derive(Clone)]
+struct ChatConfig {
+ provider: Provider,
+ model: String,
+ api_key: String,
+ base_url: String, // OpenAI / Ollama only
+ max_turns: u32,
+}
+
+fn build_config(
+ provider_arg: Option,
+ model_arg: Option,
+ max_turns: u32,
+) -> Result {
+ let provider = match provider_arg {
+ Some(p) => p,
+ None => detect_provider().ok_or_else(|| {
+ SciXError::Config(
+ "No LLM provider detected. Set one of: ANTHROPIC_API_KEY, OPENAI_API_KEY, \
+ GEMINI_API_KEY, OLLAMA_HOST. Or pass --provider."
+ .into(),
+ )
+ })?,
+ };
+
+ let (api_key, base_url) = match provider {
+ Provider::Anthropic => (
+ std::env::var("ANTHROPIC_API_KEY")
+ .map_err(|_| SciXError::Config("ANTHROPIC_API_KEY not set".into()))?,
+ String::new(),
+ ),
+ Provider::Openai => (
+ std::env::var("OPENAI_API_KEY")
+ .map_err(|_| SciXError::Config("OPENAI_API_KEY not set".into()))?,
+ std::env::var("OPENAI_BASE_URL").unwrap_or_else(|_| "https://api.openai.com/v1".into()),
+ ),
+ Provider::Gemini => (
+ std::env::var("GEMINI_API_KEY")
+ .or_else(|_| std::env::var("GOOGLE_API_KEY"))
+ .map_err(|_| {
+ SciXError::Config("GEMINI_API_KEY (or GOOGLE_API_KEY) not set".into())
+ })?,
+ String::new(),
+ ),
+ Provider::Ollama => {
+ // Ollama exposes an OpenAI-compatible API at /v1.
+ let host =
+ std::env::var("OLLAMA_HOST").unwrap_or_else(|_| "http://localhost:11434".into());
+ let base = if host.contains("/v1") {
+ host
+ } else {
+ format!("{}/v1", host.trim_end_matches('/'))
+ };
+ ("ollama".to_string(), base)
+ }
+ };
+
+ Ok(ChatConfig {
+ provider,
+ model: model_arg.unwrap_or_else(|| provider.default_model().to_string()),
+ api_key,
+ base_url,
+ max_turns,
+ })
+}
+
+async fn one_completion(
+ http: &HttpClient,
+ cfg: &ChatConfig,
+ messages: &[Message],
+) -> std::result::Result {
+ match cfg.provider {
+ Provider::Anthropic => complete_anthropic(http, &cfg.api_key, &cfg.model, messages).await,
+ Provider::Openai | Provider::Ollama => {
+ complete_openai(http, &cfg.api_key, &cfg.base_url, &cfg.model, messages).await
+ }
+ Provider::Gemini => complete_gemini(http, &cfg.api_key, &cfg.model, messages).await,
+ }
+}
+
+fn pretty_arguments(args: &Value) -> String {
+ let s = serde_json::to_string(args).unwrap_or_default();
+ if s.len() > 120 {
+ format!("{}...", &s[..117])
+ } else {
+ s
+ }
+}
+
+/// Public entry point.
+pub async fn run_chat(
+ provider: Option,
+ model: Option,
+ max_turns: Option,
+ client: SciXClient,
+) -> Result<()> {
+ let cfg = build_config(provider, model, max_turns.unwrap_or(DEFAULT_MAX_TURNS))?;
+ let http = HttpClient::builder()
+ .timeout(Duration::from_secs(120))
+ .build()
+ .map_err(SciXError::Http)?;
+
+ println!();
+ println!("scix chat — {} ({})", cfg.provider, cfg.model);
+ println!("Type your question, blank line to send. Ctrl-D or 'exit' to quit.");
+ println!();
+
+ let mut messages: Vec = Vec::new();
+
+ while let Ok(prompt) = dialoguer::Input::::new()
+ .with_prompt(">")
+ .allow_empty(false)
+ .interact_text()
+ {
+ let trimmed = prompt.trim();
+ if trimmed.is_empty() {
+ continue;
+ }
+ if matches!(trimmed, "exit" | "quit" | ":q") {
+ break;
+ }
+
+ messages.push(Message {
+ role: Role::User,
+ blocks: vec![Block::Text(trimmed.to_string())],
+ });
+
+ // Tool-call loop.
+ let mut turns_remaining = cfg.max_turns;
+ loop {
+ if turns_remaining == 0 {
+ println!("\n[reached --max-turns limit, ending iteration]");
+ break;
+ }
+ turns_remaining -= 1;
+
+ let turn = match one_completion(&http, &cfg, &messages).await {
+ Ok(t) => t,
+ Err(e) => {
+ eprintln!("\nerror: {}", e);
+ break;
+ }
+ };
+
+ if !turn.text.is_empty() {
+ println!("\n{}", turn.text);
+ }
+
+ if turn.tool_calls.is_empty() {
+ // Final assistant turn — record and break.
+ messages.push(Message {
+ role: Role::Assistant,
+ blocks: vec![Block::Text(turn.text.clone())],
+ });
+ break;
+ }
+
+ // Record the assistant turn (text + tool uses) verbatim.
+ let mut blocks: Vec = Vec::new();
+ if !turn.text.is_empty() {
+ blocks.push(Block::Text(turn.text.clone()));
+ }
+ for tc in &turn.tool_calls {
+ blocks.push(Block::ToolUse(tc.clone()));
+ }
+ messages.push(Message {
+ role: Role::Assistant,
+ blocks,
+ });
+
+ // Execute each tool call and gather results.
+ let mut result_blocks: Vec = Vec::new();
+ for tc in &turn.tool_calls {
+ println!(" [tool] {}({})", tc.name, pretty_arguments(&tc.arguments));
+ let r = dispatch_tool_call(&client, &tc.name, &tc.arguments).await;
+ let (content, is_error) = match r {
+ Ok(s) => (s, false),
+ Err(e) => (format!("Error: {}", e), true),
+ };
+ result_blocks.push(Block::ToolResult {
+ id: tc.id.clone(),
+ content,
+ is_error,
+ });
+ }
+ messages.push(Message {
+ role: Role::User,
+ blocks: result_blocks,
+ });
+ }
+
+ println!();
+ }
+
+ println!("Bye.");
+ Ok(())
+}
diff --git a/src/doctor.rs b/src/doctor.rs
new file mode 100644
index 0000000..69a1c4c
--- /dev/null
+++ b/src/doctor.rs
@@ -0,0 +1,161 @@
+//! `scix doctor` — diagnostic checks for installation and connectivity.
+//!
+//! Prints the version, the resolved binary path, environment-token status,
+//! a live API health check, and which AI editors were detected.
+
+use crate::error::{Result, SciXError};
+use crate::SciXClient;
+use std::path::PathBuf;
+
+/// Result of a single check, with a short status line.
+enum CheckStatus {
+ Ok(String),
+ Warn(String),
+ Fail(String),
+}
+
+impl CheckStatus {
+ fn render(&self) -> String {
+ match self {
+ Self::Ok(msg) => format!("[ ok ] {}", msg),
+ Self::Warn(msg) => format!("[warn] {}", msg),
+ Self::Fail(msg) => format!("[fail] {}", msg),
+ }
+ }
+ fn is_fail(&self) -> bool {
+ matches!(self, Self::Fail(_))
+ }
+}
+
+fn locate_binary() -> Option {
+ std::env::current_exe().ok()
+}
+
+fn check_binary() -> CheckStatus {
+ match locate_binary() {
+ Some(p) => CheckStatus::Ok(format!(
+ "scix binary v{} at {}",
+ env!("CARGO_PKG_VERSION"),
+ p.display()
+ )),
+ None => CheckStatus::Warn("cannot resolve current executable path".to_string()),
+ }
+}
+
+fn check_token() -> (CheckStatus, Option) {
+ if let Ok(t) = std::env::var("SCIX_API_TOKEN") {
+ if !t.is_empty() {
+ return (
+ CheckStatus::Ok("SCIX_API_TOKEN is set".to_string()),
+ Some(t),
+ );
+ }
+ }
+ if let Ok(t) = std::env::var("ADS_API_TOKEN") {
+ if !t.is_empty() {
+ return (CheckStatus::Ok("ADS_API_TOKEN is set".to_string()), Some(t));
+ }
+ }
+ (
+ CheckStatus::Fail(
+ "no SCIX_API_TOKEN or ADS_API_TOKEN in environment — run `scix setup`".to_string(),
+ ),
+ None,
+ )
+}
+
+async fn check_api(token: &str) -> CheckStatus {
+ let client = SciXClient::new(token);
+ match client.search("star", 1).await {
+ Ok(r) => CheckStatus::Ok(format!(
+ "SciX API reachable ({} results for probe query)",
+ r.num_found
+ )),
+ Err(SciXError::AuthRequired) | Err(SciXError::Api { status: 401, .. }) => {
+ CheckStatus::Fail("API rejected token (401 unauthorized)".to_string())
+ }
+ Err(SciXError::RateLimited { .. }) => {
+ CheckStatus::Warn("API rate-limited the probe; token is otherwise valid".to_string())
+ }
+ Err(e) => CheckStatus::Fail(format!("API call failed: {}", e)),
+ }
+}
+
+fn check_editors() -> CheckStatus {
+ let detected = crate::setup::detect_editors_public(None);
+ if detected.is_empty() {
+ CheckStatus::Warn(
+ "no supported MCP hosts detected (Claude Code/Desktop, Cursor, Zed, Gemini CLI, Codex CLI, Windsurf)"
+ .to_string(),
+ )
+ } else {
+ let names: Vec = detected.iter().map(|n| n.to_string()).collect();
+ CheckStatus::Ok(format!("MCP hosts detected: {}", names.join(", ")))
+ }
+}
+
+fn check_path() -> CheckStatus {
+ let Some(exe) = locate_binary() else {
+ return CheckStatus::Warn("cannot check PATH".to_string());
+ };
+ let Ok(path) = std::env::var("PATH") else {
+ return CheckStatus::Warn("PATH not set".to_string());
+ };
+ let parent = match exe.parent() {
+ Some(p) => p.to_path_buf(),
+ None => return CheckStatus::Warn("binary has no parent directory".to_string()),
+ };
+ let sep = if cfg!(windows) { ';' } else { ':' };
+ let parent_path = parent.as_path();
+ let on_path = path
+ .split(sep)
+ .any(|dir| std::path::Path::new(dir) == parent_path);
+ if on_path {
+ CheckStatus::Ok(format!("{} is on PATH", parent.display()))
+ } else {
+ CheckStatus::Warn(format!(
+ "binary directory {} is not on PATH",
+ parent.display()
+ ))
+ }
+}
+
+/// Run the full diagnostic check. Exits with code 1 if any check failed.
+pub async fn run_doctor() -> Result<()> {
+ println!();
+ println!("scix doctor — environment diagnostic");
+ println!("====================================");
+ println!();
+
+ let mut checks: Vec = Vec::new();
+
+ checks.push(check_binary());
+ checks.push(check_path());
+
+ let (token_check, token) = check_token();
+ let have_token = matches!(token_check, CheckStatus::Ok(_));
+ checks.push(token_check);
+
+ if let Some(t) = token {
+ checks.push(check_api(&t).await);
+ }
+
+ checks.push(check_editors());
+
+ for c in &checks {
+ println!(" {}", c.render());
+ }
+ println!();
+
+ let any_fail = checks.iter().any(|c| c.is_fail());
+ if any_fail {
+ println!("Some checks failed. Next steps:");
+ if !have_token {
+ println!(" • Run `scix setup` to acquire and store an API token.");
+ }
+ std::process::exit(1);
+ } else {
+ println!("All checks passed.");
+ }
+ Ok(())
+}
diff --git a/src/lib.rs b/src/lib.rs
index f5d9034..043580a 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -62,6 +62,12 @@ pub mod mcp;
#[cfg(feature = "cli")]
pub mod setup;
+#[cfg(feature = "cli")]
+pub mod doctor;
+
+#[cfg(feature = "cli")]
+pub mod chat;
+
#[cfg(feature = "python")]
pub mod python;
diff --git a/src/mcp.rs b/src/mcp.rs
index 2679254..bba5fed 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -147,21 +147,7 @@ async fn handle_tool_call(client: &SciXClient, id: &Value, params: &Value) -> Va
let tool_name = params["name"].as_str().unwrap_or("");
let args = ¶ms["arguments"];
- let result = match tool_name {
- "scix_search" => tool_search(client, args).await,
- "scix_bigquery" => tool_bigquery(client, args).await,
- "scix_export" => tool_export(client, args).await,
- "scix_metrics" => tool_metrics(client, args).await,
- "scix_library" => tool_library(client, args).await,
- "scix_library_documents" => tool_library_documents(client, args).await,
- "scix_citation_helper" => tool_citation_helper(client, args).await,
- "scix_network" => tool_network(client, args).await,
- "scix_object_search" => tool_object_search(client, args).await,
- "scix_resolve_reference" => tool_resolve_reference(client, args).await,
- "scix_resolve_links" => tool_resolve_links(client, args).await,
- "scix_get_paper" => tool_get_paper(client, args).await,
- _ => Err(SciXError::Config(format!("Unknown tool: {}", tool_name))),
- };
+ let result = dispatch_tool_call(client, tool_name, args).await;
match result {
Ok(content) => json!({
@@ -182,6 +168,42 @@ async fn handle_tool_call(client: &SciXClient, id: &Value, params: &Value) -> Va
}
}
+/// Dispatch a tool call by name and return its text result.
+///
+/// This is the same dispatch table used by the MCP server, exposed so direct
+/// LLM clients (e.g. `scix chat`) can drive the same set of tools without
+/// going through the MCP protocol layer.
+pub async fn dispatch_tool_call(
+ client: &SciXClient,
+ name: &str,
+ args: &Value,
+) -> Result {
+ match name {
+ "scix_search" => tool_search(client, args).await,
+ "scix_bigquery" => tool_bigquery(client, args).await,
+ "scix_export" => tool_export(client, args).await,
+ "scix_metrics" => tool_metrics(client, args).await,
+ "scix_library" => tool_library(client, args).await,
+ "scix_library_documents" => tool_library_documents(client, args).await,
+ "scix_citation_helper" => tool_citation_helper(client, args).await,
+ "scix_network" => tool_network(client, args).await,
+ "scix_object_search" => tool_object_search(client, args).await,
+ "scix_resolve_reference" => tool_resolve_reference(client, args).await,
+ "scix_resolve_links" => tool_resolve_links(client, args).await,
+ "scix_get_paper" => tool_get_paper(client, args).await,
+ _ => Err(SciXError::Config(format!("Unknown tool: {}", name))),
+ }
+}
+
+/// Public accessor for the JSON-Schema tool definitions.
+///
+/// Returns the same array as the MCP `tools/list` response. Useful for
+/// callers building direct LLM tool-use loops or for emitting tool schemas
+/// in provider-specific shapes.
+pub fn tool_definitions_value() -> Value {
+ tool_definitions()
+}
+
// --- Tool implementations ---
async fn tool_search(client: &SciXClient, args: &Value) -> Result {
diff --git a/src/setup.rs b/src/setup.rs
index f96c57e..f7dbef8 100644
--- a/src/setup.rs
+++ b/src/setup.rs
@@ -1,13 +1,15 @@
//! `scix setup` — one-command MCP server configuration for AI editors.
//!
-//! Detects installed editors (Claude Code, Claude Desktop, Cursor, Zed),
-//! prompts for an API token, validates it, and writes the correct MCP
-//! config for each editor.
+//! Detects installed editors (Claude Code, Claude Desktop, Cursor, Zed, Gemini
+//! CLI, Codex CLI, Windsurf), prompts for an API token, validates it, and
+//! writes the correct MCP config for each editor.
use crate::error::{Result, SciXError};
use crate::SciXClient;
use std::path::PathBuf;
+const TOKEN_URL: &str = "https://ui.adsabs.harvard.edu/user/settings/token";
+
/// Supported AI editors.
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum EditorTarget {
@@ -15,6 +17,9 @@ pub enum EditorTarget {
ClaudeDesktop,
Cursor,
Zed,
+ GeminiCli,
+ CodexCli,
+ Windsurf,
}
impl std::fmt::Display for EditorTarget {
@@ -24,6 +29,9 @@ impl std::fmt::Display for EditorTarget {
Self::ClaudeDesktop => write!(f, "Claude Desktop"),
Self::Cursor => write!(f, "Cursor"),
Self::Zed => write!(f, "Zed"),
+ Self::GeminiCli => write!(f, "Gemini CLI"),
+ Self::CodexCli => write!(f, "Codex CLI"),
+ Self::Windsurf => write!(f, "Windsurf"),
}
}
}
@@ -86,7 +94,21 @@ fn resolve_token(yes: bool) -> Result {
// Interactive prompt.
println!(" No API token found in environment.");
- println!(" Get a free token at: https://ui.adsabs.harvard.edu/user/settings/token");
+ println!(" Get a free token at: {}", TOKEN_URL);
+
+ let open_browser = dialoguer::Confirm::new()
+ .with_prompt(" Open the token page in your browser now?")
+ .default(true)
+ .interact()
+ .unwrap_or(false);
+ if open_browser {
+ if let Err(e) = webbrowser::open(TOKEN_URL) {
+ println!(
+ " Could not open browser ({}). Visit the URL above manually.",
+ e
+ );
+ }
+ }
println!();
let token: String = dialoguer::Password::new()
@@ -140,6 +162,15 @@ fn claude_cli_available() -> bool {
.unwrap_or(false)
}
+/// Public: return the list of editor targets detected on this system.
+/// Used by `scix doctor`.
+pub fn detect_editors_public(filter: Option) -> Vec {
+ detect_editors(filter)
+ .into_iter()
+ .map(|e| e.target)
+ .collect()
+}
+
/// Detect which editors are installed.
fn detect_editors(filter: Option) -> Vec {
let mut editors = Vec::new();
@@ -213,6 +244,42 @@ fn detect_editors(filter: Option) -> Vec {
}
}
+ // Gemini CLI (Google) — ~/.gemini/settings.json with mcpServers key.
+ if filter.is_none() || filter == Some(EditorTarget::GeminiCli) {
+ let gemini_dir = home.join(".gemini");
+ if gemini_dir.exists() {
+ editors.push(DetectedEditor {
+ target: EditorTarget::GeminiCli,
+ config_path: Some(gemini_dir.join("settings.json")),
+ use_cli: false,
+ });
+ }
+ }
+
+ // Codex CLI (OpenAI) — ~/.codex/config.toml with [mcp_servers.scix] table.
+ if filter.is_none() || filter == Some(EditorTarget::CodexCli) {
+ let codex_dir = home.join(".codex");
+ if codex_dir.exists() {
+ editors.push(DetectedEditor {
+ target: EditorTarget::CodexCli,
+ config_path: Some(codex_dir.join("config.toml")),
+ use_cli: false,
+ });
+ }
+ }
+
+ // Windsurf (Codeium) — ~/.codeium/windsurf/mcp_config.json.
+ if filter.is_none() || filter == Some(EditorTarget::Windsurf) {
+ let windsurf_dir = home.join(".codeium/windsurf");
+ if windsurf_dir.exists() {
+ editors.push(DetectedEditor {
+ target: EditorTarget::Windsurf,
+ config_path: Some(windsurf_dir.join("mcp_config.json")),
+ use_cli: false,
+ });
+ }
+ }
+
editors
}
@@ -357,6 +424,83 @@ fn configure_claude_code_cli(binary: &str, token: &str) -> ConfigResult {
}
}
+/// Update a TOML config file, inserting `[mcp_servers.scix]`.
+/// Used by Codex CLI which is TOML-native.
+fn update_toml_codex_config(
+ path: &PathBuf,
+ binary: &str,
+ token: &str,
+ yes: bool,
+) -> std::result::Result {
+ let content = if path.exists() {
+ std::fs::read_to_string(path)
+ .map_err(|e| format!("Cannot read {}: {}", path.display(), e))?
+ } else {
+ String::new()
+ };
+
+ let mut root: toml::Table = if content.trim().is_empty() {
+ toml::Table::new()
+ } else {
+ content
+ .parse()
+ .map_err(|e| format!("Could not parse {}: {}", path.display(), e))?
+ };
+
+ // Ensure [mcp_servers] table exists.
+ if !root.contains_key("mcp_servers") {
+ root.insert(
+ "mcp_servers".to_string(),
+ toml::Value::Table(toml::Table::new()),
+ );
+ }
+ let servers = root
+ .get_mut("mcp_servers")
+ .and_then(|v| v.as_table_mut())
+ .ok_or_else(|| format!("\"mcp_servers\" in {} is not a table", path.display()))?;
+
+ if servers.contains_key("scix") && !yes {
+ let overwrite = dialoguer::Confirm::new()
+ .with_prompt(format!(
+ " scix is already configured in {}. Overwrite?",
+ path.display()
+ ))
+ .default(false)
+ .interact()
+ .unwrap_or(false);
+ if !overwrite {
+ return Ok(ConfigResult::Skipped);
+ }
+ }
+
+ // Build the scix sub-table.
+ let mut scix_entry = toml::Table::new();
+ scix_entry.insert(
+ "command".to_string(),
+ toml::Value::String(binary.to_string()),
+ );
+ scix_entry.insert(
+ "args".to_string(),
+ toml::Value::Array(vec![toml::Value::String("serve".to_string())]),
+ );
+ let mut env_table = toml::Table::new();
+ env_table.insert(
+ "SCIX_API_TOKEN".to_string(),
+ toml::Value::String(token.to_string()),
+ );
+ scix_entry.insert("env".to_string(), toml::Value::Table(env_table));
+ servers.insert("scix".to_string(), toml::Value::Table(scix_entry));
+
+ if let Some(parent) = path.parent() {
+ std::fs::create_dir_all(parent)
+ .map_err(|e| format!("Cannot create {}: {}", parent.display(), e))?;
+ }
+ std::fs::write(path, toml::to_string_pretty(&root).unwrap().as_bytes())
+ .map_err(|e| format!("Cannot write {}: {}", path.display(), e))?;
+
+ Ok(ConfigResult::Configured)
+}
+
/// Configure a single editor.
fn configure_editor(editor: &DetectedEditor, binary: &str, token: &str, yes: bool) -> ConfigResult {
if editor.use_cli && editor.target == EditorTarget::ClaudeCode {
@@ -368,6 +512,17 @@ fn configure_editor(editor: &DetectedEditor, binary: &str, token: &str, yes: boo
None => return ConfigResult::Failed("no config path".to_string()),
};
+ // Codex CLI uses TOML; everyone else uses JSON with slight schema variations.
+ if editor.target == EditorTarget::CodexCli {
+ return match update_toml_codex_config(path, binary, token, yes) {
+ Ok(result) => result,
+ Err(msg) => {
+ eprintln!(" {}", msg);
+ ConfigResult::Failed("parse error".to_string())
+ }
+ };
+ }
+
let (section_key, entry) = match editor.target {
EditorTarget::Zed => ("context_servers", zed_mcp_entry(binary, token)),
_ => ("mcpServers", standard_mcp_entry(binary, token)),
@@ -419,6 +574,9 @@ pub async fn run_setup(
EditorTarget::ClaudeDesktop,
EditorTarget::Cursor,
EditorTarget::Zed,
+ EditorTarget::GeminiCli,
+ EditorTarget::CodexCli,
+ EditorTarget::Windsurf,
];
let detected = detect_editors(editor);