Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@ serde_json = { version = "1", features = ["preserve_order", "raw_value"] }
tempfile = "=3.27.0"
thiserror = "2"
tokio = { version = "1", features = ["rt", "macros", "time", "process", "io-std", "io-util", "fs"] }
toml_edit = "=0.25.15"
toml_edit = { version = "=0.25.15", features = ["serde"] }
toml_parser = "=1.1.3"
url = "2"
uuid = { version = "1", features = ["serde"] }
webbrowser = "1"
Expand Down
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,25 @@ New entries use this executable's absolute path and store no credentials.
Claude Code uses the top-level `mcpServers` in `~/.claude.json`.
A custom `CLAUDE_CONFIG_DIR` requires manual configuration with `--print`.

Inspect an existing registration with `proofline agent status codex` or
`proofline agent status claude-code` (also supports `cursor`, `gemini` and `kiro`).
This read-only, offline command reports the user-level configuration path and
whether its registration is missing, invalid, valid, or unable to be verified.
Local/project scopes are not inspected; a missing user-level entry does not mean
Proofline is absent from every scope. Connectivity and authentication are not
checked, and the configured command is never run. Validated origins and their
sources are reported: registration arguments, registration environment, or the
CLI default. Alternate valid origins are accepted. Status rejects explicit
`--base-url` and `--org` options; these do not override the inspected registration.
The invoking process's organization environment is ignored for status inspection.
Custom launchers, remote HTTP transports and relative executables may require
manual verification. Symlinked configuration files are read without changing
them or their targets. An absolute `CODEX_HOME` is respected; custom
`CLAUDE_CONFIG_DIR` configurations require manual inspection. JSON inspection
uses the last repeated member, while installation retains its duplicate-key
safeguards. Valid and unverifiable outcomes exit 0; missing and invalid outcomes
exit 1. Command or output failures also exit nonzero.

See the [CLI documentation](https://proofline.sh/docs/cli/) for commands.

`proofline review --path src/main.rs` reviews only that file's local changes
Expand Down
28 changes: 21 additions & 7 deletions src/agent.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
//! User-level configuration for the existing credential-free MCP launcher.

mod config;
mod status;
mod store;

#[cfg(test)]
Expand All @@ -25,6 +26,15 @@ pub(crate) struct AgentArgs {
enum AgentCommand {
/// Add Proofline to a coding agent's user configuration after confirmation.
Install(InstallArgs),
/// Inspect user-level MCP configuration offline; project scopes, connectivity and authentication are not checked.
#[command(
after_help = "Status does not accept --base-url or --org; origin and organization are read from the registration."
)]
Status {
/// Coding agent whose user configuration is inspected (read-only).
#[arg(value_enum)]
client: Client,
},
}

#[derive(Debug, Args)]
Expand Down Expand Up @@ -162,16 +172,20 @@ enum Outcome {
Installed,
}

