Skip to main content

smeltery_bellows/
lib.rs

1//! Bellows, the AI-agent support of the [Smeltery](https://github.com/smelteryworks/smeltery) framework.
2//!
3//! The app command `bellows:mcp` runs a [Model Context Protocol](https://modelcontextprotocol.io) server on
4//! stdin / stdout (JSON-RPC 2.0, one message per line) inside the app binary, so a coding agent can ask the app
5//! itself about its routes, models, database schema, configuration keys, recent errors and documentation, and can
6//! run generators, tests and agent controls. Apps register it with [`BellowsExt::bellows`]; a generated app does
7//! so in `bootstrap/app.rs`, and `.mcp.json` points the agent at `smeltery bellows:mcp`.
8//!
9//! ```
10//! use smeltery_bellows::BellowsExt as _;
11//! use smeltery_core::AppBuilder;
12//!
13//! fn build(app: AppBuilder) -> AppBuilder {
14//!     app.bellows()
15//! }
16//! # let _ = build(AppBuilder::new(smeltery_core::config::Settings::from_env()));
17//! ```
18//!
19//! | Tool | Answers |
20//! |---|---|
21//! | `route_list` | every route: methods, path, name, middleware |
22//! | `models` | the models in `app/models/` with their table's columns |
23//! | `db_schema` | every table: columns (type, nullable, default, primary key) and indexes |
24//! | `config_keys` | the names of the settings in `.env`, `.env.example` and the framework (never values) |
25//! | `last_errors` | the latest `ERROR` (and, when asked, `WARN`) lines of the app's log file (`LOG_FILE`, else `storage/logs/*.log`) |
26//! | `docs_search` | sections of the Smeltery guide, `CLAUDE.md` and `.bellows/` matching the words |
27//! | `run_generator` | runs one `smeltery make:*` command (names, fields and the generators' options as arguments) |
28//! | `run_tests` | runs `cargo test` (optionally filtered by a test path) and returns the summary and failures; it compiles and runs the app's code |
29//! | `agents_list` | the Watchfire agents of the running app |
30//! | `agent_control` | start / stop / pause / resume / restart an agent of the running app |
31#![cfg_attr(docsrs, feature(doc_cfg))]
32
33// The README's samples run as doctests without becoming the crate docs.
34#[cfg(doctest)]
35#[doc = include_str!("../README.md")]
36struct ReadmeDoctests;
37
38mod rpc;
39mod tools;
40
41use std::path::PathBuf;
42use std::time::Duration;
43
44use smeltery_core::console::{Args, Command};
45use smeltery_core::{App, AppBuilder, Result};
46
47pub use rpc::{McpServer, PROTOCOL_VERSIONS};
48
49/// `AppBuilder::bellows`: add the `bellows:mcp` command.
50pub trait BellowsExt {
51    /// Register the `bellows:mcp` app command (the MCP server on stdin / stdout).
52    fn bellows(self) -> Self;
53}
54
55impl BellowsExt for AppBuilder {
56    fn bellows(self) -> Self {
57        self.commands(|c| {
58            c.add(McpCommand);
59        })
60    }
61}
62
63/// The `bellows:mcp` command.
64#[derive(Clone, Copy, Debug, Default)]
65pub struct McpCommand;
66
67impl Command for McpCommand {
68    fn name(&self) -> &'static str {
69        "bellows:mcp"
70    }
71
72    fn about(&self) -> &'static str {
73        "Run the Bellows MCP server on stdin / stdout (for coding agents)"
74    }
75
76    async fn run(&self, app: &App, _args: Args) -> Result<()> {
77        let server = McpServer::new(app.clone(), Options::from_app(app));
78        let stdin = tokio::io::BufReader::new(tokio::io::stdin());
79        server.serve(stdin, tokio::io::stdout()).await
80    }
81}
82
83/// Where the tools look and how long their subprocesses and HTTP calls may take.
84#[derive(Clone, Debug)]
85#[non_exhaustive]
86pub struct Options {
87    /// The app root (`.env`, `app/models/`, `storage/logs/`, `CLAUDE.md`, …).
88    pub root: PathBuf,
89    /// The app's log file (`LOG_FILE`) that `last_errors` reads; without one it reads `storage/logs/*.log`.
90    pub log_file: Option<PathBuf>,
91    /// The `smeltery` binary `run_generator` calls (`SMELTERY_BIN`, else `smeltery` on `PATH`).
92    pub smeltery_bin: PathBuf,
93    /// The `cargo` binary `run_tests` calls (`CARGO`, else `cargo` on `PATH`).
94    pub cargo_bin: PathBuf,
95    /// How long one generator may run (60 s).
96    pub generator_timeout: Duration,
97    /// How long `cargo test` may run (`BELLOWS_TEST_TIMEOUT` seconds, 600).
98    pub test_timeout: Duration,
99    /// How long one call to the running app's Watchfire API may take (10 s).
100    pub http_timeout: Duration,
101}
102
103impl Options {
104    /// The options for `app`: its root and the binaries and timeouts from the environment.
105    pub fn from_app(app: &App) -> Self {
106        let var = |name: &str| {
107            std::env::var_os(name)
108                .filter(|v| !v.is_empty())
109                .map(PathBuf::from)
110        };
111        let test_secs = smeltery_core::config::env::<u64>("BELLOWS_TEST_TIMEOUT", 600).max(1);
112        Self {
113            root: app.settings().root.clone(),
114            log_file: app.settings().log_file.clone(),
115            smeltery_bin: var("SMELTERY_BIN").unwrap_or_else(|| PathBuf::from("smeltery")),
116            cargo_bin: var("CARGO").unwrap_or_else(|| PathBuf::from("cargo")),
117            generator_timeout: Duration::from_secs(60),
118            test_timeout: Duration::from_secs(test_secs),
119            http_timeout: Duration::from_secs(10),
120        }
121    }
122
123    /// Use another app root.
124    pub fn root(mut self, root: impl Into<PathBuf>) -> Self {
125        self.root = root.into();
126        self
127    }
128
129    /// Read this log file in `last_errors` (`None`: scan `storage/logs/*.log`).
130    pub fn log_file(mut self, file: Option<PathBuf>) -> Self {
131        self.log_file = file;
132        self
133    }
134
135    /// Use another `smeltery` binary.
136    pub fn smeltery_bin(mut self, bin: impl Into<PathBuf>) -> Self {
137        self.smeltery_bin = bin.into();
138        self
139    }
140
141    /// Use another `cargo` binary.
142    pub fn cargo_bin(mut self, bin: impl Into<PathBuf>) -> Self {
143        self.cargo_bin = bin.into();
144        self
145    }
146
147    /// Change the `cargo test` timeout.
148    pub fn test_timeout(mut self, timeout: Duration) -> Self {
149        self.test_timeout = timeout;
150        self
151    }
152
153    /// Change the generator timeout.
154    pub fn generator_timeout(mut self, timeout: Duration) -> Self {
155        self.generator_timeout = timeout;
156        self
157    }
158}