Skip to main content

cmd_usage/ocuse/
mcp.rs

1// MCP stdio server for ocuse — the same JSON-RPC profile cmduse speaks
2// (initialize / ping / tools/list / tools/call), so a host that already drives
3// cmduse can drive this. Tools mirror the CLI: usage, plans, models, daily,
4// hourly, session, model — the same seven cmduse exposes.
5//
6// Read-only: it reads opencode.db and the generated catalogue. The Go usage
7// endpoint's meters are not fetched here — the caller resolves them once (the
8// CLI's own rule: one fetch per run, not one per tool call) and hands them in,
9// so a `usage` call shows the same window rows the dashboard does.
10use crate::ocuse::api::Usage;
11use crate::ocuse::{db, render, window, zen};
12use serde_json::{json, Value};
13
14const PROTOCOL_VERSION: &str = "2025-06-18";
15
16/// What every tool call needs, resolved once by the caller — the per-run
17/// settings plus the account meters it already fetched. Bundled rather than
18/// passed positionally so adding a source (as `account` did) does not grow every
19/// signature in the file.
20#[derive(Clone, Copy)]
21pub struct Settings<'a> {
22    pub db_path: &'a str,
23    pub days: i64,
24    pub tz_secs: i64,
25    pub colour: bool,
26    pub plan: &'a str,
27    pub period_start: Option<i64>,
28    pub account: Option<&'a Usage>,
29    /// Why the account's meters are missing, when the CLI resolved it — the same
30    /// line the dashboard prints, so a `usage` call through MCP explains itself
31    /// too instead of showing bare local estimates.
32    pub account_error: Option<&'a str>,
33}
34
35/// Serve stdin -> stdout until the host closes the pipe.
36pub fn run(settings: Settings) {
37    use std::io::{BufRead, Write};
38    let stdin = std::io::stdin();
39    let mut out = std::io::stdout().lock();
40    for line in stdin.lock().lines() {
41        let Ok(line) = line else { break };
42        if line.trim().is_empty() {
43            continue;
44        }
45        let Ok(msg) = serde_json::from_str::<Value>(&line) else {
46            continue; // not JSON: ignore, a host bug shouldn't kill the server
47        };
48        if let Some(response) = handle(&msg, &settings) {
49            if writeln!(out, "{response}").is_err() {
50                break; // stdout closed: host is gone
51            }
52            out.flush().ok();
53        }
54    }
55}
56
57/// One message in, one response out; `None` for notifications (no `id`).
58pub fn handle(msg: &Value, settings: &Settings) -> Option<Value> {
59    let method = msg.get("method")?.as_str()?;
60    let id = msg.get("id")?;
61    let result = match method {
62        "initialize" => Ok(json!({
63            "protocolVersion": msg
64                .pointer("/params/protocolVersion")
65                .and_then(|v| v.as_str())
66                .unwrap_or(PROTOCOL_VERSION),
67            "capabilities": { "tools": {} },
68            "serverInfo": { "name": "ocuse", "version": env!("CARGO_PKG_VERSION") },
69        })),
70        "ping" => Ok(json!({})),
71        "tools/list" => Ok(json!({ "tools": tools() })),
72        "tools/call" => tool_call(msg, settings),
73        other => Err((-32601, format!("method not found: {other}"))),
74    };
75    Some(match result {
76        Ok(value) => json!({ "jsonrpc": "2.0", "id": id, "result": value }),
77        Err((code, message)) => json!({
78            "jsonrpc": "2.0", "id": id,
79            "error": { "code": code, "message": message },
80        }),
81    })
82}
83
84fn tool_call(msg: &Value, settings: &Settings) -> Result<Value, (i64, String)> {
85    let Settings {
86        db_path,
87        days,
88        tz_secs,
89        colour,
90        plan,
91        period_start,
92        account,
93        account_error,
94    } = *settings;
95    let name = msg
96        .pointer("/params/name")
97        .and_then(|v| v.as_str())
98        .unwrap_or_default();
99    let args = msg
100        .pointer("/params/arguments")
101        .cloned()
102        .unwrap_or(json!({}));
103    let number =
104        |key: &str, fallback: i64| args.get(key).and_then(|v| v.as_i64()).unwrap_or(fallback);
105    // The plan may be overridden per call; it defaults to the server's flag.
106    let plan_id = args
107        .get("plan")
108        .and_then(|v| v.as_str())
109        .unwrap_or(plan)
110        .to_string();
111
112    let rows = || db::read_rows(db_path, crate::ocuse::window::now_ms() - days * 86_400_000);
113    let text = match name {
114        "usage" => rows().map(|rows| {
115            let mut report =
116                window::build(&rows, &zen::catalog(), &plan_id, window::now_ms(), None);
117            // The account's own meters when the caller resolved them, so a `usage`
118            // call renders the same window rows the dashboard does — and the same
119            // reason when a key was refused.
120            report.account = account.cloned();
121            report.account_error = account_error.map(str::to_string);
122            render::render_text(&report, db_path, 15, colour, render::DEFAULT_BAR_WIDTH)
123        }),
124        "plans" => Ok(render::plans_text(colour)),
125        "models" => {
126            // The catalogue is static, but a per-call plan override must be real.
127            let catalog = zen::catalog();
128            if catalog.plan(&plan_id).is_none() {
129                return Err((
130                    -32602,
131                    format!("plan must be one of: {}", catalog.plan_ids().join(", ")),
132                ));
133            }
134            let gated = args.get("gated").and_then(|v| v.as_bool()).unwrap_or(false);
135            Ok(render::models_text(&plan_id, gated, colour))
136        }
137        "daily" => rows().map(|rows| {
138            render::bucket_text(
139                &rows,
140                window::now_ms(),
141                number("days", days) * 86_400_000,
142                86_400_000,
143                tz_secs,
144                colour,
145                crate::report_render::Fmt::Table,
146            )
147        }),
148        "hourly" => rows().map(|rows| {
149            render::bucket_text(
150                &rows,
151                window::now_ms(),
152                number("hours", 24) * 3_600_000,
153                3_600_000,
154                tz_secs,
155                colour,
156                crate::report_render::Fmt::Table,
157            )
158        }),
159        "session" => rows().map(|rows| {
160            render::session_text(
161                &rows,
162                number("limit", 20) as usize,
163                colour,
164                crate::report_render::Fmt::Table,
165            )
166        }),
167        "model" => {
168            let wanted = args
169                .get("id")
170                .and_then(|v| v.as_str())
171                .unwrap_or_default()
172                .to_string();
173            rows().map(|rows| {
174                let report = window::build(
175                    &rows,
176                    &zen::catalog(),
177                    &plan_id,
178                    window::now_ms(),
179                    period_start,
180                );
181                render::model_text(&report, &wanted, colour)
182            })
183        }
184        _ => {
185            return Ok(json!({
186                "content": [{ "type": "text", "text": format!("unknown tool: {name}") }],
187                "isError": true,
188            }))
189        }
190    };
191    Ok(match text {
192        Ok(body) => json!({ "content": [{ "type": "text", "text": body }] }),
193        Err(error) => json!({
194            "content": [{ "type": "text", "text": format!("error: {error}") }],
195            "isError": true,
196        }),
197    })
198}
199
200fn tools() -> Value {
201    json!([
202        { "name": "usage", "description": "OpenCode Go/Zen usage: period totals, rolling windows, per-model spend against each model's monthly limit. Defaults to the Go plan.", "inputSchema": { "type": "object", "properties": { "plan": { "type": "string", "description": "Go plan: go (default) or go-plus" } } } },
203        { "name": "plans", "description": "The Go/Zen catalogue from the docs: both Go plans' per-model monthly limits and the shared $/1M rates.", "inputSchema": { "type": "object", "properties": {} } },
204        { "name": "models", "description": "The Go catalogue for a plan: every model's $/1M in/out/cache-read rates and its monthly limit, marked granted or not.", "inputSchema": { "type": "object", "properties": { "plan": { "type": "string", "description": "Go plan: go (default) or go-plus" }, "gated": { "type": "boolean", "description": "Only models the plan grants" } } } },
205        { "name": "daily", "description": "Spend, requests and tokens per day.", "inputSchema": { "type": "object", "properties": { "days": { "type": "integer", "description": "days of history (default 120)" } } } },
206        { "name": "hourly", "description": "Spend, requests and tokens per hour.", "inputSchema": { "type": "object", "properties": { "hours": { "type": "integer", "description": "hours of history (default 24)" } } } },
207        { "name": "session", "description": "Spend per OpenCode session, newest first.", "inputSchema": { "type": "object", "properties": { "limit": { "type": "integer", "description": "sessions to list (default 20)" } } } },
208        { "name": "model", "description": "One model's limit, spend and window figures, against the given Go plan.", "inputSchema": { "type": "object", "properties": { "id": { "type": "string", "description": "model id, e.g. glm-5.2" }, "plan": { "type": "string", "description": "Go plan: go (default) or go-plus" } }, "required": ["id"] } },
209    ])
210}
211
212#[cfg(test)]
213mod tests {
214    use super::*;
215
216    fn call(method: &str, params: Value, id: i64) -> Value {
217        handle(
218            &json!({ "jsonrpc": "2.0", "id": id, "method": method, "params": params }),
219            &Settings {
220                db_path: "/nonexistent/opencode.db",
221                days: 120,
222                tz_secs: 0,
223                colour: false,
224                plan: crate::ocuse::zen::DEFAULT_PLAN,
225                period_start: None,
226                // No account: the tests never reach the network, and the local
227                // estimate is what the fixtures below are written against.
228                account: None,
229                account_error: None,
230            },
231        )
232        .expect("notification")
233    }
234
235    #[test]
236    fn initialize_negotiates_the_client_version() {
237        let r = call("initialize", json!({ "protocolVersion": "2025-03-26" }), 1);
238        assert_eq!(r["result"]["protocolVersion"], "2025-03-26");
239        assert_eq!(r["result"]["serverInfo"]["name"], "ocuse");
240    }
241
242    #[test]
243    fn unknown_method_is_jsonrpc_error() {
244        let r = call("resources/list", json!({}), 2);
245        assert_eq!(r["error"]["code"], -32601);
246    }
247
248    #[test]
249    fn unknown_tool_is_iserror_result_not_rpc_error() {
250        let r = call("tools/call", json!({ "name": "nope", "arguments": {} }), 3);
251        assert!(r.get("error").is_none());
252        assert_eq!(r["result"]["isError"], true);
253    }
254
255    #[test]
256    fn a_missing_store_reports_an_error_result() {
257        let r = call("tools/call", json!({ "name": "usage", "arguments": {} }), 4);
258        assert_eq!(r["result"]["isError"], true, "{r}");
259        assert!(r["result"]["content"][0]["text"]
260            .as_str()
261            .unwrap()
262            .contains("error"));
263    }
264
265    #[test]
266    fn tools_list_covers_every_command() {
267        let r = call("tools/list", json!({}), 5);
268        // Sorted set: fails if either MCP server's tool list drifts (the cmduse
269        // side asserts the same seven).
270        let mut names: Vec<&str> = r["result"]["tools"]
271            .as_array()
272            .unwrap()
273            .iter()
274            .map(|t| t["name"].as_str().unwrap())
275            .collect();
276        names.sort_unstable();
277        assert_eq!(
278            names,
279            ["daily", "hourly", "model", "models", "plans", "session", "usage"]
280        );
281    }
282
283    #[test]
284    fn models_tool_is_the_catalogue_and_needs_no_store() {
285        let r = call(
286            "tools/call",
287            json!({ "name": "models", "arguments": {} }),
288            6,
289        );
290        assert!(r.get("error").is_none(), "{r}");
291        let text = r["result"]["content"][0]["text"].as_str().unwrap();
292        assert!(text.contains("glm-5.3-flash"), "{text}");
293        assert!(text.contains("GRANTED"), "{text}");
294    }
295
296    #[test]
297    fn models_tool_rejects_an_unknown_plan() {
298        let r = call(
299            "tools/call",
300            json!({ "name": "models", "arguments": { "plan": "nope" } }),
301            7,
302        );
303        assert_eq!(r["error"]["code"], -32602, "{r}");
304    }
305}