Compare commits

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

No files matched your search

Generated
+1144 -532
View File
File diff suppressed because it is too large. Load diff
+2 -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",
@@ -63,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"
+35 -43
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;
@@ -186,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);
}
}
}
@@ -228,7 +225,7 @@ component ConnStatusIndicator inherits Rectangle {
}
component RefreshButton inherits HorizontalLayout {
spacing: 8px;
spacing: 8px;
alignment: center;
Button {
text: "Refresh";
@@ -237,7 +234,6 @@ component RefreshButton inherits HorizontalLayout {
State.refresh-list();
}
}
ConnStatusIndicator { }
}
@@ -247,7 +243,7 @@ component AddView inherits VerticalLayout {
padding: 8px;
spacing: 8px;
RefreshButton { }
RefreshButton {}
goods := GoodsListAdd {
items <=> list;
@@ -285,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();
}
}
}
@@ -327,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 -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,
)
}