Compare commits

..
1 Commits
Author SHA1 Message Date
hulthe 3873fad612 Add MCP server 2026-08-21 22:54:12 +02:00
9 changed files with 1317 additions and 634 deletions

No files matched your search

Generated
+1144 -532
View File
File diff suppressed because it is too large. Load diff
-9
View File
@@ -5,12 +5,3 @@ members = [
"srv",
"gui",
]
# Enable max optimizations for dependencies, but not for our code:
# Very helpful when developing in Slint.
[profile.dev.package."*"]
opt-level = 3
# Enable only a small amount of optimization in debug mode
[profile.dev]
opt-level = 1
+3 -2
View File
@@ -39,7 +39,7 @@ serde_json = "1.0.148"
anyhow = "1.0.100"
[dependencies.slint]
version = "1.18.0"
version = "1.17.1"
default-features = false
features = [
"live-preview",
@@ -49,6 +49,7 @@ features = [
"backend-android-activity-06",
]
[target.'cfg(target_os = "linux")'.dependencies]
tokio = { version = "1.48.0", default-features = false, features = ["fs", "rt-multi-thread"] }
xdg = "3.0.0"
@@ -62,4 +63,4 @@ wasm-bindgen-futures = "0.4.56"
web-sys = "0.3.83"
[build-dependencies]
slint-build = "1.18.0"
slint-build = "1.17.1"
-2
View File
@@ -93,7 +93,6 @@ fn update_slint_list(new_list: Vec<Item>, list: &VecModel<ui::SItem>) {
name: item.name.to_shared_string(),
checked: item.data.checked,
amount: item.data.amount as i32,
just_added: false,
})
.for_each(|item| list.push(item));
}
@@ -197,7 +196,6 @@ pub fn run() -> Result<(), anyhow::Error> {
checked: false,
name: item.clone(),
amount: 1,
just_added: true,
});
let conf = conf.clone();
io.spawn(async move || {
+57 -84
View File
@@ -9,13 +9,12 @@ import {
GridBox,
HorizontalBox,
ComboBox,
Palette,
Spinner,
SpinBox,
Palette, Spinner, SpinBox,
} from "std-widgets.slint";
import { SettingsView } from "settings.slint";
import { ConnectionStatus, State, SItem, SButtonItem } from "state.slint";
export { ConnectionStatus, State, SItem }
component GoodListItem inherits Rectangle {
in-out property <SItem> item;
background: Palette.alternate-background;
@@ -113,50 +112,31 @@ component PlusMinus inherits HorizontalLayout {
component GoodListItemAdd inherits Rectangle {
in-out property <SItem> item;
Rectangle {
// Animate when this item appears.
transform-scale: item.just-added ? 90% : 100%;
opacity: item.just-added ? 0 : 100%;
init => {
self.transform-scale = 100%;
self.opacity = 100%;
item.just-added = false;
}
animate transform-scale {
duration: 500ms;
easing: ease-out-bounce;
}
animate opacity {
duration: 300ms;
easing: ease-out;
background: Palette.alternate-background;
border-radius: 8pt;
border-width: 10pt;
HorizontalLayout {
spacing: 8px;
padding: 8px;
alignment: start;
PlusMinus {
item: item;
}
background: Palette.alternate-background;
border-radius: 8pt;
border-width: 10pt;
HorizontalLayout {
spacing: 8px;
padding: 8px;
alignment: start;
PlusMinus {
item: item;
Rectangle {
height: 30px;
Text {
text: root.item.amount;
font-size: 12pt;
}
}
Rectangle {
height: 30px;
Text {
text: root.item.amount;
font-size: 12pt;
}
}
Rectangle {
height: 30px;
Text {
opacity: (root.item.checked ? 0.5 : 1.0);
font-size: 12pt;
text: root.item.name;
}
Rectangle {
height: 30px;
Text {
opacity: (root.item.checked ? 0.5 : 1.0);
font-size: 12pt;
text: root.item.name;
}
}
}
@@ -188,7 +168,7 @@ component GoodsListAdd {
for item in items: VerticalLayout {
GoodListItemAdd {
item <=> item;
item: item;
}
Rectangle {
@@ -205,21 +185,19 @@ component GoodButtons inherits ScrollView {
property <int> count-x: floor(root.width / (button-min-width + button-spacing));
property <int> count-y: ceil(State.favorites.length / count-x);
property <length> button-width: ((root.width + button-spacing) / count-x) - button-spacing;
property <length> button-width: ((self.width + button-spacing ) / count-x) - button-spacing;
content-height: (count-y * (button-height + button-spacing));
viewport-height: (count-y * (button-height + button-spacing));
mouse-drag-pan-enabled: true;
vertical-scrollbar-policy: always-off;
FlexboxLayout {
spacing: button-spacing;
for item in State.favorites: Button {
width: root.button-width;
height: root.button-height;
text: item.name;
clicked => {
State.add-to-list(item.name);
}
for item[idx] in State.favorites: Button {
x: floor(mod(idx, count-x)) * (root.button-width + root.button-spacing);
y: floor(idx / count-x) * (root.button-height + root.button-spacing);
width: root.button-width;
height: root.button-height;
text: item.name;
clicked => {
State.add-to-list(item.name);
}
}
}
@@ -247,7 +225,7 @@ component ConnStatusIndicator inherits Rectangle {
}
component RefreshButton inherits HorizontalLayout {
spacing: 8px;
spacing: 8px;
alignment: center;
Button {
text: "Refresh";
@@ -256,7 +234,6 @@ component RefreshButton inherits HorizontalLayout {
State.refresh-list();
}
}
ConnStatusIndicator { }
}
@@ -266,7 +243,7 @@ component AddView inherits VerticalLayout {
padding: 8px;
spacing: 8px;
RefreshButton { }
RefreshButton {}
goods := GoodsListAdd {
items <=> list;
@@ -304,25 +281,24 @@ component AddView inherits VerticalLayout {
GoodButtons { }
}
component ShopView inherits ScrollView {
component ShopView inherits VerticalLayout {
in property <[SItem]> list;
mouse-drag-pan-enabled: true;
VerticalLayout {
RefreshButton { }
padding: 8px;
spacing: 8px;
goods := GoodsList {
items <=> list;
}
padding: 8px;
spacing: 8px;
HorizontalLayout {
padding: 12px;
Button {
text: "I am done hehe";
clicked => {
State.delete-checked();
}
RefreshButton { }
goods := GoodsList {
items <=> list;
}
HorizontalLayout {
padding: 12px;
Button {
text: "I am done hehe";
clicked => {
State.delete-checked();
}
}
}
@@ -346,26 +322,23 @@ component CatItem inherits HorizontalBox {
}
component CatView inherits ScrollView {
component CatView inherits VerticalLayout {
in-out property <[SButtonItem]> cats;
mouse-drag-pan-enabled: true;
VerticalLayout {
for item in cats: CatItem {
item: item;
}
for item in cats: CatItem {
item: item;
}
}
export component App inherits Window {
in property <int> prefered-start-tab: 0;
title: "Inköpslista";
icon: @image-url("../images/icon.svg");
preferred-height: 700px;
preferred-width: 480px;
tabs := TabWidget {
current-index: prefered-start-tab;
TabWidget {
Tab {
title: "Add";
AddView {
-4
View File
@@ -2,10 +2,6 @@ export struct SItem {
name: string,
checked: bool,
amount: int,
/// Whether the item was just added by the user.
/// Determines whether the add-animation plays.
just_added: bool,
}
export struct SButtonItem{
+4 -1
View File
@@ -9,6 +9,9 @@ serde_json = "1.0.145"
inkopslista-lib = { path = "../lib" }
sqlite = "0.37.0"
clap = { version = "4.6.6", features = ["derive", "env"] }
axum = { version = "0.8.9", features = ["http1"] }
axum = { version = "0.8.9", features = ["http1", "http2", "tokio"] }
tower-http = { version = "0.7.0", features = ["fs", "trace", "compression-gzip"] }
tokio = { version = "1.53.1", features = ["full"] }
rmcp = { version = "3.1.2", features = ["server", "macros", "schemars", "transport-streamable-http-server", "transport-streamable-http-server-session"] }
tracing = "0.1.44"
tracing-subscriber = { version = "0.3.23", features = ["env-filter"] }
+20
View File
@@ -9,6 +9,10 @@ use std::net::SocketAddr;
use std::path::PathBuf;
use std::sync::Arc;
use tower_http::services::ServeDir;
use tower_http::trace::TraceLayer;
use tracing::Level;
mod mcp;
/// The directory where the web files for the gui is stored.
fn www_path() -> &'static std::path::Path {
@@ -116,6 +120,8 @@ struct Opt {
bind: SocketAddr,
#[clap(long, env = "DB_PATH")]
db_path: PathBuf,
#[clap(long, env = "RUST_LOG", default_value = "debug")]
log_level: String,
#[clap(long, env = "NUM_DAYS", default_value = "5")]
num_days: u32,
}
@@ -123,6 +129,11 @@ struct Opt {
#[tokio::main]
async fn main() {
let opt = Opt::parse();
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::new(&opt.log_level))
.init();
let db = sqlite::Connection::open_thread_safe(opt.db_path).unwrap();
db.execute(include_str!("db/init.sql"))
.expect("unable to initialize database");
@@ -135,8 +146,17 @@ async fn main() {
.route("/api/favorites", get(get_favorites))
.route("/api/favorites/{item}/category", put(put_category))
.fallback_service(ServeDir::new(www_path()))
.nest_service("/mcp", mcp::service(db.clone()))
.layer(
TraceLayer::new_for_http()
.make_span_with(tower_http::trace::DefaultMakeSpan::new().level(Level::INFO))
.on_request(tower_http::trace::DefaultOnRequest::new().level(Level::INFO))
.on_response(tower_http::trace::DefaultOnResponse::new().level(Level::INFO)),
)
.with_state(db);
let listener = tokio::net::TcpListener::bind(opt.bind).await.unwrap();
tracing::info!("Listening on http://{}", opt.bind);
axum::serve(listener, app).await.unwrap();
}
+89
View File
@@ -0,0 +1,89 @@
//! MCP routes
use axum::Json;
use axum::extract::{Path, State};
use inkopslista_lib::ItemData;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
use rmcp::transport::streamable_http_server::tower::{
StreamableHttpServerConfig, StreamableHttpService,
};
use rmcp::{schemars, tool, tool_router};
use serde::Deserialize;
use sqlite::ConnectionThreadSafe;
use std::fmt::Write;
use std::sync::Arc;
#[derive(Debug, Deserialize, schemars::JsonSchema)]
struct PutParams {
/// The name of the shopping-list item,
item: String,
/// The number of items to buy.
#[serde(default = "default_amount")]
amount: i64,
/// Whether the item has been checked off.
#[serde(default)]
checked: bool,
}
fn default_amount() -> i64 {
1
}
#[derive(Clone)]
pub struct McpServer {
db: Arc<ConnectionThreadSafe>,
}
#[tool_router(server_handler)]
impl McpServer {
#[tool(description = "Read the entire shopping list")]
async fn list(&self) -> String {
// TODO: don't call the HTTP request handlers. Split the DB stuff out instead.
let db = State(self.db.clone());
let items = crate::get_list(db).await.0;
let mut out = String::new();
for item in items {
_ = writeln!(
&mut out,
"- [{checked}] {n}x {name}",
checked = if item.data.checked { "x" } else { " " },
n = item.data.amount,
name = item.name,
);
}
out
}
#[tool(description = "Put an item onto the shopping list.")]
async fn put(&self, Parameters(params): Parameters<PutParams>) -> String {
// TODO: don't call the HTTP request handlers. Split the DB stuff out instead.
let db = State(self.db.clone());
let data = ItemData {
amount: params.amount,
checked: params.checked,
};
crate::put_list(db, Path(params.item), Json(data)).await;
"Ok".to_string()
}
}
/// Create an MCP service that can be plugged into axum
pub fn service(
db: Arc<ConnectionThreadSafe>,
) -> StreamableHttpService<McpServer, LocalSessionManager> {
// TODO: tower_http::auth::add_authorization
let config = StreamableHttpServerConfig::default()
.with_legacy_session_mode(true)
.with_json_response(false)
.disable_allowed_hosts()
.disable_allowed_origins();
let server = McpServer { db };
StreamableHttpService::new(
move || Ok(server.clone()),
LocalSessionManager::default().into(),
config,
)
}