ahk-cli 0.5.0

Run an ahk script on this machine: the script on stdin, the report on stdout
Documentation
// SPDX-License-Identifier: Apache-2.0
//! A Model Context Protocol server for debugging AHK development, over
//! JSON-RPC 2.0 on stdio (one JSON object per line), the same framing as the
//! rgx MCP. It exposes the tree's own answers so a client can read the errors
//! of a script without a shell:
//!
//! * `check`  — parse a script and report the load error (line/column/message).
//! * `run`    — run a script and report the whole report (output/steps/error).
//! * `surface`— the summary of the names of a dialect.
//!
//! The request is read with the djson on-demand parser (rgx-core); the answer
//! is written with the tree's own JSON writer, so a client reads the same
//! report the runner writes.

use std::io::{BufRead, Write};

use ahk::dialect::{self, Dialect};
use ahk::json::Object;
use ahk::parse_with;
use ahk::runtime::Runtime;
use ahk::surface;
use ahk_cli::report;
use rgx_core::djson::ondemand::Ondemand;

const PROTOCOL_VERSION: &str = "2025-03-26";

/// Serve the MCP on stdio until the input ends.
pub fn serve() {
    let stdin = std::io::stdin();
    let stdout = std::io::stdout();
    let mut out = stdout.lock();
    for line in stdin.lock().lines() {
        let Ok(line) = line else { break };
        if line.trim().is_empty() {
            continue;
        }
        if let Some(answer) = handle_line(&line) {
            let _ = writeln!(out, "{answer}");
            let _ = out.flush();
        }
    }
}

/// One request, one answer (notifications get no answer).
pub fn handle_line(line: &str) -> Option<String> {
    let mut od = Ondemand::new(line).ok()?;
    let root = od.root().ok()?;
    let mut method = String::new();
    let mut id = String::from("null");
    let mut has_id = false;
    let mut name = String::new();
    let mut source = String::new();
    let mut dialect = String::from("v2");
    let _ = root.object_entries(|key, v| {
        match key.as_ref() {
            "method" => {
                if let Ok(Some(s)) = v.as_str() {
                    method = s.into_owned();
                }
            }
            "id" => {
                if let Ok(raw) = v.raw() {
                    id = raw.to_string();
                    has_id = true;
                }
            }
            "params" => {
                let _ = v.object_entries(|k2, v2| {
                    match k2.as_ref() {
                        "name" => {
                            if let Ok(Some(s)) = v2.as_str() {
                                name = s.into_owned();
                            }
                        }
                        "arguments" => {
                            let _ = v2.object_entries(|k3, v3| {
                                match k3.as_ref() {
                                    "source" => {
                                        if let Ok(Some(s)) = v3.as_str() {
                                            source = s.into_owned();
                                        }
                                    }
                                    "dialect" => {
                                        if let Ok(Some(s)) = v3.as_str() {
                                            dialect = s.into_owned();
                                        }
                                    }
                                    _ => {}
                                }
                                Ok(true)
                            });
                        }
                        _ => {}
                    }
                    Ok(true)
                });
            }
            _ => {}
        }
        Ok(true)
    });
    if !has_id {
        return None; // a notification
    }
    let body = match method.as_str() {
        "initialize" => initialize_result(),
        "ping" => Object::new(4).finish(),
        "tools/list" => tools_json(),
        "tools/call" => tool_call(&name, &source, &dialect),
        _ => return Some(error(&id, -32601, "method not found")),
    };
    Some(result(&id, &body))
}

fn result(id: &str, body: &str) -> String {
    format!("{{\"jsonrpc\":\"2.0\",\"id\":{id},\"result\":{body}}}")
}

fn error(id: &str, code: i32, message: &str) -> String {
    let mut e = Object::new(4);
    e.number("code", code as i64);
    e.text("message", message);
    format!("{{\"jsonrpc\":\"2.0\",\"id\":{id},\"error\":{}}}", e.finish())
}