pub(crate) async fn run(args: AgentArgs, origin: Origin) -> anyhow::Result<()> {
tokio::task::spawn_blocking(move || {
let AgentCommand::Install(args) = args.command;
pub(crate) async fn run(args: AgentArgs, base_url: String) -> anyhow::Result<crate::Verdict> {
tokio::task::spawn_blocking(move || -> anyhow::Result<crate::Verdict> {
let args = match args.command {
AgentCommand::Status { client } => return status::run(client),
AgentCommand::Install(args) => args,
};
let origin = Origin::parse(&base_url)?;
let home = std::env::home_dir().ok_or(InstallError::Home)?;
let codex_home = std::env::var_os("CODEX_HOME");
if args.client == Client::ClaudeCode
&& !args.print
&& std::env::var_os("CLAUDE_CONFIG_DIR").is_some()
{
return Err(InstallError::CustomClaudeHome);
return Err(InstallError::CustomClaudeHome.into());
}
let stdin = io::stdin();
let stdout = io::stdout();
Expand All @@ -184,11 +198,11 @@ pub(crate) async fn run(args: AgentArgs, origin: Origin) -> anyhow::Result<()> {
&mut stdin.lock(),
&mut stdout.lock(),
&mut stderr.lock(),
)
)?;
Ok(crate::Verdict::Done)
})
.await
.map_err(InstallError::Task)??;
Ok(())
.map_err(InstallError::Task)?
}

fn install(
Expand Down
252 changes: 252 additions & 0 deletions src/agent/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,110 @@ pub(super) fn prepare(
}
}

pub(super) fn registration(client: Client, bytes: &[u8]) -> Result<Option<Value>, InstallError> {
let document: Value = if client == Client::Codex {
let raw = std::str::from_utf8(bytes).map_err(|_| InstallError::InvalidConfig(client))?;
let document = bounded_toml(raw)?;
Value::deserialize(toml_edit::de::Deserializer::from(document))
.map_err(|_| InstallError::InvalidConfig(client))?
} else {
// Client JSON parsers use the last occurrence of a repeated member.
serde_json::from_slice(bytes).map_err(|_| InstallError::InvalidConfig(client))?
};
let root = document.as_object().ok_or(InstallError::ConfigShape {
client,
member: "root",
})?;
let member = if client == Client::Codex {
"mcp_servers"
} else {
"mcpServers"
};
let Some(servers) = root.get(member) else {
return Ok(None);
};
let servers = servers
.as_object()
.ok_or(InstallError::ConfigShape { client, member })?;
Ok(servers.get("proofline").cloned())
}

fn bounded_toml(raw: &str) -> Result<toml_edit::Document<&str>, InstallError> {
use toml_parser::parser::{EventKind, RecursionGuard, parse_document};

// Inspect flat events before tree construction, whose error cleanup can
// itself recurse. Reuse the same lexer/parser as toml_edit, including quoted
// keys, strings and comments. The guard bounds the event parser's recursion.
let tokens = toml_parser::Source::new(raw).lex().into_vec();
let mut events = Vec::new();
let mut error = None;
parse_document(
&tokens,
&mut RecursionGuard::new(&mut events, 64),
&mut error,
);
if error.is_some() {
return Err(InstallError::InvalidConfig(Client::Codex));
}
let mut containers = Vec::new();
let mut table_depth = 0;
let mut key_depth = 0;
let mut value_depth = 0;
for event in events {
match event.kind() {
EventKind::StdTableOpen | EventKind::ArrayTableOpen => key_depth = 0,
EventKind::SimpleKey => key_depth += 1,
EventKind::StdTableClose | EventKind::ArrayTableClose => {
table_depth = key_depth + usize::from(event.kind() == EventKind::ArrayTableClose);
key_depth = 0;
}
EventKind::KeyValSep => {
value_depth = containers.last().copied().unwrap_or(table_depth) + key_depth;
key_depth = 0;
}
EventKind::InlineTableOpen | EventKind::ArrayOpen => {
if value_depth > 64 {
return Err(InstallError::InvalidConfig(Client::Codex));
}
containers.push(value_depth);
value_depth += 1;
}
EventKind::InlineTableClose | EventKind::ArrayClose => {
value_depth = containers.pop().unwrap_or(0);
}
EventKind::ValueSep => value_depth = containers.last().copied().unwrap_or(0) + 1,
EventKind::Scalar if value_depth > 64 => {
return Err(InstallError::InvalidConfig(Client::Codex));
}
_ => {}
}
if key_depth > 64 || table_depth > 64 {
return Err(InstallError::InvalidConfig(Client::Codex));
}
}
let document =
toml_edit::Document::parse(raw).map_err(|_| InstallError::InvalidConfig(Client::Codex))?;
// Array-of-table ancestors add implicit containers to header paths. The flat
// guard bounds these to at most twice its limit, including error cleanup;
// check the exact structural depth before recursive serde conversion.
let mut pending = vec![(document.as_item(), 0_usize)];
while let Some((item, depth)) = pending.pop() {
if depth > 64 {
return Err(InstallError::InvalidConfig(Client::Codex));
}
if let Some(table) = item.as_table_like() {
pending.extend(table.iter().map(|(_, item)| (item, depth + 1)));
} else {
let mut index = 0;
while let Some(child) = item.get(index) {
pending.push((child, depth + 1));
index += 1;
}
}
}
Ok(document)
}

fn arguments(origin: &Origin) -> [String; 3] {
["--base-url".to_owned(), origin.as_key(), "mcp".to_owned()]
}
Expand Down Expand Up @@ -271,3 +375,151 @@ impl<'de> Visitor<'de> for UniqueVisitor {
Ok(UniqueJson)
}
}

#[cfg(test)]
mod tests {
use clap::ValueEnum as _;
use serde_json::json;

use super::{Client, InstallError, registration};

#[test]
fn json_extraction_uses_the_effective_container_and_registration() {
for client in Client::value_variants()
.iter()
.copied()
.filter(|client| *client != Client::Codex)
{
for (raw, expected) in [
(br#"{}"#.as_slice(), None),
(br#"{"mcpServers":{"other":{"command":"private-status-canary"}}}"#.as_slice(), None),
(br#"{"mcpServers":{"proofline":null}}"#.as_slice(), Some(json!(null))),
(br#"{"mcpServers":null,"mcpServers":{"proofline":null,"proofline":{"command":"old","command":"proofline","args":[],"args":["mcp"]}}}"#.as_slice(), Some(json!({"command":"proofline","args":["mcp"]}))),
(br#"{"mcpServers":{"proofline":{},"proofline":null}}"#.as_slice(), Some(json!(null))),
] {
assert_eq!(registration(client, raw).unwrap(), expected);
}
for raw in [b"[]".as_slice(), b"null".as_slice()] {
assert!(matches!(
registration(client, raw),
Err(InstallError::ConfigShape { member: "root", .. })
));
}
for raw in [
br#"{"mcpServers":null}"#.as_slice(),
br#"{"mcpServers":[]}"#.as_slice(),
] {
assert!(matches!(
registration(client, raw),
Err(InstallError::ConfigShape {
member: "mcpServers",
..
})
));
}
for raw in [b"\xff".as_slice(), b"{".as_slice()] {
assert!(matches!(
registration(client, raw),
Err(InstallError::InvalidConfig(_))
));
}
}
}

#[test]
fn toml_extraction_accepts_tables_and_keeps_syntax_validation_strict() {
for raw in [
"[mcp_servers.proofline]\ncommand='proofline'\nargs=['mcp']\n",
"mcp_servers={proofline={command='proofline',args=['mcp']}}\nwhen=2026-11-06T12:00:00Z\n",
"'a.b' = { 'c.d' = '''{ [ x.y = z ] }''' } # { [ ignored.key\n[mcp_servers.proofline]\ncommand='proofline'\nargs=['mcp']\n",
] {
assert_eq!(
registration(Client::Codex, raw.as_bytes()).unwrap(),
Some(json!({"command":"proofline","args":["mcp"]}))
);
}
for raw in ["", "[mcp_servers.other]\ncommand='other'\n"] {
assert!(
registration(Client::Codex, raw.as_bytes())
.unwrap()
.is_none()
);
}
assert_eq!(
registration(Client::Codex, b"mcp_servers={proofline=42}").unwrap(),
Some(json!(42))
);
assert!(matches!(
registration(Client::Codex, b"mcp_servers=[]"),
Err(InstallError::ConfigShape {
member: "mcp_servers",
..
})
));
for raw in [
b"\xff".as_slice(),
b"[mcp_servers.proofline".as_slice(),
b"private='private-status-canary'\nprivate='duplicate'".as_slice(),
b"[mcp_servers.proofline]\ncommand='first'\ncommand='last'".as_slice(),
] {
assert!(matches!(
registration(Client::Codex, raw),
Err(InstallError::InvalidConfig(_))
));
}
}

#[test]
fn toml_inspection_bounds_structural_depth_including_dotted_keys_and_arrays() {
for (raw, valid) in [
(format!("{} = 1\n", vec!["x"; 64].join(".")), true),
(format!("{} = 1\n", vec!["x"; 65].join(".")), false),
(format!("a = {{ {} = 1 }}\n", vec!["x"; 63].join(".")), true),
(
format!("a = {{ {} = 1 }}\n", vec!["x"; 64].join(".")),
false,
),
(format!("a = {}1{}\n", "[".repeat(63), "]".repeat(63)), true),
(
format!("a = {}1{}\n", "[".repeat(64), "]".repeat(64)),
false,
),
(format!("[[{}]]\na = 1\n", vec!["x"; 62].join(".")), true),
(format!("[[{}]]\na = 1\n", vec!["x"; 63].join(".")), false),
] {
let result = registration(Client::Codex, raw.as_bytes());
if valid {
assert!(result.unwrap().is_none());
} else {
assert!(matches!(
result,
Err(InstallError::InvalidConfig(Client::Codex))
));
}
}
for (ancestors, valid) in [(31, true), (32, false)] {
let mut raw: String = (1..=ancestors)
.map(|depth| format!("[[{}]]\n", vec!["x"; depth].join(".")))
.collect();
raw.push_str("a = 1\n");
let result = registration(Client::Codex, raw.as_bytes());
if valid {
assert!(result.unwrap().is_none());
} else {
assert!(matches!(
result,
Err(InstallError::InvalidConfig(Client::Codex))
));
}
}
let raw = format!(
"{} = 1\n[mcp_servers]\nproofline = 42\n",
vec!["x"; 65].join(".")
);
let origin = crate::origin::Origin::parse("https://proofline.sh").unwrap();
assert!(matches!(
super::prepare(Client::Codex, Some(raw.as_bytes()), &origin),
Ok(super::Update::Existing)
));
}
}
Loading