2 Commits
Author SHA1 Message Date
hulthe 3873fad612 Add MCP server 2026-08-21 22:54:12 +02:00
hulthe b874f0c577 Replace rocket with axum 2026-08-20 23:59:51 +02:00
8 changed files with 490 additions and 690 deletions
-29
View File
@@ -1,29 +0,0 @@
name: APK Builder
run-name: Build Android APK
on: [push]
jobs:
build-apk:
runs-on: ubuntu-latest
container:
image: docker.nubo.sh/inkopslista-builder:latest
strategy:
matrix:
arch: [aarch64, x86_64]
steps:
- name: Check out repository code
uses: actions/checkout@v4
- run: echo "SHA_SHORT=$(echo ${{ gitea.sha }} | head -c 8)" >> $GITEA_ENV
- run: echo "OUT_NAME=inkopslista.${{ env.SHA_SHORT }}.${{ matrix.arch }}.apk" >> $GITEA_ENV
- run: cargo apk build --lib --release -p inkopslista --target ${{ matrix.arch }}-linux-android
- run: mv "$CARGO_TARGET_DIR/release/apk/inkopslista.apk" "$OUT_NAME"
- uses: https://gitea.com/actions/gitea-upload-artifact@v4
with:
name : "${{ env.OUT_NAME }}"
path: "${{ env.OUT_NAME }}"
if-no-files-found: error
overwrite: true
retention-days: 1 # TODO
-23
View File
@@ -1,23 +0,0 @@
name: Gitea Actions Demo
run-name: ${{ gitea.actor }} is testing out Gitea Actions 🚀
on: [push]
jobs:
Explore-Gitea-Actions:
runs-on: ubuntu-latest
container:
image: docker.nubo.sh/inkopslista-builder:latest
steps:
- run: cargo --version
- run: rustup target list --installed
- run: echo "🎉 The job was automatically triggered by a ${{ gitea.event_name }} event."
- run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by Gitea!"
- run: echo "🔎 The name of your branch is ${{ gitea.ref }} and your repository is ${{ gitea.repository }}."
- name: Check out repository code
uses: actions/checkout@v4
- run: echo "💡 The ${{ gitea.repository }} repository has been cloned to the runner."
- run: echo "🖥️ The workflow is now ready to test your code on the runner."
- name: List files in the repository
run: |
ls ${{ gitea.workspace }}
- run: echo "🍏 This job's status is ${{ job.status }}."
Generated
+325 -579
View File
File diff suppressed because it is too large Load Diff
+1 -2
View File
@@ -63,8 +63,7 @@ RUN wasm-pack build --release --target web
FROM scratch
ENV RUST_LOG="info"
ENV ROCKET_ADDRESS="0.0.0.0"
ENV ROCKET_PORT="8000"
ENV BIND="0.0.0.0:8000"
VOLUME ["/data"]
ENV DB_PATH="/data/db.sqlite"
+1 -1
View File
@@ -71,7 +71,7 @@ async fn put_category(
) -> Result<(), anyhow::Error> {
let client = reqwest::Client::new();
let url: Url = format!(
"{address}/api/favourites/{itemname}/category",
"{address}/api/favorites/{itemname}/category",
address = conf.lock().unwrap().address
)
.parse()?;
+6 -1
View File
@@ -4,9 +4,14 @@ version = "0.1.0"
edition = "2024"
[dependencies]
rocket = { version = "0.5.1", features = ["json"] }
serde = { version = "1.0.228", features = ["derive"] }
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", "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"] }
+68 -55
View File
@@ -1,32 +1,29 @@
#[macro_use]
extern crate rocket;
use axum::extract::{Path, State};
use axum::response::Html;
use axum::routing::method_routing::{get, put};
use axum::{Json, Router};
use clap::Parser;
use inkopslista_lib::{ButtonItem, Item, ItemData};
use rocket::{
State,
fs::{FileServer, NamedFile},
serde::json::Json,
shield::Shield,
};
use sqlite::ConnectionThreadSafe;
use std::path::{Path, PathBuf};
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 Path {
Path::new("./www")
fn www_path() -> &'static std::path::Path {
std::path::Path::new("./www")
}
/// Serve `index.html` from [`www_path`].
#[get("/")]
async fn index() -> NamedFile {
NamedFile::open(www_path().join("index.html"))
.await
.expect("index.html")
async fn index() -> Html<&'static str> {
Html(include_str!("../../gui/index.html"))
}
#[get("/api/list")]
fn get_list(db: &State<ConnectionThreadSafe>) -> Json<Vec<Item>> {
async fn get_list(State(db): State<Arc<ConnectionThreadSafe>>) -> Json<Vec<Item>> {
// TODO errorhandling
let query = "SELECT * FROM list;";
let list = db
@@ -47,8 +44,7 @@ fn get_list(db: &State<ConnectionThreadSafe>) -> Json<Vec<Item>> {
Json(list)
}
#[get("/api/favorites")]
fn get_favorites(db: &State<ConnectionThreadSafe>) -> Json<Vec<ButtonItem>> {
async fn get_favorites(State(db): State<Arc<ConnectionThreadSafe>>) -> Json<Vec<ButtonItem>> {
let opt = Opt::parse();
let query = format!("WITH favorites as (SELECT itemname, COUNT(date_added) day_count
@@ -75,24 +71,30 @@ fn get_favorites(db: &State<ConnectionThreadSafe>) -> Json<Vec<ButtonItem>> {
Json(list)
}
#[put("/api/favourites/<itemname>/category", data = "<category>")]
fn put_category(db: &State<ConnectionThreadSafe>, itemname: &str, category: &str) {
async fn put_category(
State(db): State<Arc<ConnectionThreadSafe>>,
Path(item): Path<String>,
category: String,
) {
let query = "INSERT INTO categories VALUES (?, ?) ON CONFLICT DO UPDATE SET category = ?";
let mut statement = db.prepare(query).unwrap();
statement.bind((1, itemname)).unwrap();
statement.bind((2, category)).unwrap();
statement.bind((3, category)).unwrap();
statement.bind((1, item.as_str())).unwrap();
statement.bind((2, category.as_str())).unwrap();
statement.bind((3, category.as_str())).unwrap();
while let Ok(sqlite::State::Row) = statement.next() {}
}
#[put("/api/list/<item>", data = "<data>")]
fn put_list(item: &str, data: Json<ItemData>, db: &State<ConnectionThreadSafe>) {
async fn put_list(
State(db): State<Arc<ConnectionThreadSafe>>,
Path(item): Path<String>,
Json(data): Json<ItemData>,
) {
// TODO: errorhandling
// TODO: transaction
let query =
"INSERT INTO list VALUES(?, ?, ?) ON CONFLICT DO UPDATE SET checked = ?, amount = ?;";
let mut statement = db.prepare(query).unwrap();
let data = data.into_inner();
statement.bind((1, item)).unwrap();
statement.bind((1, item.as_str())).unwrap();
statement.bind((2, data.checked as i64)).unwrap();
statement.bind((3, data.amount)).unwrap();
statement.bind((4, data.checked as i64)).unwrap();
@@ -100,50 +102,61 @@ fn put_list(item: &str, data: Json<ItemData>, db: &State<ConnectionThreadSafe>)
while let Ok(sqlite::State::Row) = statement.next() {}
let query = "INSERT INTO adds VALUES(?, strftime('%s','now')) ON CONFLICT DO NOTHING";
let mut statement = db.prepare(query).unwrap();
statement.bind((1, item)).unwrap();
statement.bind((1, item.as_str())).unwrap();
while let Ok(sqlite::State::Row) = statement.next() {}
}
#[delete("/api/list/<item>")]
fn delete_item(item: &str, db: &State<ConnectionThreadSafe>) {
async fn delete_item(State(db): State<Arc<ConnectionThreadSafe>>, Path(item): Path<String>) {
// TODO: Eror handling
let query = "DELETE FROM list WHERE itemname = ?";
let mut statement = db.prepare(query).unwrap();
statement.bind((1, item)).unwrap();
statement.bind((1, item.as_str())).unwrap();
while let Ok(sqlite::State::Row) = statement.next() {}
}
#[derive(Parser)]
struct Opt {
#[clap(long, env = "BIND", default_value = "127.0.0.1:8000")]
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,
}
#[launch]
fn rocket() -> _ {
#[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");
rocket::build()
.attach(
Shield::default()
// Allow content to be served through iframes
.disable::<rocket::shield::Frame>(),
let db = Arc::new(db);
let app = Router::new()
.route("/", get(index))
.route("/api/list", get(get_list))
.route("/api/list/{item}", put(put_list).delete(delete_item))
.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)),
)
.manage(db)
.mount(
"/",
routes![
index,
get_list,
put_list,
delete_item,
get_favorites,
put_category
],
)
.mount("/", FileServer::from(www_path()))
.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,
)
}