fn initialize_result() -> String {
    let mut o = Object::new(8);
    o.text("protocolVersion", PROTOCOL_VERSION);
    o.field("capabilities", |s| s.push_str("{\"tools\":{}}"));
    o.field("serverInfo", |s| {
        let mut i = Object::new(4);
        i.text("name", "ahk");
        i.text("version", env!("CARGO_PKG_VERSION"));
        s.push_str(&i.finish());
    });
    o.finish()
}

fn tool_schema(name: &str, desc: &str) -> String {
    let mut t = Object::new(8);
    t.text("name", name);
    t.text("description", desc);
    t.field("inputSchema", |s| {
        let mut sc = Object::new(8);
        sc.text("type", "object");
        sc.field("properties", |p| {
            let mut props = Object::new(8);
            props.field("source", |x| {
                let mut d = Object::new(4);
                d.text("type", "string");
                d.text("description", "the AHK source");
                x.push_str(&d.finish());
            });
            props.field("dialect", |x| {
                let mut d = Object::new(4);
                d.text("type", "string");
                d.text("description", "v1 | v2 | v2.1 | ks | ks20 (default v2)");
                x.push_str(&d.finish());
            });
            p.push_str(&props.finish());
        });
        sc.texts("required", &["source".to_string()]);
        s.push_str(&sc.finish());
    });
    t.finish()
}

fn tools_json() -> String {
    let mut o = Object::new(4);
    o.field("tools", |s| {
        s.push('[');
        s.push_str(&tool_schema("check", "Parse an AHK script and report the load error (line, column, message), or ok."));
        s.push(',');
        s.push_str(&tool_schema("run", "Run an AHK script and report the whole report: output, steps, error."));
        s.push(',');
        s.push_str(&tool_schema("surface", "The summary of the names of a dialect (dialect argument only)."));
        s.push(']');
    });
    o.finish()
}

fn the_dialect(name: &str) -> &'static dyn Dialect {
    match name.to_lowercase().as_str() {
        "v1" => dialect::v1(),
        "v2.1" | "v2_1" => dialect::v2_1(),
        "ks" => dialect::ks(),
        "ks20" | "ks2.0" => dialect::ks_20(),
        _ => dialect::v2(),
    }
}

fn tool_call(name: &str, source: &str, dialect_name: &str) -> String {
    let dialect = the_dialect(dialect_name);
    let content = match name {
        "check" => match parse_with(source, dialect) {
            Ok(_) => {
                let mut o = Object::new(4);
                o.boolean("ok", true);
                o.finish()
            }
            Err(e) => {
                let mut o = Object::new(8);
                o.boolean("ok", false);
                o.text("error", &e.message);
                o.number("line", e.line as i64);
                o.number("column", e.column as i64);
                o.finish()
            }
        },
        "run" => match parse_with(source, dialect) {
            Ok(statements) => {
                let mut desktop = the_desktop();
                let runtime = Runtime::new(&mut *desktop, std::time::Duration::from_secs(10))
                    .with_source(source)
                    .with_dialect(dialect);
                let rep = runtime.run(&statements);
                report::the_report(&rep, &[])
            }
            Err(e) => report::the_failure_of_the_load(&e.message, e.line, e.column),
        },
        "surface" => {
            let entries = surface::entries_of(dialect);
            let summary = surface::summary_of(&entries, dialect);
            let mut o = Object::new(4);
            o.number("total", entries.len() as i64);
            o.text("summary", &summary.text());
            o.finish()
        }
        _ => {
            let mut o = Object::new(4);
            o.boolean("isError", true);
            o.text("error", &format!("unknown tool {name}"));
            o.finish()
        }
    };
    let mut o = Object::new(4);
    o.field("content", |s| {
        s.push('[');
        let mut c = Object::new(4);
        c.text("type", "text");
        c.text("text", &content);
        s.push_str(&c.finish());
        s.push(']');
    });
    o.finish()
}

#[cfg(windows)]
fn the_desktop() -> Box<dyn ahk::desktop::Desktop> {
    Box::new(ahk_box::windows::WindowsDesktop::new())
}
#[cfg(not(windows))]
fn the_desktop() -> Box<dyn ahk::desktop::Desktop> {
    Box::new(ahk_box::LabDesktop::new())
}