use crate::cli::verbs::{self, Output, Overrides};
use serde_json::{Value, json};
use std::io::{BufRead, Write};
const PROTOCOL: &str = "2025-06-18";
const SKILL_URI: &str = "skill://elinvar/SKILL.md";
const INSTRUCTIONS: &str = "Elinvar checks designs written in its Alloy 6 subset by searching \
every case up to a finite scope. Read the `skill://elinvar/SKILL.md` resource (or call \
`explain` with `{\"code\": \"skill\"}`) before writing a model for the supported subset and \
workflow. Verdicts: `holds` means no counterexample up to the scope searched (not an \
unbounded proof); `vacuous` means the rules contradict each other and allow no case at all \
(never report `vacuous` or `unknown` as `holds`); `counterexample` is refereed and shrunk. \
In temporal models, every step predicate must state what stays unchanged.";
fn resources() -> Value {
let mut out = vec![json!({
"uri": SKILL_URI,
"name": "elinvar-skill",
"title": "Elinvar Agent Skill Guide",
"description": "How to model designs in Elinvar's Alloy 6 subset, read verdicts, and iterate.",
"mimeType": "text/markdown"
})];
for spec in crate::cli::schemas::SCHEMAS {
out.push(json!({
"uri": spec.uri,
"name": format!("{}-v1-schema", spec.name),
"title": spec.title,
"description": spec.description,
"mimeType": "application/schema+json"
}));
}
Value::Array(out)
}
fn read_resource(uri: &str) -> Result<Value, (i64, String)> {
if uri == SKILL_URI {
return Ok(json!({
"contents": [{
"uri": SKILL_URI,
"mimeType": "text/markdown",
"text": verbs::SKILL
}]
}));
}
if let Some(spec) = crate::cli::schemas::by_uri(uri) {
return Ok(json!({
"contents": [{
"uri": spec.uri,
"mimeType": "application/schema+json",
"text": spec.text
}]
}));
}
Err((-32002, format!("no resource `{uri}`")))
}
fn model_props() -> Value {
json!({
"model": { "type": "string", "description": "the model, as Alloy 6 text in the subset of LOGIC.md section 15" },
"command": { "type": "string", "description": "the command to run, by name; all of this kind when absent" },
"scope": { "type": "integer", "minimum": 0, "description": "the scope of every top-level signature the command does not name" },
"steps": { "type": "integer", "minimum": 1, "description": "at most this many states in a trace" },
"budget": { "type": "integer", "minimum": 1, "description": "at most this many solver conflicts per solve" },
"timeout": { "type": "string", "description": "wall-clock time limit per solve (e.g. `30s`, `500ms`, `2m`)" },
"explain": { "type": "boolean", "description": "on holds, proved, or vacuous checks, or a run with no instance, extract the minimal unsat core of rules that established the verdict" },
"brief": { "type": "boolean", "description": "omit empty relations and ordering helpers from text output" },
"induction": { "type": "integer", "minimum": 1, "description": "prove `always P` for any number of steps by k-induction" },
"climb": { "type": "boolean", "description": "climb scopes automatically under budget until a hole is found or budget runs out" },
"no_slicing": { "type": "boolean", "description": "on check, solve every check whole instead of slicing it first: slower, and the reference answer" },
"symmetry": { "type": "integer", "minimum": 0, "description": "symmetry-breaking predicate length (default 20; 0 disables symmetry breaking)" },
"no_overflow": { "type": "boolean", "description": "forbid signed integer overflow (Alloy `noOverflow`; off by default)" },
"summary": { "type": "boolean", "description": "return a compact summary table across all checks" },
"shrink": { "type": "boolean", "description": "on run, shrink the found instance to the fewest atoms and tuples" },
"all": { "type": "boolean", "description": "on run, enumerate all non-isomorphic instances up to scope" },
"limit": { "type": "integer", "minimum": 1, "description": "maximum instances to return with `all`" },
"sql": { "type": "boolean", "description": "on run with `all`, also render each instance as SQL inserts" },
"is_sql": { "type": "boolean", "description": "treat `model` as SQL DDL, as the command line treats a `.sql` file" },
"promises": { "type": "string", "description": "Alloy promises and predicates appended to the model, as `--with FILE.als`" },
"views": { "type": "string", "description": "with `is_sql`, SQL views and queries appended to the schema, as `--with FILE.sql`" },
"tables": { "type": "array", "items": { "type": "string" }, "description": "with `is_sql`, only these tables and their FK targets" },
"with_referencing": { "type": "boolean", "description": "with `tables`, also include tables pointing into the slice" },
"from_any": { "type": "boolean", "description": "with `is_sql`, start traces from any allowed state, not from empty tables" }
})
}
fn sql_props(mut props: Value) -> Value {
let extra = json!({
"is_sql": { "type": "boolean", "description": "treat `model` as SQL DDL, as the command line treats a `.sql` file" },
"promises": { "type": "string", "description": "Alloy promises appended to the model, as `--with FILE.als`" },
"views": { "type": "string", "description": "with `is_sql`, SQL views and queries appended to the schema, as `--with FILE.sql`" },
"tables": { "type": "array", "items": { "type": "string" }, "description": "with `is_sql`, only these tables and their FK targets" },
"with_referencing": { "type": "boolean", "description": "with `tables`, also include tables pointing into the slice" }
});
if let (Some(p), Some(e)) = (props.as_object_mut(), extra.as_object()) {
for (k, v) in e {
p.insert(k.clone(), v.clone());
}
}
props
}
fn tools() -> Value {
json!([
{
"name": "check",
"description": "Check every assertion of a model, or the one named. Each result is holds (up to the scope), counterexample (shrunk, as a story and as data), vacuous (the rules allow no case: fix the rules), or unknown (budget ran out).",
"inputSchema": { "type": "object", "properties": model_props(), "required": ["model"] }
},
{
"name": "run",
"description": "Find an instance of every run command of a model, or the one named.",
"inputSchema": { "type": "object", "properties": model_props(), "required": ["model"] }
},
{
"name": "diff",
"description": "Compare two Alloy models sharing the same signatures and fields, finding minimal shrunk cases allowed by one and forbidden by the other.",
"inputSchema": {
"type": "object",
"properties": {
"old_model": { "type": "string", "description": "the old model text (Alloy 6, or SQL DDL when `sql` is true)" },
"new_model": { "type": "string", "description": "the new model text (Alloy 6, or SQL DDL when `sql` is true)" },
"of": { "type": "string", "description": "optional function, parameterized predicate, or expression to compare between both models" },
"sql": { "type": "boolean", "description": "treat both inputs as SQL DDL schemas (compares triggers too; unchanged unread rules are listed once)" },
"tables": { "type": "array", "items": { "type": "string" }, "description": "for SQL schemas, compare only these tables and their FK targets" },
"with_referencing": { "type": "boolean", "description": "with tables, also include tables pointing into the slice" },
"ignore_unread": { "type": "boolean", "description": "for SQL schemas, compare read rules and list differing unread rules under not_compared instead of aborting" },
"from_any": { "type": "boolean", "description": "for SQL schemas, start traces from any allowed state" },
"from_empty": { "type": "boolean", "description": "for SQL schemas, start traces from empty tables" },
"scope": { "type": "integer", "minimum": 0, "description": "scope per top-level signature (default 3)" },
"steps": { "type": "integer", "minimum": 1, "description": "at most this many states in a trace" },
"budget": { "type": "integer", "minimum": 1, "description": "at most this many solver conflicts per solve" },
"timeout": { "type": "string", "description": "wall-clock time limit per solve (e.g. `30s`, `500ms`, `2m`)" },
"no_slicing": { "type": "boolean", "description": "solve each side whole instead of slicing it first: slower, and the reference answer" }
},
"required": ["old_model", "new_model"]
}
},
{
"name": "import_sql",
"description": "Import SQL DDL (CREATE TABLE, CREATE UNIQUE INDEX, PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY / REFERENCES, CHECK) into an Alloy 6 model in Elinvar's subset.",
"inputSchema": {
"type": "object",
"properties": {
"sql": { "type": "string", "description": "SQL DDL schema text" },
"strict": { "type": "boolean", "description": "fail if any SQL statement or constraint was skipped" },
"temporal": { "type": "boolean", "description": "emit stateful var tables, insert/update/delete steps, and triggers" },
"from_empty": { "type": "boolean", "description": "with temporal, require all tables to start empty so every state is reached by steps" },
"tables": { "type": "array", "items": { "type": "string" }, "description": "import only these tables and their foreign-key targets" },
"with_referencing": { "type": "boolean", "description": "with tables, also include tables that point into the slice via foreign keys" },
"only_ruled": { "type": "boolean", "description": "omit columns not referenced by any key, index, constraint, or trigger" }
},
"required": ["sql"]
}
},
{
"name": "render",
"description": "Render an instance or trace from a check/run result as Graphviz DOT, Mermaid, or executable SQL, or render an Alloy model's structure as DOT or Mermaid.",
"inputSchema": {
"type": "object",
"properties": {
"result": { "type": "object", "description": "one result object from check or run" },
"model": { "type": "string", "description": "an Alloy model text to draw as a schema/step diagram (alternative to `result`)" },
"format": { "type": "string", "enum": ["dot", "mermaid", "sql"], "description": "output format: dot (default), mermaid, or sql" },
"state": { "type": "integer", "minimum": 0, "description": "for a trace, render only this state" }
}
}
},
{
"name": "eval",
"description": "Evaluate an expression or formula on the instance or trace of a result from check or run, at a state, without solving again.",
"inputSchema": {
"type": "object",
"properties": sql_props(json!({
"model": { "type": "string", "description": "the model text the result came from" },
"result": { "type": "object", "description": "one result object from check or run" },
"expression": { "type": "string", "description": "an expression or formula in the model" },
"state": { "type": "integer", "minimum": 0, "description": "the state, from 0" }
})),
"required": ["model", "result", "expression"]
}
},
{
"name": "tests",
"description": "Generate step reachability tests and per-guard refusal tests from a model with steps (or a SQL schema).",
"inputSchema": {
"type": "object",
"properties": {
"model": { "type": "string", "description": "the Alloy model (or SQL DDL when `is_sql` is true)" },
"is_sql": { "type": "boolean", "description": "treat `model` as SQL DDL (imported with --temporal --from-empty)" },
"sql": { "type": "boolean", "description": "render SQL replay scripts for each test case" },
"tables": { "type": "array", "items": { "type": "string" }, "description": "for SQL schemas, test only these tables and their FK targets" },
"with_referencing": { "type": "boolean", "description": "with tables, also include tables pointing into the slice" },
"allow_dead": { "type": "array", "items": { "type": "string" }, "description": "step names expected to be dead" },
"scope": { "type": "integer", "minimum": 1 },
"steps": { "type": "integer", "minimum": 1 },
"budget": { "type": "integer", "minimum": 1 },
"timeout": { "type": "string", "description": "wall-clock time limit per test (e.g. `30s`, `500ms`)" }
},
"required": ["model"]
}
},
{
"name": "accepts",
"description": "Check whether a trace JSON or SQL DML script is allowed by a model and whether every check holds along it.",
"inputSchema": {
"type": "object",
"properties": sql_props(json!({
"model": { "type": "string", "description": "the Alloy model text, or SQL DDL with `is_sql`" },
"trace": { "type": "string", "description": "a trace/result JSON string or SQL DML script" }
})),
"required": ["model", "trace"]
}
},
{
"name": "discover",
"description": "Discover and prove common invariants of a SQL schema by k-induction, listing each proved invariant in plain English together with the triggers and rules it rests on.",
"inputSchema": {
"type": "object",
"properties": {
"sql": { "type": "string", "description": "SQL DDL schema text" },
"tables": { "type": "array", "items": { "type": "string" }, "description": "discover invariants only on these tables (plus their FK targets)" },
"with_referencing": { "type": "boolean", "description": "with tables, also include tables pointing into the slice" },
"scope": { "type": "integer", "minimum": 1, "description": "scope per top-level signature (default 3)" },
"budget": { "type": "integer", "minimum": 1, "description": "at most this many solver conflicts per candidate" },
"timeout": { "type": "string", "description": "wall-clock time limit for discovery (e.g. `30s`, `2m`)" },
"show_rejected": { "type": "boolean", "description": "include rejected candidates and counterexamples in the text story" }
},
"required": ["sql"]
}
},
{
"name": "audit",
"description": "Audit a SQL dump of INSERT rows against a SQL schema and optional Alloy promises directly without invoking the SAT solver.",
"inputSchema": {
"type": "object",
"properties": {
"sql": { "type": "string", "description": "SQL DDL schema text" },
"data": { "type": "string", "description": "SQL dump text containing INSERT statements" },
"promises": { "type": "string", "description": "optional sidecar Alloy promises text" },
"tables": { "type": "array", "items": { "type": "string" }, "description": "audit only these tables (plus their FK targets)" },
"with_referencing": { "type": "boolean", "description": "with tables, also include tables pointing into the slice" }
},
"required": ["sql", "data"]
}
},
{
"name": "explain",
"description": "Explain an error code, print a verb's JSON Schema (schema:result, schema:results, schema:diff, schema:import, schema:render, schema:eval, schema:tests, schema:accepts, schema:fuzz, schema:discover, schema:ci, schema:audit, schema:usage, or `schema` to list them), print the embedded agent guide (skill), or list every code.",
"inputSchema": {
"type": "object",
"properties": { "code": { "type": "string" } }
}
}
])
}
fn opt_u64(args: &Value, key: &str) -> Result<Option<u64>, String> {
match args.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v
.as_u64()
.map(Some)
.ok_or_else(|| format!("`{key}` must be a non-negative integer")),
}
}
fn opt_usize(args: &Value, key: &str) -> Result<Option<usize>, String> {
match opt_u64(args, key)? {
None => Ok(None),
Some(n) => usize::try_from(n)
.map(Some)
.map_err(|_| format!("`{key}` is out of range")),
}
}
fn opt_bool(args: &Value, key: &str) -> Result<bool, String> {
match args.get(key) {
None | Some(Value::Null) => Ok(false),
Some(v) => v
.as_bool()
.ok_or_else(|| format!("`{key}` must be a boolean")),
}
}
fn opt_str<'a>(args: &'a Value, key: &str) -> Result<Option<&'a str>, String> {
match args.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) => v
.as_str()
.map(Some)
.ok_or_else(|| format!("`{key}` must be a string")),
}
}
fn opt_str_list(args: &Value, key: &str) -> Result<Vec<String>, String> {
match args.get(key) {
None | Some(Value::Null) => Ok(Vec::new()),
Some(Value::Array(arr)) => arr
.iter()
.map(|v| {
v.as_str()
.map(str::to_string)
.ok_or_else(|| format!("`{key}` must be an array of strings"))
})
.collect(),
Some(_) => Err(format!("`{key}` must be an array of strings")),
}
}
fn call(name: &str, args: &Value) -> Result<Output, String> {
let model = || {
args["model"]
.as_str()
.ok_or_else(|| "`model` must be the model's text".to_string())
};
let timeout_ms = match opt_str(args, "timeout")? {
Some(raw) => Some(verbs::parse_duration_ms(raw)?),
None => None,
};
let over = Overrides {
scope: opt_usize(args, "scope")?,
steps: opt_usize(args, "steps")?,
budget: opt_u64(args, "budget")?,
timeout_ms,
explain: opt_bool(args, "explain")?,
brief: opt_bool(args, "brief")?,
inductive: opt_usize(args, "induction")?,
climb: opt_bool(args, "climb")?,
summary: opt_bool(args, "summary")?,
shrink: opt_bool(args, "shrink")?,
ignore_unread: opt_bool(args, "ignore_unread")?,
from_any: opt_bool(args, "from_any")?,
from_empty: opt_bool(args, "from_empty")?,
no_slicing: opt_bool(args, "no_slicing")?,
symmetry: opt_usize(args, "symmetry")?,
no_overflow: opt_bool(args, "no_overflow")?,
default_bitwidth: None,
};
let is_sql = opt_bool(args, "is_sql")?;
let promises = opt_str(args, "promises")?;
let views = opt_str(args, "views")?;
if views.is_some() && !is_sql {
return Err("`views` is SQL, and needs `is_sql`".to_string());
}
let fname = if is_sql { "schema.sql" } else { "model.als" };
let text = || -> Result<String, String> {
let m = model()?;
Ok(match (is_sql, views, promises) {
(true, Some(v), _) => format!("{m}\n{v}\n"),
(true, None, _) => m.to_string(),
(false, _, Some(p)) => format!("{m}\n{p}\n"),
(false, _, None) => m.to_string(),
})
};
let tables = opt_str_list(args, "tables")?;
let with_referencing = opt_bool(args, "with_referencing")?;
let sql_promises = if is_sql { promises } else { None };
match name {
"check" | "run" => {
let verb = if name == "check" { "check" } else { "run" };
let mut over = over;
let text = if is_sql {
match verbs::compose_sql_model_with_bitwidth(
verb,
fname,
&text()?,
promises,
&tables,
with_referencing,
!over.from_any,
) {
Ok((m, bw)) => {
over.default_bitwidth = Some(bw);
m
}
Err(out) => return Ok(out),
}
} else {
text()?
};
if verb == "run" && opt_bool(args, "all")? {
Ok(verbs::run_all(
fname,
&text,
opt_str(args, "command")?,
over,
opt_bool(args, "sql")?,
opt_usize(args, "limit")?.unwrap_or(1000),
false,
))
} else {
Ok(verbs::solve_inline(
verb,
fname,
&text,
opt_str(args, "command")?,
over,
))
}
}
"tests" => {
let allow_dead = opt_str_list(args, "allow_dead")?;
let opts = verbs::TestsOptions {
as_sql: opt_bool(args, "sql")?,
tables,
with_referencing,
sample_values: std::collections::BTreeMap::new(),
allow_dead,
extra_als: None,
};
Ok(verbs::tests_with_options(
fname,
model()?,
over,
&opts,
false,
None,
))
}
"accepts" => {
let trace = args["trace"]
.as_str()
.ok_or("`trace` must be a JSON string or SQL DML script")?;
Ok(verbs::accepts_with_options(
fname,
&text()?,
trace,
false,
sql_promises,
&tables,
with_referencing,
))
}
"discover" => {
let sql = args["sql"]
.as_str()
.ok_or("`sql` must be the SQL DDL text")?;
let opts = crate::cli::discover::DiscoverOptions {
tables,
with_referencing,
extra_als: None,
scope: over.scope.unwrap_or(3),
budget: over.budget,
timeout_ms: over.timeout_ms,
show_rejected: opt_bool(args, "show_rejected")?,
};
Ok(crate::cli::discover::discover(
"schema.sql",
sql,
&opts,
None,
))
}
"audit" => {
let sql = args["sql"]
.as_str()
.ok_or("`sql` must be the SQL DDL text")?;
let data = args["data"]
.as_str()
.ok_or("`data` must be SQL dump text containing INSERT statements")?;
let opts = crate::cli::audit::AuditOptions {
tables,
with_referencing,
extra_als: promises.map(str::to_string),
};
Ok(crate::cli::audit::audit(
"schema.sql",
sql,
"dump.sql",
data,
&opts,
))
}
"diff" => {
let old = args["old_model"]
.as_str()
.ok_or("`old_model` must be the old model's text")?;
let new = args["new_model"]
.as_str()
.ok_or("`new_model` must be the new model's text")?;
if let Some(fun_name) = opt_str(args, "of")? {
return Ok(verbs::diff_of_inline(
"old.als", old, "new.als", new, fun_name, over,
));
}
let (old_name, new_name) = if opt_bool(args, "sql")? {
("old.sql", "new.sql")
} else {
("old.als", "new.als")
};
Ok(verbs::diff_with_options(
old_name,
old,
false,
new_name,
new,
false,
&tables,
with_referencing,
over,
))
}
"import_sql" => {
let sql = args["sql"].as_str().ok_or("`sql` must be SQL DDL text")?;
let strict = opt_bool(args, "strict")?;
let temporal = opt_bool(args, "temporal")?;
let from_empty = opt_bool(args, "from_empty")?;
let only_ruled = opt_bool(args, "only_ruled")?;
let opts = elinvar_als::SqlImportOptions::new()
.temporal(temporal)
.from_empty(from_empty)
.tables(tables)
.with_referencing(with_referencing)
.only_ruled(only_ruled);
Ok(verbs::import_sql_with("schema.sql", sql, &opts, strict).0)
}
"render" => {
let format = match opt_str(args, "format")? {
None => elinvar_engine::DiagramFormat::Dot,
Some(name) => {
verbs::diagram_format(name).ok_or_else(|| format!("unknown format `{name}`"))?
}
};
if let Some(model_text) = opt_str(args, "model")? {
return Ok(verbs::render_model_text(
"model.als",
model_text,
format,
false,
));
}
let state = opt_usize(args, "state")?;
Ok(verbs::render(&args["result"], format, state))
}
"eval" => {
let expr = args["expression"]
.as_str()
.ok_or("`expression` must be text")?;
let state = opt_usize(args, "state")?.unwrap_or(0);
Ok(verbs::eval_with_options(
fname,
&text()?,
&args["result"],
expr,
state,
sql_promises,
&tables,
with_referencing,
false,
))
}
"explain" => Ok(verbs::explain(opt_str(args, "code")?)),
other => Err(format!("no tool `{other}`")),
}
}
fn respond(id: &Value, result: Result<Value, (i64, String)>) -> Value {
match result {
Ok(r) => json!({ "jsonrpc": "2.0", "id": id, "result": r }),
Err((code, message)) => {
json!({ "jsonrpc": "2.0", "id": id, "error": { "code": code, "message": message } })
}
}
}
fn unknown_arguments(tool: &Value, args: &Value) -> Result<(), String> {
let Some(args) = args.as_object() else {
return Err("`arguments` must be an object".to_string());
};
let props = &tool["inputSchema"]["properties"];
let unknown: Vec<&str> = args
.keys()
.filter(|k| props.get(k.as_str()).is_none())
.map(String::as_str)
.collect();
if unknown.is_empty() {
return Ok(());
}
let mut known: Vec<&str> = props
.as_object()
.map(|o| o.keys().map(String::as_str).collect())
.unwrap_or_default();
known.sort_unstable();
Err(format!(
"unknown argument(s) {} for `{}`; it takes: {}",
unknown
.iter()
.map(|k| format!("`{k}`"))
.collect::<Vec<_>>()
.join(", "),
tool["name"].as_str().unwrap_or(""),
known.join(", ")
))
}
pub fn handle(msg: &Value) -> Option<Value> {
let Some(obj) = msg.as_object() else {
let why = if msg.is_array() {
"a batch (a JSON array) is not part of MCP 2025-06-18; send one request per line"
} else {
"a request must be a JSON object"
};
return Some(respond(&Value::Null, Err((-32600, why.to_string()))));
};
let id = obj.get("id")?.clone();
let Some(method) = obj.get("method").and_then(Value::as_str) else {
return Some(respond(
&id,
Err((-32600, "a request needs a string `method`".to_string())),
));
};
if obj.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
return Some(respond(
&id,
Err((-32600, "a request needs `\"jsonrpc\": \"2.0\"`".to_string())),
));
}
let params = match obj.get("params") {
None | Some(Value::Null) => json!({}),
Some(p @ Value::Object(_)) => p.clone(),
Some(_) => {
return Some(respond(
&id,
Err((-32602, "`params` must be an object".to_string())),
));
}
};
let result = match method {
"initialize" => Ok(json!({
"protocolVersion": PROTOCOL,
"capabilities": { "tools": {}, "resources": {} },
"serverInfo": { "name": "elinvar", "version": env!("CARGO_PKG_VERSION") },
"instructions": INSTRUCTIONS
})),
"ping" => Ok(json!({})),
"resources/list" => Ok(json!({ "resources": resources() })),
"resources/read" => match params["uri"].as_str() {
Some(uri) => read_resource(uri),
None => Err((-32602, "`uri` must be a string".to_string())),
},
"tools/list" => Ok(json!({ "tools": tools() })),
"tools/call" => {
let name = params["name"].as_str().unwrap_or("");
let tools = tools();
let tool = tools
.as_array()
.and_then(|t| t.iter().find(|t| t["name"] == name));
let args = match ¶ms["arguments"] {
Value::Null => json!({}),
a => a.clone(),
};
let called = match tool {
None => return Some(respond(&id, Err((-32602, format!("no tool `{name}`"))))),
Some(tool) => unknown_arguments(tool, &args).and_then(|()| call(name, &args)),
};
match called {
Ok(out) => Ok(json!({
"content": [{ "type": "text", "text": out.json.to_string() }],
"structuredContent": if out.json.is_object() { out.json.clone() } else { json!({ "results": out.json }) },
"isError": out.status == 3
})),
Err(m) => Ok(json!({
"content": [{ "type": "text", "text": m }],
"isError": true
})),
}
}
other => Err((-32601, format!("no method `{other}`"))),
};
Some(respond(&id, result))
}
pub fn serve() {
let stdin = std::io::stdin();
let mut stdout = std::io::stdout();
for line in stdin.lock().lines() {
let Ok(line) = line else { break };
if line.trim().is_empty() {
continue;
}
let reply = match serde_json::from_str::<Value>(&line) {
Ok(msg) => handle(&msg),
Err(e) => Some(respond(
&Value::Null,
Err((-32700, format!("not JSON: {e}"))),
)),
};
if let Some(r) = reply {
let _ = writeln!(stdout, "{r}");
let _ = stdout.flush();
}
}
}