From 4aa9f4696f20cb836f681d51cb62881179c1ae32 Mon Sep 17 00:00:00 2001 From: John Michael Manlupig Date: Sun, 22 Nov 2026 23:44:45 +0800 Subject: [PATCH] feat: add local stdio MCP server subcommand (codeint mcp) --- crates/cli/Cargo.toml | 2 +- crates/cli/src/lib.rs | 153 +++++++++++++------ crates/cli/src/mcp.rs | 312 +++++++++++++++++++++++++++++++++++++++ crates/cli/tests/mcp.rs | 95 ++++++++++++ crates/config/src/lib.rs | 83 ++++++++--- docs/guide/README.md | 7 +- docs/guide/mcp.md | 29 ++++ docs/reference.md | 15 ++ llms.txt | 3 +- 9 files changed, 627 insertions(+), 72 deletions(-) create mode 100644 crates/cli/src/mcp.rs create mode 100644 crates/cli/tests/mcp.rs create mode 100644 docs/guide/mcp.md diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index 2ed143e..b4a5506 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -22,10 +22,10 @@ codeint-plugin-host = { workspace = true } codeint-report = { workspace = true } rayon = { workspace = true } serde = { workspace = true } +serde_json = { workspace = true } thiserror = { workspace = true } [dev-dependencies] -serde_json = { workspace = true } tempfile = { workspace = true } toon-format = { workspace = true } diff --git a/crates/cli/src/lib.rs b/crates/cli/src/lib.rs index 4eab12c..bec0ed4 100644 --- a/crates/cli/src/lib.rs +++ b/crates/cli/src/lib.rs @@ -4,6 +4,7 @@ mod check; mod commit_measurement; mod diff; mod init; +mod mcp; mod remedy; mod trend; mod update; @@ -141,26 +142,34 @@ pub fn diff( base_ref: &str, options: &DiffOptions, ) -> Result { + let report = measure_diff(folder, base_ref, options) + .map_err(|err| CodeintError::from_cli_error(CliError::Check(err)))?; + let failures = report.failure_messages(); + let passed = failures.is_empty(); + Ok(DiffOutcome { + passed, + failures, + report, + }) +} + +fn measure_diff( + folder: &Path, + base_ref: &str, + options: &DiffOptions, +) -> Result { let refs = diff::Refs { base: base_ref, head: options.head_ref.as_deref(), }; let cache = options.result_cache.clone().map(ResultCache::in_folder); - let report = diff::diff( + diff::diff( folder, refs, options.findings, cache.as_ref(), &options.plugin_host, ) - .map_err(|err| CodeintError::from_cli_error(CliError::Check(err)))?; - let failures = report.failure_messages(); - let passed = failures.is_empty(); - Ok(DiffOutcome { - passed, - failures, - report, - }) } pub fn trend(folder: &Path, options: &TrendOptions) -> Result { @@ -237,17 +246,7 @@ fn run() -> Result { findings, format, plugin_host, - } => { - let report = check::check(&folder, findings, &plugin_host)?; - write_report(&report.render(format)?, &destination)?; - Ok(Outcome::from_failures( - report - .over_budget() - .iter() - .map(ToString::to_string) - .collect(), - )) - } + } => run_check(&folder, &destination, findings, format, &plugin_host), Command::Diff { folder, base_ref, @@ -258,14 +257,13 @@ fn run() -> Result { result_cache, plugin_host, } => { - let refs = diff::Refs { - base: &base_ref, - head: head_ref.as_deref(), + let options = DiffOptions { + head_ref, + findings, + result_cache, + plugin_host, }; - let result_cache = result_cache.map(ResultCache::in_folder); - let report = diff::diff(&folder, refs, findings, result_cache.as_ref(), &plugin_host)?; - write_report(&report.render(format)?, &destination)?; - Ok(Outcome::from_failures(report.failure_messages())) + run_diff(&folder, &base_ref, &destination, format, &options) } Command::Trend { folder, @@ -274,30 +272,97 @@ fn run() -> Result { format, result_cache, plugin_host, - } => { - let result_cache = result_cache.map(ResultCache::in_folder); - let report = trend::trend(&folder, range, result_cache.as_ref(), &plugin_host)?; - write_report(&report.render(format)?, &destination)?; - Ok(Outcome::Passed) - } - Command::Init { folder } => { - let written = init::init(&folder)?; - print_report(&format!("Wrote {}\n", written.display()))?; - Ok(Outcome::Passed) - } + } => run_trend( + &folder, + range, + &destination, + format, + result_cache, + &plugin_host, + ), + Command::Init { folder } => run_init(&folder), Command::Update { check_only, version, release_base_url, - } => { - let message = - update::update(check_only, version.as_deref(), release_base_url.as_deref())?; - print_report(&format!("{message}\n"))?; - Ok(Outcome::Passed) - } + } => run_update(check_only, version.as_deref(), release_base_url.as_deref()), + Command::Mcp { + folder, + result_cache, + plugin_host, + } => run_mcp(&folder, result_cache, plugin_host), } } +fn run_init(folder: &Path) -> Result { + let written = init::init(folder)?; + print_report(&format!("Wrote {}\n", written.display()))?; + Ok(Outcome::Passed) +} + +fn run_update( + check_only: bool, + version: Option<&str>, + release_base_url: Option<&str>, +) -> Result { + let message = update::update(check_only, version, release_base_url)?; + print_report(&format!("{message}\n"))?; + Ok(Outcome::Passed) +} + +fn run_mcp( + folder: &Path, + result_cache: Option, + plugin_host: PluginHostConfig, +) -> Result { + mcp::serve_stdio(folder, result_cache, plugin_host).map_err(CliError::Output)?; + Ok(Outcome::Passed) +} + +fn run_check( + folder: &Path, + destination: &ReportDestination, + findings: FindingsShown, + format: ReportFormat, + plugin_host: &PluginHostConfig, +) -> Result { + let report = check::check(folder, findings, plugin_host)?; + write_report(&report.render(format)?, destination)?; + Ok(Outcome::from_failures( + report + .over_budget() + .iter() + .map(ToString::to_string) + .collect(), + )) +} + +fn run_diff( + folder: &Path, + base_ref: &str, + destination: &ReportDestination, + format: ReportFormat, + options: &DiffOptions, +) -> Result { + let report = measure_diff(folder, base_ref, options)?; + write_report(&report.render(format)?, destination)?; + Ok(Outcome::from_failures(report.failure_messages())) +} + +fn run_trend( + folder: &Path, + range: TrendRange, + destination: &ReportDestination, + format: TrendFormat, + result_cache: Option, + plugin_host: &PluginHostConfig, +) -> Result { + let result_cache = result_cache.map(ResultCache::in_folder); + let report = trend::trend(folder, range, result_cache.as_ref(), plugin_host)?; + write_report(&report.render(format)?, destination)?; + Ok(Outcome::Passed) +} + fn write_report(report: &str, destination: &ReportDestination) -> Result<(), CliError> { let text = format!("{report}\n"); match destination { diff --git a/crates/cli/src/mcp.rs b/crates/cli/src/mcp.rs new file mode 100644 index 0000000..e8553c7 --- /dev/null +++ b/crates/cli/src/mcp.rs @@ -0,0 +1,312 @@ +use std::io::{BufRead, Write}; +use std::path::{Path, PathBuf}; +use std::str::FromStr; + +use codeint_config::{ + CalendarDay, FindingsShown, PluginHostConfig, ReportFormat, TrendFormat, TrendRange, +}; +use serde_json::{Value, json}; + +use crate::{CheckOptions, DiffOptions, TrendOptions, check, diff, trend}; + +const DEFAULT_PROTOCOL_VERSION: &str = "2024-11-05"; + +pub(crate) fn serve_stdio( + default_folder: &Path, + result_cache: Option, + plugin_host: PluginHostConfig, +) -> Result<(), std::io::Error> { + let stdin = std::io::stdin(); + let stdout = std::io::stdout(); + let mut reader = stdin.lock(); + let mut writer = stdout.lock(); + serve( + &mut reader, + &mut writer, + default_folder, + result_cache, + plugin_host, + ) +} + +fn serve( + reader: &mut R, + writer: &mut W, + default_folder: &Path, + result_cache: Option, + plugin_host: PluginHostConfig, +) -> Result<(), std::io::Error> { + let ctx = ServerContext { + default_folder, + result_cache, + plugin_host, + }; + let mut line = String::new(); + loop { + line.clear(); + if reader.read_line(&mut line)? == 0 { + break; + } + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + if let Some(response) = handle_line(trimmed, &ctx) { + writeln!(writer, "{response}")?; + writer.flush()?; + } + } + Ok(()) +} + +struct ServerContext<'a> { + default_folder: &'a Path, + result_cache: Option, + plugin_host: PluginHostConfig, +} + +fn handle_line(line: &str, ctx: &ServerContext<'_>) -> Option { + let request: Value = match serde_json::from_str(line) { + Ok(val) => val, + Err(err) => { + return Some(rpc_error( + Value::Null, + -32700, + &format!("Parse error: {err}"), + )); + } + }; + let id = request.get("id").cloned(); + let method = request + .get("method") + .and_then(Value::as_str) + .unwrap_or_default(); + let params = request.get("params"); + let response_id = id?; + let result = dispatch(method, params, ctx); + Some(match result { + Ok(value) => json!({ "jsonrpc": "2.0", "id": response_id, "result": value }), + Err((code, message)) => rpc_error(response_id, code, &message), + }) +} + +fn dispatch( + method: &str, + params: Option<&Value>, + ctx: &ServerContext<'_>, +) -> Result { + match method { + "initialize" => Ok(handle_initialize(params)), + "ping" => Ok(json!({})), + "tools/list" => Ok(handle_tools_list()), + "tools/call" => handle_tools_call(params, ctx), + other => Err((-32601, format!("Method not found: {other}"))), + } +} + +fn handle_initialize(params: Option<&Value>) -> Value { + let protocol_version = params + .and_then(|p| p.get("protocolVersion")) + .and_then(Value::as_str) + .unwrap_or(DEFAULT_PROTOCOL_VERSION); + json!({ + "protocolVersion": protocol_version, + "capabilities": { "tools": {} }, + "serverInfo": { + "name": "codeint", + "version": env!("CARGO_PKG_VERSION"), + } + }) +} + +fn handle_tools_list() -> Value { + json!({ + "tools": [ + { + "name": "check", + "description": "Measure Software entropy of a Git repository working tree (Erosion, Duplication, Verbosity, Import cycles) and report any Budget failures.", + "inputSchema": { + "type": "object", + "properties": { + "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "all": { "type": "boolean", "description": "Return all Findings instead of the 20 worst per Metric." } + } + } + }, + { + "name": "diff", + "description": "Compare the working tree (or a head Git ref) against the merge-base of base_ref and classify Findings as new, resolved, or unchanged.", + "inputSchema": { + "type": "object", + "required": ["base_ref"], + "properties": { + "base_ref": { "type": "string", "description": "Base Git ref such as main or origin/main." }, + "head_ref": { "type": "string", "description": "Optional head Git ref instead of the working tree." }, + "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "all": { "type": "boolean", "description": "Return all Findings instead of the 20 worst per Metric." } + } + } + }, + { + "name": "trend", + "description": "Measure each main-line commit over time (latest 20 commits or since YYYY-MM-DD).", + "inputSchema": { + "type": "object", + "properties": { + "path": { "type": "string", "description": "Folder inside the Git repository (defaults to server working directory)." }, + "since": { "type": "string", "description": "UTC date YYYY-MM-DD to start the trend from." } + } + } + } + ] + }) +} + +fn handle_tools_call( + params: Option<&Value>, + ctx: &ServerContext<'_>, +) -> Result { + let name = params + .and_then(|p| p.get("name")) + .and_then(Value::as_str) + .ok_or_else(|| (-32602, "Missing tool name".to_owned()))?; + let args = params.and_then(|p| p.get("arguments")); + match name { + "check" => Ok(call_check(args, ctx)), + "diff" => Ok(call_diff(args, ctx)), + "trend" => Ok(call_trend(args, ctx)), + other => Err((-32602, format!("Unknown tool: {other}"))), + } +} + +fn call_check(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { + let folder = resolve_folder(args, ctx.default_folder); + let options = CheckOptions { + findings: parse_findings(args), + plugin_host: ctx.plugin_host.clone(), + }; + match check(&folder, &options) { + Ok(outcome) => render_outcome( + outcome.passed, + outcome.failures, + outcome.report.render(ReportFormat::Json), + ), + Err(err) => tool_err(&err.to_string()), + } +} + +fn call_diff(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { + let Some(base_ref) = args.and_then(|a| a.get("base_ref")).and_then(Value::as_str) else { + return tool_err("Missing required argument: base_ref"); + }; + let folder = resolve_folder(args, ctx.default_folder); + let options = DiffOptions { + head_ref: args + .and_then(|a| a.get("head_ref")) + .and_then(Value::as_str) + .map(str::to_owned), + findings: parse_findings(args), + result_cache: ctx.result_cache.clone(), + plugin_host: ctx.plugin_host.clone(), + }; + match diff(&folder, base_ref, &options) { + Ok(outcome) => render_outcome( + outcome.passed, + outcome.failures, + outcome.report.render(ReportFormat::Json), + ), + Err(err) => tool_err(&err.to_string()), + } +} + +fn render_outcome( + passed: bool, + failures: Vec, + rendered: Result, +) -> Value { + match rendered { + Ok(text) => { + let report: Value = serde_json::from_str(&text).unwrap_or(Value::Null); + tool_ok(json!({ + "passed": passed, + "failures": failures, + "report": report, + })) + } + Err(err) => tool_err(&err.to_string()), + } +} + +fn call_trend(args: Option<&Value>, ctx: &ServerContext<'_>) -> Value { + let folder = resolve_folder(args, ctx.default_folder); + let range = match args.and_then(|a| a.get("since")).and_then(Value::as_str) { + Some(day_str) => match CalendarDay::from_str(day_str) { + Ok(day) => TrendRange::Since(day), + Err(err) => return tool_err(&format!("Invalid since date {day_str:?}: {err}")), + }, + None => TrendOptions::default().range, + }; + let options = TrendOptions { + range, + result_cache: ctx.result_cache.clone(), + plugin_host: ctx.plugin_host.clone(), + }; + match trend(&folder, &options) { + Ok(report) => match report.render(TrendFormat::Json) { + Ok(rendered) => { + let payload: Value = serde_json::from_str(&rendered).unwrap_or(Value::Null); + tool_ok(payload) + } + Err(err) => tool_err(&err.to_string()), + }, + Err(err) => tool_err(&err.to_string()), + } +} + +fn resolve_folder(args: Option<&Value>, default_folder: &Path) -> PathBuf { + match args.and_then(|a| a.get("path")).and_then(Value::as_str) { + Some(p) if !p.is_empty() => { + let candidate = PathBuf::from(p); + if candidate.is_absolute() { + candidate + } else { + default_folder.join(candidate) + } + } + _ => default_folder.to_path_buf(), + } +} + +fn parse_findings(args: Option<&Value>) -> FindingsShown { + if args + .and_then(|a| a.get("all")) + .and_then(Value::as_bool) + .unwrap_or(false) + { + FindingsShown::All + } else { + CheckOptions::default().findings + } +} + +fn tool_ok(payload: Value) -> Value { + json!({ + "content": [{ "type": "text", "text": payload.to_string() }], + "isError": false, + }) +} + +fn tool_err(message: &str) -> Value { + json!({ + "content": [{ "type": "text", "text": message }], + "isError": true, + }) +} + +fn rpc_error(id: Value, code: i64, message: &str) -> Value { + json!({ + "jsonrpc": "2.0", + "id": id, + "error": { "code": code, "message": message }, + }) +} diff --git a/crates/cli/tests/mcp.rs b/crates/cli/tests/mcp.rs new file mode 100644 index 0000000..0ef1089 --- /dev/null +++ b/crates/cli/tests/mcp.rs @@ -0,0 +1,95 @@ +use std::io::Write; +use std::process::{Command, Stdio}; + +use serde_json::{Value, json}; +use tempfile::TempDir; + +fn init_sample_repo() -> TempDir { + let dir = TempDir::new().unwrap(); + let run_git = |args: &[&str]| { + let status = Command::new("git") + .args(args) + .current_dir(dir.path()) + .env("GIT_AUTHOR_NAME", "Test") + .env("GIT_AUTHOR_EMAIL", "test@example.com") + .env("GIT_COMMITTER_NAME", "Test") + .env("GIT_COMMITTER_EMAIL", "test@example.com") + .status() + .unwrap(); + assert!(status.success(), "git {args:?} failed"); + }; + run_git(&["init", "-q", "-b", "main"]); + std::fs::write( + dir.path().join("app.ts"), + "export function greet(x: number): number {\n return x + 1;\n}\n", + ) + .unwrap(); + run_git(&["add", "."]); + run_git(&["commit", "-q", "-m", "initial"]); + dir +} + +fn send_mcp_requests(dir: &std::path::Path, requests: &[Value]) -> Vec { + let mut child = Command::new(env!("CARGO_BIN_EXE_codeint")) + .arg("mcp") + .current_dir(dir) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + { + let mut stdin = child.stdin.take().unwrap(); + for req in requests { + writeln!(stdin, "{req}").unwrap(); + } + } + let output = child.wait_with_output().unwrap(); + assert!( + output.status.success(), + "codeint mcp failed: {}", + String::from_utf8_lossy(&output.stderr) + ); + String::from_utf8(output.stdout) + .unwrap() + .lines() + .filter(|l| !l.trim().is_empty()) + .map(|l| serde_json::from_str(l).unwrap()) + .collect() +} + +#[test] +fn mcp_initialize_list_and_call_tools() { + let repo = init_sample_repo(); + let responses = send_mcp_requests( + repo.path(), + &[ + json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2024-11-05"}}), + json!({"jsonrpc": "2.0", "method": "notifications/initialized"}), + json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list"}), + json!({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "check", "arguments": {}}}), + json!({"jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": {"name": "diff", "arguments": {"base_ref": "main"}}}), + json!({"jsonrpc": "2.0", "id": 5, "method": "tools/call", "params": {"name": "trend", "arguments": {}}}), + json!({"jsonrpc": "2.0", "id": 6, "method": "unknown/method"}), + ], + ); + assert_eq!(responses.len(), 6); + assert_eq!(responses[0]["result"]["serverInfo"]["name"], "codeint"); + let tools = responses[1]["result"]["tools"].as_array().unwrap(); + let names: Vec<&str> = tools.iter().map(|t| t["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["check", "diff", "trend"]); + + assert_eq!(responses[2]["result"]["isError"], false); + let check_payload: Value = serde_json::from_str( + responses[2]["result"]["content"][0]["text"] + .as_str() + .unwrap(), + ) + .unwrap(); + assert_eq!(check_payload["passed"], true); + assert_eq!(check_payload["report"]["files"], 1); + + assert_eq!(responses[3]["result"]["isError"], false); + assert_eq!(responses[4]["result"]["isError"], false); + assert_eq!(responses[5]["error"]["code"], -32601); +} diff --git a/crates/config/src/lib.rs b/crates/config/src/lib.rs index b910789..5f9a88b 100644 --- a/crates/config/src/lib.rs +++ b/crates/config/src/lib.rs @@ -136,6 +136,11 @@ pub enum Command { version: Option, release_base_url: Option, }, + Mcp { + folder: PathBuf, + result_cache: Option, + plugin_host: PluginHostConfig, + }, } #[derive(Debug)] @@ -225,6 +230,10 @@ enum CommandArguments { )] version: Option, }, + #[command( + about = "Run a local stdio Model Context Protocol (MCP) server exposing check, diff, and trend tools" + )] + Mcp, } #[derive(Debug, clap::Args)] @@ -250,27 +259,14 @@ pub fn read_invocation() -> Result { let arguments = Arguments::parse(); let current_folder = std::env::current_dir().map_err(ConfigError::CurrentFolder)?; let command = match arguments.command { - CommandArguments::Check { path, report } => Command::Check { - folder: existing_folder(¤t_folder, path)?, - destination: report_destination(¤t_folder, report.output)?, - findings: findings_shown(report.all), - format: report.format, - plugin_host: plugin_host_config_of_this_process(¤t_folder), - }, + CommandArguments::Check { path, report } => { + build_check_command(¤t_folder, path, report)? + } CommandArguments::Diff { base_ref, head_ref, report, - } => Command::Diff { - folder: current_folder.clone(), - base_ref, - head_ref, - destination: report_destination(¤t_folder, report.output)?, - findings: findings_shown(report.all), - format: report.format, - result_cache: result_cache_folder_of_this_process(¤t_folder), - plugin_host: plugin_host_config_of_this_process(¤t_folder), - }, + } => build_diff_command(¤t_folder, base_ref, head_ref, report)?, CommandArguments::Trend { since, output, @@ -289,17 +285,58 @@ pub fn read_invocation() -> Result { CommandArguments::Init => Command::Init { folder: current_folder, }, - CommandArguments::Update { check, version } => Command::Update { - check_only: check, - version, - release_base_url: std::env::var(RELEASE_BASE_URL_VARIABLE) - .ok() - .filter(|value| !value.is_empty()), + CommandArguments::Update { check, version } => build_update_command(check, version), + CommandArguments::Mcp => Command::Mcp { + result_cache: result_cache_folder_of_this_process(¤t_folder), + plugin_host: plugin_host_config_of_this_process(¤t_folder), + folder: current_folder, }, }; Ok(Invocation { command }) } +fn build_check_command( + current_folder: &Path, + path: Option, + report: ReportArguments, +) -> Result { + Ok(Command::Check { + folder: existing_folder(current_folder, path)?, + destination: report_destination(current_folder, report.output)?, + findings: findings_shown(report.all), + format: report.format, + plugin_host: plugin_host_config_of_this_process(current_folder), + }) +} + +fn build_diff_command( + current_folder: &Path, + base_ref: String, + head_ref: Option, + report: ReportArguments, +) -> Result { + Ok(Command::Diff { + folder: current_folder.to_path_buf(), + base_ref, + head_ref, + destination: report_destination(current_folder, report.output)?, + findings: findings_shown(report.all), + format: report.format, + result_cache: result_cache_folder_of_this_process(current_folder), + plugin_host: plugin_host_config_of_this_process(current_folder), + }) +} + +fn build_update_command(check_only: bool, version: Option) -> Command { + Command::Update { + check_only, + version, + release_base_url: std::env::var(RELEASE_BASE_URL_VARIABLE) + .ok() + .filter(|value| !value.is_empty()), + } +} + fn result_cache_folder_of_this_process(current_folder: &Path) -> Option { result_cache_folder::result_cache_folder( current_folder, diff --git a/docs/guide/README.md b/docs/guide/README.md index 1bb6423..26e560d 100644 --- a/docs/guide/README.md +++ b/docs/guide/README.md @@ -9,9 +9,10 @@ Each page below focuses on one topic and links to [docs/reference.md](../referen 2. [Getting Started](./getting-started.md): install codeint, initialize `codeint.json`, and run your first `check`, `diff`, and `trend`. 3. [Configuration (`codeint.json`)](./configuration.md): set Budgets, Regression limits, Source-set globs, and multi-language folders. 4. [Built-in Languages](./languages.md): how TypeScript/JavaScript, Rust, PHP, Dart, and Python are measured, plus their calibrated Reference ranges. -5. [CI and GitHub Actions](./ci-and-github-actions.md): gate pull requests with `codeint diff` and upload SARIF findings to GitHub code scanning. -6. [Programmatic API](../programmatic.md): call codeint from JavaScript, TypeScript, or Rust. -7. [Plugins](../plugins.md): build, hash, declare, and test external WebAssembly Language and Metric plugins. +5. [CI and GitHub Actions](./ci-and-github-actions.md): gate pull requests with the reusable GitHub Action or `codeint diff` and SARIF upload. +6. [Coding-Agent Integration (MCP Server)](./mcp.md): connect `codeint mcp` to Claude Code, Cursor, Codex, or Antigravity. +7. [Programmatic API](../programmatic.md): call codeint from JavaScript, TypeScript, or Rust. +8. [Plugins](../plugins.md): build, hash, declare, and test external WebAssembly Language and Metric plugins. ## Reference and domain docs diff --git a/docs/guide/mcp.md b/docs/guide/mcp.md new file mode 100644 index 0000000..df06b6d --- /dev/null +++ b/docs/guide/mcp.md @@ -0,0 +1,29 @@ +# Coding-Agent Integration (MCP Server) + +`codeint mcp` runs a local Model Context Protocol (MCP) server over standard input and standard output with no open network port. +Coding agents can call `check`, `diff`, and `trend` directly as structured tools to catch Software entropy Regressions before opening a pull request. + +## Exposed tools + +| Tool | Required arguments | Optional arguments | Purpose | +| ---- | ------------------ | ------------------ | ------- | +| `check` | none | `path`, `all` | Measure the working tree and report any Budget failures. | +| `diff` | `base_ref` | `head_ref`, `path`, `all` | Compare against the merge-base of `base_ref` and classify Findings as new, resolved, or unchanged. | +| `trend` | none | `path`, `since` (`YYYY-MM-DD`) | Measure each main-line commit over time. | + +## Configure in your coding agent + +Add `codeint mcp` as a stdio MCP server in your client configuration (Claude Code, Cursor, Codex, or Antigravity): + +```json +{ + "mcpServers": { + "codeint": { + "command": "codeint", + "args": ["mcp"] + } + } +} +``` + +If you run codeint through npm without a global binary install, set `"command": "npx"` and `"args": ["-y", "codeint", "mcp"]`. diff --git a/docs/reference.md b/docs/reference.md index 343bbcc..a75ffea 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -28,6 +28,7 @@ The working tree adds `src/route.ts`, an eroded function that is not committed. | `trend` | Measure each commit of the main line and print each Metric over time; see [`codeint trend`](#codeint-trend) | | `init` | Write a starter `codeint.json`; see [`codeint init`](#codeint-init) | | `update` | Update a standalone codeint binary in place from GitHub Releases; see [`codeint update`](#codeint-update) | +| `mcp` | Run a local stdio Model Context Protocol (MCP) server exposing `check`, `diff`, and `trend` tools; see [`codeint mcp`](#codeint-mcp) | | `help` | Print the help of codeint, or of the command that follows it | | Option | Meaning | @@ -478,6 +479,20 @@ codeint update --check --version v0.4.0 codeint 0.4.0 is already up to date (v0.4.0) ``` +### `codeint mcp` + +| Option | Meaning | +| ------ | ------- | +| `-h, --help` | Print the help of `codeint mcp` | + +`codeint mcp` runs a local Model Context Protocol (MCP) server over standard input and standard output with no open network port. +It exposes three read-only tools (`check`, `diff`, and `trend`) so coding agents can measure Software entropy and fix Regressions before opening a pull request. +When standard input closes, the server exits with code 0: + +```sh exit=0 +codeint mcp +``` + ## Exit codes | Exit code | Meaning | diff --git a/llms.txt b/llms.txt index 75efce1..8b684bd 100644 --- a/llms.txt +++ b/llms.txt @@ -9,7 +9,8 @@ - [Getting Started](docs/guide/getting-started.md): install codeint, initialize `codeint.json`, and run `check`, `diff`, `trend`, and `update`. - [Configuration](docs/guide/configuration.md): configure `codeint.json` Budgets, Regression limits, Source sets, and multi-language folders. - [Built-in Languages](docs/guide/languages.md): TypeScript/JavaScript, Rust, PHP, Dart, and Python rules and calibrated Reference ranges. -- [CI and GitHub Actions](docs/guide/ci-and-github-actions.md): pull-request diff gating and SARIF code scanning setup. +- [CI and GitHub Actions](docs/guide/ci-and-github-actions.md): reusable GitHub Action with sticky pull-request comment and SARIF code scanning setup. +- [Coding-Agent Integration (MCP Server)](docs/guide/mcp.md): local stdio MCP server (`codeint mcp`) exposing read-only `check`, `diff`, and `trend` tools. ## Reference and APIs