From 0d335b808c4f2be55e51773e37ffe199a5dbd6ff Mon Sep 17 00:00:00 2001 From: iz0eyj Date: Mon, 30 Nov 2026 02:29:55 +0100 Subject: [PATCH] agent: wire MCP connectors into the loop (rmcp v3, Initialize lifecycle) - src/mcp: streamable-HTTP client (rmcp v3.12) negotiating Initialize + LATEST_WITH_INITIALIZE; namespaced mcp__{connector}__{tool} surface, write badges from ToolAnnotations, persisted discovery (tools_json) so the agent tool declarations stay byte-stable for KV-cache reuse. - store: mcp_connectors catalog + tools_json column (idempotent migration) and set_mcp_tools; per-session per-tool allowlist (SessionSettings.mcp_enabled). - agent: execute_mcp routes namespaced calls, gated on the session allowlist before any network call; Bearer token comes from the DB catalog, never echoed. - api/sessions: build the MCP surface into Ambient + the agent tool declarations on both the turn and prewarm paths (identical rebuild keeps the prefix stable). - api/mcp + GUI: connector CRUD, tool-discovery picker, per-session enable. - examples/mcp_probe: read-only CLI discovery spike. Live-verified: 22 gmail tools discovered, gmail_labels returned 25 labels, and a full model-driven GUI turn (7 enabled tools) with a 9197-token RESUME cache hit. --- Cargo.lock | 921 ++++++++++++++++++++++++++++++++++++- Cargo.toml | 1 + examples/mcp_probe.rs | 67 +++ src/agent/mod.rs | 107 ++++- src/api/mcp.rs | 148 ++++++ src/api/mod.rs | 1 + src/api/routes.rs | 8 +- src/api/sessions.rs | 74 ++- src/lib.rs | 1 + src/mcp/client.rs | 111 +++++ src/mcp/mod.rs | 319 +++++++++++++ src/store.rs | 199 +++++++- tests/api_sessions.rs | 47 ++ web/assets/app.css | 37 +- web/assets/app.js | 164 ++++++- web/assets/locales/en.json | 23 + web/assets/locales/it.json | 23 + web/index.html | 32 ++ 18 files changed, 2266 insertions(+), 17 deletions(-) create mode 100644 examples/mcp_probe.rs create mode 100644 src/api/mcp.rs create mode 100644 src/mcp/client.rs create mode 100644 src/mcp/mod.rs diff --git a/Cargo.lock b/Cargo.lock index 3bb1a4f..172911c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -142,6 +142,29 @@ dependencies = [ "arrayvec", ] +[[package]] +name = "aws-lc-rs" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" +dependencies = [ + "aws-lc-sys", + "zeroize", +] + +[[package]] +name = "aws-lc-sys" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" +dependencies = [ + "cc", + "cmake", + "dunce", + "fs_extra", + "pkg-config", +] + [[package]] name = "axum" version = "0.8.9" @@ -293,12 +316,48 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures", + "rand_core 0.10.1", +] + +[[package]] +name = "cmake" +version = "0.1.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0f78a02292a74a88ac736019ab962ece0bc380e3f977bf72e376c5d78ff0678" +dependencies = [ + "cc", +] + [[package]] name = "color_quant" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "compact_str" version = "0.9.1" @@ -332,6 +391,22 @@ version = "0.10.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be95d4a884358a21a199689323c29e9256b4a1b315e22f183d155422041d3a9a" +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + [[package]] name = "cpufeatures" version = "0.3.1" @@ -482,6 +557,23 @@ dependencies = [ "crypto-common", ] +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + [[package]] name = "either" version = "1.19.0" @@ -514,6 +606,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + [[package]] name = "errno" version = "0.3.15" @@ -608,6 +706,12 @@ dependencies = [ "percent-encoding", ] +[[package]] +name = "fs_extra" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c" + [[package]] name = "futures" version = "0.3.34" @@ -712,8 +816,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" dependencies = [ "cfg-if", + "js-sys", "libc", "wasi", + "wasm-bindgen", ] [[package]] @@ -738,6 +844,7 @@ dependencies = [ "js-sys", "libc", "r-efi 6.0.0", + "rand_core 0.10.1", "wasm-bindgen", ] @@ -771,13 +878,19 @@ dependencies = [ "ahash", ] +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + [[package]] name = "hashlink" version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ba4ff7128dee98c7dc9794b6a411377e1404dba1c97deb8d1a55297bd25d8af" dependencies = [ - "hashbrown", + "hashbrown 0.14.5", ] [[package]] @@ -851,6 +964,22 @@ dependencies = [ "pin-project-lite", "smallvec", "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", ] [[package]] @@ -859,13 +988,105 @@ version = "0.1.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" dependencies = [ + "base64 0.23.1", "bytes", + "futures-channel", + "futures-util", "http", "http-body", + "httparse", "hyper", + "ipnet", + "libc", + "percent-encoding", "pin-project-lite", + "socket2", "tokio", "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", ] [[package]] @@ -874,6 +1095,27 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + [[package]] name = "image" version = "0.25.10" @@ -914,6 +1156,18 @@ version = "1.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.2", + "serde", + "serde_core", +] + [[package]] name = "indicatif" version = "0.18.6" @@ -938,6 +1192,12 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "ipnet" +version = "2.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "007d6e6b91097094791302ccc6cd0588e0700ddac5c6829035bcd71eff4dc433" + [[package]] name = "itertools" version = "0.14.0" @@ -953,6 +1213,90 @@ version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" +[[package]] +name = "jiff" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "107f2e89536b6818514025f6787b0d94d819e54fe3b40365275fc753de485b3f" +dependencies = [ + "jiff-core", + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-core" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d44c923edf2bf456a982253f1a9ee1f6e89e421dffd0065d9b9a581da0def58f" +dependencies = [ + "log", +] + +[[package]] +name = "jiff-static" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4996f71e569e3a3e32b925c28ef8f0027dc30bb1d594b33eeda409eea185f5c8" +dependencies = [ + "jiff-core", + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys", + "log", + "simd_cesu8", + "thiserror", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "jobserver" version = "0.1.35" @@ -1013,6 +1357,12 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + [[package]] name = "lock_api" version = "0.4.14" @@ -1037,6 +1387,12 @@ dependencies = [ "imgref", ] +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + [[package]] name = "macro_rules_attribute" version = "0.2.3" @@ -1327,6 +1683,12 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + [[package]] name = "parking_lot" version = "0.12.5" @@ -1405,6 +1767,24 @@ version = "1.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "ppv-lite86" version = "0.2.21" @@ -1491,6 +1871,63 @@ version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "aws-lc-rs", + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.4", + "rand_pcg", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + [[package]] name = "quote" version = "1.0.47" @@ -1519,7 +1956,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ "rand_chacha", - "rand_core", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", ] [[package]] @@ -1529,7 +1977,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.9.5", ] [[package]] @@ -1541,6 +1989,21 @@ dependencies = [ "getrandom 0.3.4", ] +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core 0.10.1", +] + [[package]] name = "rav1e" version = "0.8.1" @@ -1568,7 +2031,7 @@ dependencies = [ "num-traits", "paste", "profiling", - "rand", + "rand 0.9.5", "rand_chacha", "simd_helpers", "thiserror", @@ -1660,6 +2123,46 @@ version = "0.8.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" +[[package]] +name = "reqwest" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "rustls-platform-verifier", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + [[package]] name = "rgb" version = "0.8.53" @@ -1680,6 +2183,35 @@ dependencies = [ "windows-sys 0.52.0", ] +[[package]] +name = "rmcp" +version = "3.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc4fa9a7558c480e1817c0f02e9a73782001ac1f47fb9d26cc073915963282ea" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures", + "http", + "indexmap", + "jiff", + "libc", + "percent-encoding", + "pin-project-lite", + "reqwest", + "serde", + "serde_json", + "sha2", + "sse-stream", + "thiserror", + "tokio", + "tokio-stream", + "tokio-util", + "tracing", + "unicode-general-category", + "unicode-normalization", +] + [[package]] name = "rusqlite" version = "0.32.1" @@ -1729,12 +2261,28 @@ dependencies = [ "walkdir", ] +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustls" version = "0.23.46" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" dependencies = [ + "aws-lc-rs", "log", "once_cell", "ring", @@ -1744,21 +2292,62 @@ dependencies = [ "zeroize", ] +[[package]] +name = "rustls-native-certs" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a073f5dc7469f984c52ad2752b63b0807745133b6de880b7b64c1ac4c48aec4" +dependencies = [ + "openssl-probe", + "rustls-pki-types", + "schannel", + "security-framework", +] + [[package]] name = "rustls-pki-types" version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" dependencies = [ + "web-time", "zeroize", ] +[[package]] +name = "rustls-platform-verifier" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1167586491e2b18b8bfbb293e8180ec17c201c4f076d7cb3070ca964e7598f98" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls", + "rustls-native-certs", + "rustls-platform-verifier-android", + "rustls-webpki", + "security-framework", + "security-framework-sys", + "webpki-root-certs", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eec689c0bc40ff2458a5977b6619cb718087084a18e02a131c599b62d05e1a5f" + [[package]] name = "rustls-webpki" version = "0.103.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" dependencies = [ + "aws-lc-rs", "ring", "rustls-pki-types", "untrusted", @@ -1785,12 +2374,50 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "scopeguard" version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + [[package]] name = "serde" version = "1.0.229" @@ -1899,6 +2526,16 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + [[package]] name = "simd_helpers" version = "0.1.0" @@ -1908,6 +2545,12 @@ dependencies = [ "quote", ] +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "slab" version = "0.4.12" @@ -1942,6 +2585,19 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "sse-stream" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c25ac7aff0abd1dbc474536e40416e1102c7dd9bfba0b9861c6d357f835dcfb4" +dependencies = [ + "bytes", + "futures-util", + "http-body", + "http-body-util", + "pin-project-lite", +] + [[package]] name = "stable_deref_trait" version = "1.2.1" @@ -1967,6 +2623,7 @@ dependencies = [ "minijinja", "pulldown-cmark", "pulldown-latex", + "rmcp", "rusqlite", "rust-embed", "serde", @@ -2020,6 +2677,20 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] [[package]] name = "target-features" @@ -2070,6 +2741,22 @@ dependencies = [ "zune-jpeg", ] +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + [[package]] name = "tokenizers" version = "0.23.2" @@ -2090,7 +2777,7 @@ dependencies = [ "monostate", "onig", "paste", - "rand", + "rand 0.9.5", "rayon", "rayon-cond", "regex", @@ -2132,6 +2819,16 @@ dependencies = [ "syn 3.0.10", ] +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + [[package]] name = "tokio-stream" version = "0.1.19" @@ -2143,6 +2840,19 @@ dependencies = [ "tokio", ] +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + [[package]] name = "tower" version = "0.5.3" @@ -2159,6 +2869,24 @@ dependencies = [ "tracing", ] +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + [[package]] name = "tower-layer" version = "0.3.3" @@ -2233,6 +2961,12 @@ dependencies = [ "tracing-log", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "typenum" version = "1.20.1" @@ -2245,12 +2979,27 @@ version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "unicode-normalization" +version = "0.1.26" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75cd3fb03d5288b3ba9a1ee103ac7e9cbb59f0b03d64f8ddfcc04dd42758a85d" +dependencies = [ + "tinyvec", +] + [[package]] name = "unicode-normalization-alignments" version = "0.1.12" @@ -2319,12 +3068,39 @@ dependencies = [ "log", ] +[[package]] +name = "url" +version = "2.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f00cd2407bb42c0ef17be88d4cf020f5cceffd121665bac9b8b9493a369b3b1a" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + [[package]] name = "utf8-zero" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" +[[package]] +name = "utf8_iter" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af3bd9d3e571c26fcce9d033b87ea5ab061b8d2ffe9b7a5675d810d68f03edf0" +dependencies = [ + "utf_types", +] + +[[package]] +name = "utf_types" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a3b425286980a367278453f3b6d28cdcb134b574e5a35824a6ff5eebad50bb6" + [[package]] name = "v_frame" version = "0.3.9" @@ -2364,6 +3140,15 @@ dependencies = [ "winapi-util", ] +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" @@ -2391,6 +3176,17 @@ dependencies = [ "wasm-bindgen-shared", ] +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + [[package]] name = "wasm-bindgen-macro" version = "0.2.130" @@ -2423,6 +3219,29 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "wasm-streams" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "web-time" version = "1.1.0" @@ -2433,6 +3252,15 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-root-certs" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "293198dcebfb821155b5092ab94b5a82ff180eddd7241df3bd6e66a4ffd1a585" +dependencies = [ + "rustls-pki-types", +] + [[package]] name = "webpki-roots" version = "1.0.12" @@ -2551,12 +3379,41 @@ version = "0.57.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + [[package]] name = "y4m" version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + [[package]] name = "zerocopy" version = "0.8.64" @@ -2577,12 +3434,66 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", + "synstructure", +] + [[package]] name = "zeroize" version = "1.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + [[package]] name = "zlib-rs" version = "0.6.8" diff --git a/Cargo.toml b/Cargo.toml index f86902f..db575b8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,6 +28,7 @@ rusqlite = { version = "0.32", features = ["bundled"] } rust-embed = "8" pulldown-cmark = "0.13.6" pulldown-latex = "0.8.0" +rmcp = { version = "3.12.0", default-features = false, features = ["client", "transport-streamable-http-client-reqwest", "reqwest"] } [dev-dependencies] http-body-util = "0.1.5" diff --git a/examples/mcp_probe.rs b/examples/mcp_probe.rs new file mode 100644 index 0000000..af651eb --- /dev/null +++ b/examples/mcp_probe.rs @@ -0,0 +1,67 @@ +//! Bounded MCP connectivity spike: connect to ONE external MCP server over +//! streamable-HTTP with a Bearer token, discover its tools, print each name + +//! read/write hint + the namespaced name the agent would see, then close. +//! READ-ONLY: no tool is ever called. +//! +//! Usage (token passed as an argument; no env vars): +//! +//! ```sh +//! cargo run --example mcp_probe -- http://192.168.50.117:8080/ gmail +//! ``` +//! +//! The GUI settings picker does the same discovery against the saved catalog; +//! this spike is for quick command-line checks. + +use strata_ctl::mcp::{self, ConnectorSpec}; + +#[tokio::main] +async fn main() { + let args: Vec = std::env::args().collect(); + if args.len() < 3 { + eprintln!("usage: cargo run --example mcp_probe -- [connector-name]"); + std::process::exit(2); + } + let spec = ConnectorSpec { + url: args[1].clone(), + token: args[2].clone(), + name: args.get(3).cloned().unwrap_or_else(|| "gmail".into()), + }; + + println!("connecting to {} (connector '{}') ...", spec.url, spec.name); + let client = match mcp::client::McpClient::connect(&spec, &spec.token).await { + Ok(c) => c, + Err(e) => { + eprintln!("connect error: {e}"); + std::process::exit(1); + } + }; + println!("connected."); + + match client.list_tools().await { + Ok(tools) => { + println!("discovered {} tools:", tools.len()); + for t in &tools { + let badge = if mcp::is_write_tool(t) { + "write" + } else { + "read " + }; + println!( + " [{badge}] {} -> {}", + t.name, + mcp::namespaced(&spec.name, t.name.as_ref()) + ); + if let Some(d) = &t.description { + if let Some(first) = d.lines().next() { + println!(" {first}"); + } + } + } + } + Err(e) => eprintln!("list error: {e}"), + } + + if let Err(e) = client.close().await { + eprintln!("close error: {e}"); + } +} diff --git a/src/agent/mod.rs b/src/agent/mod.rs index 5322836..97098bd 100644 --- a/src/agent/mod.rs +++ b/src/agent/mod.rs @@ -21,7 +21,8 @@ use serde_json::{json, Value as Json}; use tokio::sync::mpsc::UnboundedSender; use crate::api::types::{ApiErrorEnvelope, ChatMessage, ChatRequest, ChatResponse, Role, ToolCall}; -use crate::store::{NewMessage, Store}; +use crate::mcp::{self, client::McpClient, ConnectorSpec}; +use crate::store::{McpConnector, NewMessage, Store}; use shell::{ShellRequest, ShellRunner}; /// Default cap on model↔tool iterations, so a misbehaving model cannot loop forever. @@ -101,10 +102,68 @@ async fn execute_tool( } "notepad" => notepad::execute(store, session_id, &args).await, "share_file" => share::execute(session_id, &args, default_cwd, workspace_root).await, + name if mcp::is_mcp_tool(name) => execute_mcp(store, session_id, name, &args).await, other => format!("error: unknown tool '{other}'"), } } +/// Execute a namespaced MCP tool call: resolve the connector from the global +/// catalog and gate on the session's per-tool allowlist (the model may only call +/// what the user enabled), then connect live and call the ORIGINAL tool name. +/// The Bearer token comes from the DB catalog and is never echoed into the result. +async fn execute_mcp(store: &Arc, session_id: &str, name: &str, args: &Json) -> String { + let Some((connector, tool)) = mcp::parse_namespaced(name) else { + return format!("error: malformed MCP tool name '{name}'"); + }; + let store2 = store.clone(); + let sid = session_id.to_string(); + let cname = connector.clone(); + let tname = tool.clone(); + let loaded = + tokio::task::spawn_blocking(move || -> anyhow::Result<(Option, bool)> { + let conn = store2 + .mcp_connectors()? + .into_iter() + .find(|c| c.name == cname); + let allowed = store2 + .get_session(&sid)? + .and_then(|s| s.settings.mcp_enabled.get(&cname).cloned()) + .map(|v| v.contains(&tname)) + .unwrap_or(false); + Ok((conn, allowed)) + }) + .await; + let (conn, allowed) = match loaded { + Ok(Ok(x)) => x, + Ok(Err(e)) => return format!("error: MCP lookup failed: {e}"), + Err(e) => return format!("error: MCP task failed: {e}"), + }; + let Some(conn) = conn else { + return format!("error: unknown MCP connector '{connector}'"); + }; + if !allowed { + return format!( + "error: tool '{tool}' is not enabled for connector '{connector}' in this session" + ); + } + let spec = ConnectorSpec { + name: conn.name.clone(), + url: conn.url.clone(), + token: conn.token.clone(), + }; + let client = match McpClient::connect(&spec, &spec.token).await { + Ok(c) => c, + Err(e) => return format!("error: {e}"), + }; + let result = client.call_tool(&tool, args.clone()).await; + // Best-effort close; never mask the call result. + let _ = client.close().await; + match result { + Ok(r) => mcp::result_to_text(&r), + Err(e) => format!("error: {e}"), + } +} + /// An owned message to persist (the store trait is sync; we spawn_blocking it). struct Persisted { role: String, @@ -493,6 +552,52 @@ mod tests { assert!(out.contains("unknown tool")); } + #[tokio::test] + async fn mcp_routing_is_allowlist_gated() { + let store: Arc = Arc::new(SqliteStore::open_in_memory().unwrap()); + let mut settings = crate::store::SessionSettings::default(); + settings + .mcp_enabled + .insert("gmail".into(), vec!["gmail_search".into()]); + let sess = store.create_session("Agent", "m", &settings).unwrap(); + store + .upsert_mcp_connector(&McpConnector { + name: "gmail".into(), + url: "http://127.0.0.1:1/".into(), + token: "tok".into(), + tools_json: None, + created_at: 0, + updated_at: 0, + }) + .unwrap(); + let runner: Arc = Arc::new(HostShell); + let call = |name: &str| ToolCall { + id: "c".into(), + kind: "function".into(), + function: FunctionCall { + name: name.into(), + arguments: "{}".into(), + }, + }; + // A tool the user did NOT enable is refused before any network call. + let out = execute_tool( + &runner, + &store, + &sess.id, + &call("mcp__gmail__gmail_send"), + None, + None, + ) + .await; + assert!(out.contains("not enabled"), "{out}"); + // An unknown connector is refused. + let out = execute_tool(&runner, &store, &sess.id, &call("mcp__nope__x"), None, None).await; + assert!(out.contains("unknown MCP connector"), "{out}"); + // A malformed namespaced name is refused. + let out = execute_tool(&runner, &store, &sess.id, &call("mcp__gmail"), None, None).await; + assert!(out.contains("malformed"), "{out}"); + } + #[tokio::test] async fn loop_runs_notepad_tool_and_persists_entry() { let store: Arc = Arc::new(SqliteStore::open_in_memory().unwrap()); diff --git a/src/api/mcp.rs b/src/api/mcp.rs new file mode 100644 index 0000000..e38250e --- /dev/null +++ b/src/api/mcp.rs @@ -0,0 +1,148 @@ +//! MCP connector management API for the GUI settings. +//! +//! Two levels, mirroring the ratified design: +//! - the GLOBAL catalog (`/api/mcp/connectors`): connection parameters (name, +//! url, token). The Bearer token is stored in the local DB like all other +//! persistent state (no env vars / files — that would break cloud access). +//! - LIVE discovery (`/api/mcp/connectors/{name}/tools`): connect on demand, +//! `tools/list`, and return the tool names + descriptions + write hint so the +//! GUI can render the per-tool checkbox picker. The chosen allowlist is saved +//! per session in `SessionSettings.mcp_enabled` (via the session PATCH), not +//! here. +//! +//! Discovery is read-only: no tool is ever called from this surface. + +use axum::extract::{Path, State}; +use axum::http::StatusCode; +use axum::response::Json; +use serde::{Deserialize, Serialize}; + +use super::routes::{AppState, Error}; +use super::sessions::with_store; +use crate::mcp::{self, ConnectorSpec}; +use crate::store::McpConnector; + +/// `GET /api/mcp/connectors` — the global catalog, ordered by name. +pub(crate) async fn list_connectors( + State(st): State, +) -> Result>, Error> { + Ok(Json(with_store(&st, |s| s.mcp_connectors()).await?)) +} + +#[derive(Deserialize)] +pub(crate) struct ConnectorBody { + url: String, + token: String, +} + +/// `PUT /api/mcp/connectors/{name}` — create or update a connector's parameters. +/// The name is sanitized into a namespace-safe id; url and token are required. +/// The token is stored in the local DB catalog (no env vars), like all other +/// persistent state, so it works unchanged in cloud deployments. +pub(crate) async fn upsert_connector( + State(st): State, + Path(name): Path, + Json(body): Json, +) -> Result { + let name = mcp::sanitize_connector(&name); + if name.is_empty() { + return Err(Error::bad_request("connector name is empty or invalid")); + } + let url = body.url.trim().to_string(); + let token = body.token.trim().to_string(); + if url.is_empty() { + return Err(Error::bad_request("connector url is required")); + } + if token.is_empty() { + return Err(Error::bad_request("connector token is required")); + } + let connector = McpConnector { + name, + url, + token, + tools_json: None, + created_at: 0, + updated_at: 0, + }; + with_store(&st, move |s| s.upsert_mcp_connector(&connector)).await?; + Ok(StatusCode::OK) +} + +/// `DELETE /api/mcp/connectors/{name}` — remove a connector from the catalog. +pub(crate) async fn delete_connector( + State(st): State, + Path(name): Path, +) -> Result { + let existed = with_store(&st, move |s| s.delete_mcp_connector(&name)).await?; + if existed { + Ok(StatusCode::NO_CONTENT) + } else { + Err(Error::not_found("connector not found")) + } +} + +/// One discovered tool, shaped for the GUI checkbox picker. +#[derive(Serialize)] +pub(crate) struct ToolView { + name: String, + description: String, + /// Server hint that the tool mutates external state (the "write" badge). + write: bool, +} + +/// `POST /api/mcp/connectors/{name}/tools` — connect live and discover the tools +/// the server exposes. Read-only; the GUI uses this to populate the picker. +pub(crate) async fn list_tools( + State(st): State, + Path(name): Path, +) -> Result>, Error> { + let connector = with_store(&st, { + let name = name.clone(); + move |s| Ok(s.mcp_connectors()?.into_iter().find(|c| c.name == name)) + }) + .await? + .ok_or_else(|| Error::not_found("connector not found"))?; + + let spec = ConnectorSpec { + name: connector.name.clone(), + url: connector.url.clone(), + token: connector.token.clone(), + }; + let client = mcp::client::McpClient::connect(&spec, &spec.token) + .await + .map_err(upstream)?; + let tools = client.list_tools().await.map_err(upstream)?; + // Best-effort close; a close failure must not mask a successful discovery. + let _ = client.close().await; + // Persist the discovered surface so the agent builds its curated declarations + // and context synchronously from the catalog (no network on the turn / + // pre-warm path, byte-stable KV prefix). Best-effort: a storage failure must + // not mask a successful discovery for the picker. + if let Ok(json) = serde_json::to_string(&tools) { + let cname = connector.name.clone(); + if with_store(&st, move |s| s.set_mcp_tools(&cname, &json)) + .await + .is_err() + { + tracing::warn!("failed to persist MCP tool discovery for the agent surface"); + } + } + let views = tools + .iter() + .map(|t| ToolView { + name: t.name.to_string(), + description: t.description.as_deref().unwrap_or("").to_string(), + write: mcp::is_write_tool(t), + }) + .collect(); + Ok(Json(views)) +} + +/// An upstream MCP failure (unreachable server, bad credential, protocol error) +/// is a 502: the request was well-formed but the remote connector failed. +fn upstream(msg: String) -> Error { + Error::new( + StatusCode::BAD_GATEWAY, + super::types::ApiErrorEnvelope::new(msg, "server_error", Some("mcp_upstream".to_string())), + ) +} diff --git a/src/api/mod.rs b/src/api/mod.rs index 7a1e290..195c0e9 100644 --- a/src/api/mod.rs +++ b/src/api/mod.rs @@ -7,6 +7,7 @@ pub mod anthropic; mod files; pub mod formatter; +mod mcp; pub mod routes; pub mod service; mod sessions; diff --git a/src/api/routes.rs b/src/api/routes.rs index d6b27ee..fd89da3 100644 --- a/src/api/routes.rs +++ b/src/api/routes.rs @@ -15,7 +15,7 @@ use std::sync::Arc; use super::anthropic::{self, AnthropicRequest, AnthropicStream}; use super::service::ChatService; use super::types::{ApiErrorEnvelope, ChatRequest, ModelCard, ModelList}; -use super::{files, sessions, uploads, web}; +use super::{files, mcp, sessions, uploads, web}; use crate::store::Store; /// Build the router. Mount this inside any axum `Router` or serve it directly. @@ -95,6 +95,12 @@ fn build_router(state: AppState, auth: AuthConfig) -> Router { get(sessions::get_defaults).put(sessions::put_defaults), ) .route("/api/stats", get(sessions::stats)) + .route("/api/mcp/connectors", get(mcp::list_connectors)) + .route( + "/api/mcp/connectors/{name}", + axum::routing::put(mcp::upsert_connector).delete(mcp::delete_connector), + ) + .route("/api/mcp/connectors/{name}/tools", post(mcp::list_tools)) .route("/", get(web::index)) .route("/assets/{*path}", get(web::asset)); } diff --git a/src/api/sessions.rs b/src/api/sessions.rs index bb74780..df1d8cd 100644 --- a/src/api/sessions.rs +++ b/src/api/sessions.rs @@ -29,7 +29,8 @@ use crate::i18n::t; use crate::name; use crate::render; use crate::store::{ - ContextSection, NewMessage, NotepadEntry, Session, SessionSettings, Stats, Store, StoredMessage, + ContextSection, McpConnector, NewMessage, NotepadEntry, Session, SessionSettings, Stats, Store, + StoredMessage, }; use crate::window; use tokio_stream::wrappers::UnboundedReceiverStream; @@ -337,6 +338,39 @@ fn build_request( } } +/// Build the curated MCP surface for a session from the GLOBAL connector catalog +/// and the session's per-tool allowlist: the declarations to append to the agent +/// tools, and the `` context sections to pin beside TOOL_USE. Pure and +/// synchronous over persisted data, so the real turn and `schedule_prewarm` +/// produce a byte-identical prefix. Iterates the allowlist (a BTreeMap, sorted by +/// connector name) for a deterministic order; a connector with no persisted +/// discovery or an empty selection contributes nothing. +fn mcp_surface( + connectors: &[McpConnector], + allow: &BTreeMap>, +) -> (Vec, Vec) { + let mut declarations = Vec::new(); + let mut sections = Vec::new(); + for (name, tools) in allow { + if tools.is_empty() { + continue; + } + let Some(c) = connectors.iter().find(|c| &c.name == name) else { + continue; + }; + let s = crate::mcp::surface(name, c.tools_json.as_deref().unwrap_or(""), tools); + declarations.extend(s.declarations); + if let Some(body) = s.context { + sections.push(ContextSection { + name: format!("MCP_{}", name.to_uppercase()), + content: body, + position: 2, + }); + } + } + (declarations, sections) +} + /// Accumulates the assistant turn while streaming, for persistence at the end. #[derive(Default, Clone)] struct Accum { @@ -488,6 +522,18 @@ pub(crate) async fn session_chat( Ok(v) => v, Err(e) => return e.into_response(), }; + // Curated MCP surface from the global catalog + this session's allowlist. + // Built once, synchronously, and shared by the prompt (context sections) and + // the agent declarations; `schedule_prewarm` rebuilds it identically so the + // KV prefix stays byte-stable. No network here — discovery was persisted by + // the picker. + let connectors = match with_store(&st, |s| s.mcp_connectors()).await { + Ok(v) => v, + Err(e) => return e.into_response(), + }; + let (mcp_decls, mcp_sections) = mcp_surface(&connectors, &sess.settings.mcp_enabled); + let mut all_sections = sections.clone(); + all_sections.extend(mcp_sections); let notepad = match with_store(&st, { let id = id.clone(); move |s| s.notepad(&id) @@ -522,7 +568,7 @@ pub(crate) async fn session_chat( &images, Ambient { user_name: &user_name, - sections: §ions, + sections: &all_sections, notepad: ¬epad, }, ); @@ -552,7 +598,11 @@ pub(crate) async fn session_chat( // Agent mode: drive the model↔shell_exec loop, streaming progress events. if body.agent { - req.tools = Some(agent::agent_tools()); + let mut tools = agent::agent_tools(); + if let Some(arr) = tools.as_array_mut() { + arr.extend(mcp_decls); + } + req.tools = Some(tools); req.tool_choice = Some(serde_json::json!("auto")); let (tx, rx) = tokio::sync::mpsc::unbounded_channel::(); let svc = st.service.clone(); @@ -825,6 +875,7 @@ fn schedule_prewarm( let history = store.message_window(&sid_load, ws).ok()?.0; let sections = store.context_sections().ok()?; let notepad = store.notepad(&sid_load).ok()?; + let connectors = store.mcp_connectors().ok()?; let user_name = store .get_defaults() .ok()? @@ -832,12 +883,12 @@ fn schedule_prewarm( .map(|n| n.trim().to_string()) .filter(|n| !n.is_empty()) .unwrap_or_else(|| "User".to_string()); - Some((sess, ws, history, sections, notepad, user_name)) + Some((sess, ws, history, sections, notepad, user_name, connectors)) }) .await .ok() .flatten(); - let Some((sess, ws, history, sections, notepad, user_name)) = loaded else { + let Some((sess, ws, history, sections, notepad, user_name, connectors)) = loaded else { return; }; let sel = window::select(&history, ws); @@ -859,11 +910,16 @@ fn schedule_prewarm( if !rotation_pending && !notepad_dirty { return; } + // Rebuild the SAME curated MCP surface the real turn uses (persisted + // catalog + session allowlist), so the pre-warmed prefix is byte-identical. + let (mcp_decls, mcp_sections) = mcp_surface(&connectors, &sess.settings.mcp_enabled); + let mut all_sections = sections.clone(); + all_sections.extend(mcp_sections); let prefix = context::compose_prefix( &sess, &history[sel.start..], &user_name, - §ions, + &all_sections, ¬epad, ); let mut req = ChatRequest { @@ -872,7 +928,11 @@ fn schedule_prewarm( ..Default::default() }; if agent_mode { - req.tools = Some(agent::agent_tools()); + let mut tools = agent::agent_tools(); + if let Some(arr) = tools.as_array_mut() { + arr.extend(mcp_decls); + } + req.tools = Some(tools); req.tool_choice = Some(serde_json::json!("auto")); } // Re-check idle right before warming: a real turn may have started while we diff --git a/src/lib.rs b/src/lib.rs index 01a002c..9109593 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -16,6 +16,7 @@ pub mod context; pub mod engine; pub mod i18n; pub mod inkling; +pub mod mcp; pub mod name; pub mod render; pub mod store; diff --git a/src/mcp/client.rs b/src/mcp/client.rs new file mode 100644 index 0000000..e773c09 --- /dev/null +++ b/src/mcp/client.rs @@ -0,0 +1,111 @@ +//! The async MCP client: owns one rmcp connection to an external server over +//! streamable-HTTP, with the Bearer token taken from the local DB catalog. +//! Discovery (`tools/list`) and execution (`tools/call`) are exposed; the pure +//! surface layer in [`super`] translates/filters/maps around them. +//! +//! Transport notes (rmcp v3): the default reqwest backend follows same-origin +//! 307/308 redirects (up to 10 hops) but refuses 301/302/303 and cross-origin +//! redirects, so a connector behind a rewriting proxy must be pointed at its +//! final URL. `auth_header` takes the token WITHOUT the `Bearer ` prefix. + +use rmcp::model::{ + CallToolRequestParams, CallToolResult, ClientCapabilities, ClientConfig, Implementation, + ProtocolVersion, Tool, +}; +use rmcp::service::RunningService; +use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig; +use rmcp::transport::StreamableHttpClientTransport; +use rmcp::{ClientLifecycleMode, ClientServiceExt, RoleClient}; +use serde_json::Value as Json; + +use super::ConnectorSpec; + +/// Strip an optional `Bearer ` prefix so the value can be handed to rmcp's +/// `auth_header` (which adds the prefix itself). Case-insensitive, trimmed. +fn strip_bearer(token: &str) -> String { + let t = token.trim(); + if t.len() >= 7 && t[..7].eq_ignore_ascii_case("bearer ") { + t[7..].trim().to_string() + } else { + t.to_string() + } +} + +/// One live connection to an external MCP server. +pub struct McpClient { + running: RunningService, +} + +impl McpClient { + /// Connect over streamable-HTTP. `token` is the Bearer value (with or without + /// the `Bearer ` prefix); an empty token connects anonymously. Negotiates the + /// protocol version automatically, falling back to the legacy `initialize` + /// handshake for older servers (the team's connectors). + pub async fn connect(spec: &ConnectorSpec, token: &str) -> Result { + let mut cfg = StreamableHttpClientTransportConfig::with_uri(spec.url.as_str()); + let token = strip_bearer(token); + if !token.is_empty() { + cfg = cfg.auth_header(token); + } + let transport = StreamableHttpClientTransport::from_config(cfg); + // The team's connectors (e.g. gm-email) are initialize/session-based: + // they answer `initialize` and negotiate down to their newest supported + // revision, but their modern `server/discover` + per-request `_meta` + // path then rejects `tools/list` (-32022 "version not supported" while + // listing that same version as supported). So drive the legacy + // `initialize` handshake at the newest revision that still has one and + // let the server pick the version it actually speaks. + let info = ClientConfig::new( + ClientCapabilities::default(), + Implementation::new("strata-ctl", env!("CARGO_PKG_VERSION")), + ) + .with_protocol_version(ProtocolVersion::LATEST_WITH_INITIALIZE); + let running = info + .serve_with_lifecycle(transport, ClientLifecycleMode::Initialize) + .await + .map_err(|e| format!("MCP connect to '{}' failed: {e}", spec.name))?; + Ok(Self { running }) + } + + /// Discover every tool the server exposes (follows pagination). The caller + /// filters this down to the session's allowlist before declaring anything. + pub async fn list_tools(&self) -> Result, String> { + self.running + .list_all_tools() + .await + .map_err(|e| format!("tools/list failed: {e}")) + } + + /// Call one tool by its ORIGINAL (server-side) name with JSON arguments. + pub async fn call_tool(&self, tool: &str, arguments: Json) -> Result { + let args = arguments.as_object().cloned().unwrap_or_default(); + let params = CallToolRequestParams::new(tool.to_string()).with_arguments(args); + self.running + .call_tool(params) + .await + .map_err(|e| format!("tools/call '{tool}' failed: {e}")) + } + + /// Close the connection (cancels the rmcp service and its transport). + pub async fn close(self) -> Result<(), String> { + self.running + .cancel() + .await + .map_err(|e| format!("MCP close failed: {e}")) + .map(|_| ()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn strip_bearer_handles_prefix_and_case() { + assert_eq!(strip_bearer("abc123"), "abc123"); + assert_eq!(strip_bearer("Bearer abc123"), "abc123"); + assert_eq!(strip_bearer("bearer abc123"), "abc123"); + assert_eq!(strip_bearer(" Bearer abc123 "), "abc123"); + assert_eq!(strip_bearer(""), ""); + } +} diff --git a/src/mcp/mod.rs b/src/mcp/mod.rs new file mode 100644 index 0000000..a05d3b6 --- /dev/null +++ b/src/mcp/mod.rs @@ -0,0 +1,319 @@ +//! MCP client integration: connect the agent to external Model Context Protocol +//! servers (the team's Google-services connectors) over streamable-HTTP. +//! +//! Design (ratified): connectors stay whole and shared; strata-ctl curates the +//! surface CLIENT-SIDE. `tools/list` discovers everything, but only the tools on +//! a session's per-tool allowlist are declared to the model, namespaced +//! `mcp__{connector}__{tool}` so routing is unambiguous and collisions with the +//! built-in tools (`shell_exec`/`notepad`/`share_file`) are impossible. The Bearer +//! token is stored in the local database catalog (no env vars / files), entered +//! from the GUI; it is never echoed into chat. +//! +//! Split into a pure surface layer (namespacing, declaration translation, +//! allowlist filtering, result mapping — unit-testable without a server) and an +//! async client ([`client::McpClient`]) owning the rmcp connection. Wiring into +//! the agent loop comes after the core is proven against a real connector. + +pub mod client; + +use rmcp::model::{CallToolResult, ContentBlock, Tool}; +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value as Json}; + +/// Prefix marking a tool as MCP-provided (vs the built-in agent tools). +pub const MCP_PREFIX: &str = "mcp__"; +/// Separator between connector and tool inside a namespaced name. +pub const MCP_SEP: &str = "__"; + +/// Connection parameters for one external MCP server, including the Bearer +/// token (persisted in the local DB catalog, entered from the GUI). +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ConnectorSpec { + /// Stable connector id, used in the namespaced tool name. Sanitized to + /// `[a-z0-9_]` with no consecutive underscores so parsing is unambiguous. + pub name: String, + /// Streamable-HTTP endpoint URL (e.g. `http://192.168.50.117:8080/` or + /// `https://mcp1.uncino.eu`). Internally the LAN IP+port is used because the + /// hostname hairpin/loopback is unsolved. + pub url: String, + /// Bearer token (with or without the `Bearer ` prefix; the client strips it). + pub token: String, +} + +/// Sanitize a connector id into a namespace-safe token: lowercase, any char +/// outside `[a-z0-9]` becomes `_`, runs of `_` collapse, leading/trailing `_` +/// trimmed. Guarantees no `__` inside, so `mcp__{connector}__{tool}` parses +/// unambiguously even when the tool name itself contains `__`. +pub fn sanitize_connector(name: &str) -> String { + let mut out = String::new(); + let mut prev_us = false; + for c in name.chars() { + let lc = c.to_ascii_lowercase(); + if lc.is_ascii_alphanumeric() { + out.push(lc); + prev_us = false; + } else if !prev_us { + out.push('_'); + prev_us = true; + } + } + out.trim_matches('_').to_string() +} + +/// The namespaced tool name the model sees and calls. +pub fn namespaced(connector: &str, tool: &str) -> String { + format!( + "{MCP_PREFIX}{}{MCP_SEP}{tool}", + sanitize_connector(connector) + ) +} + +/// Whether a tool name is an MCP-provided one (routes to the MCP client). +pub fn is_mcp_tool(name: &str) -> bool { + name.starts_with(MCP_PREFIX) +} + +/// Parse a namespaced name back into `(connector, original_tool)`. The connector +/// is the sanitized segment up to the first `__`; the tool is the remainder +/// (which may itself contain `__`). `None` for non-MCP or malformed names. +pub fn parse_namespaced(name: &str) -> Option<(String, String)> { + let rest = name.strip_prefix(MCP_PREFIX)?; + let (connector, tool) = rest.split_once(MCP_SEP)?; + if connector.is_empty() || tool.is_empty() { + return None; + } + Some((connector.to_string(), tool.to_string())) +} + +/// Translate an MCP tool into the OpenAI-style function declaration the agent +/// loop uses, namespaced under the connector. The server's `inputSchema` becomes +/// the function `parameters` verbatim (it is already a JSON Schema object). +pub fn translate_tool(connector: &str, tool: &Tool) -> Json { + json!({ + "type": "function", + "function": { + "name": namespaced(connector, tool.name.as_ref()), + "description": tool.description.as_deref().unwrap_or(""), + "parameters": tool.schema_as_json_value(), + } + }) +} + +/// Filter discovered tools to those whose ORIGINAL name is on the allowlist. +/// An empty allowlist declares nothing (opt-in: a connector enabled with no +/// tools selected contributes no surface). Order follows the server's list. +pub fn filter_allowed<'a>(tools: &'a [Tool], allow: &[String]) -> Vec<&'a Tool> { + tools + .iter() + .filter(|t| allow.iter().any(|a| a.as_str() == t.name.as_ref())) + .collect() +} + +/// Whether a tool mutates external state — for the GUI "write" badge and for +/// read-only presets. Uses the server's annotations as HINTS only: a tool is +/// treated as a write unless it explicitly declares `readOnlyHint = true`. +/// Untrusted servers' hints are NOT a security boundary; the allowlist is. +pub fn is_write_tool(tool: &Tool) -> bool { + match &tool.annotations { + Some(a) => !a.read_only_hint.unwrap_or(false), + None => true, + } +} + +/// Map an MCP `CallToolResult` to the text the model reads as the tool result. +/// Text blocks are joined; `structuredContent` is used when there is no text; +/// non-text blocks become bounded placeholders (no base64 dumps into context). +/// A tool-level error (`isError`) is prefixed so the model sees the failure. +pub fn result_to_text(result: &CallToolResult) -> String { + let mut parts: Vec = Vec::new(); + for block in &result.content { + match block { + ContentBlock::Text(t) => parts.push(t.text.clone()), + ContentBlock::Image(_) => parts.push("[image content omitted]".into()), + ContentBlock::Audio(_) => parts.push("[audio content omitted]".into()), + ContentBlock::ResourceLink(r) => parts.push(format!("[resource link: {}]", r.uri)), + ContentBlock::Resource(_) => parts.push("[embedded resource omitted]".into()), + _ => parts.push("[non-text content omitted]".into()), + } + } + if parts.is_empty() { + if let Some(sc) = &result.structured_content { + parts.push(sc.to_string()); + } + } + let body = if parts.is_empty() { + "(no content)".to_string() + } else { + parts.join("\n") + }; + if result.is_error == Some(true) { + format!("error: {body}") + } else { + body + } +} + +/// The curated MCP surface for one connector, built synchronously from the +/// persisted discovery (`tools_json`, a JSON array of rmcp `Tool`) intersected +/// with the session allowlist: the OpenAI-style declarations to append to the +/// agent's tools, plus a concise `` context body. Deriving only from +/// stored data means the real turn and the cache pre-warm produce a byte-identical +/// prefix (no network on the generation path). Empty/invalid discovery or an empty +/// allowlist yields no surface — MCP is strictly opt-in per session. +pub struct Surface { + pub declarations: Vec, + pub context: Option, +} + +pub fn surface(connector: &str, tools_json: &str, allow: &[String]) -> Surface { + let tools: Vec = serde_json::from_str(tools_json).unwrap_or_default(); + let allowed = filter_allowed(&tools, allow); + if allowed.is_empty() { + return Surface { + declarations: Vec::new(), + context: None, + }; + } + let declarations = allowed + .iter() + .map(|t| translate_tool(connector, t)) + .collect(); + let names = allowed + .iter() + .map(|t| format!("- {}", namespaced(connector, t.name.as_ref()))) + .collect::>() + .join("\n"); + let context = format!( + "Connettore MCP esterno \"{connector}\": questi strumenti agiscono su servizi \ + esterni con effetti reali, non sull'host locale. Strumenti abilitati in questa \ + sessione:\n{names}\nUsa solo questi nomi namespaced e attieniti alle dichiarazioni \ + dei tool per gli argomenti. Gli strumenti di scrittura modificano stato esterno reale." + ); + Surface { + declarations, + context: Some(context), + } +} + +#[cfg(test)] +mod tests { + use super::*; + use rmcp::model::ToolAnnotations; + + fn tool(name: &str, desc: &str, read_only: Option) -> Tool { + let schema = json!({"type":"object","properties":{"q":{"type":"string"}},"required":["q"]}); + let mut t = Tool::new( + name.to_string(), + desc.to_string(), + schema.as_object().unwrap().clone(), + ); + if let Some(ro) = read_only { + t = t.with_annotations(ToolAnnotations::new().read_only(ro)); + } + t + } + + #[test] + fn sanitize_collapses_and_lowercases() { + assert_eq!(sanitize_connector("GMail"), "gmail"); + assert_eq!(sanitize_connector("GM-GWS"), "gm_gws"); + assert_eq!(sanitize_connector("a__b--c"), "a_b_c"); + assert_eq!(sanitize_connector("__x__"), "x"); + assert_eq!(sanitize_connector("!!!"), ""); + } + + #[test] + fn namespaced_round_trips_even_with_underscores_in_tool() { + let n = namespaced("GM-GWS", "drive__files_list"); + assert_eq!(n, "mcp__gm_gws__drive__files_list"); + assert!(is_mcp_tool(&n)); + assert_eq!( + parse_namespaced(&n), + Some(("gm_gws".into(), "drive__files_list".into())) + ); + } + + #[test] + fn parse_rejects_non_mcp_and_malformed() { + assert_eq!(parse_namespaced("shell_exec"), None); + assert_eq!(parse_namespaced("mcp__gmail"), None); + assert_eq!(parse_namespaced("mcp____tool"), None); + assert_eq!(parse_namespaced("mcp__gmail__"), None); + assert!(!is_mcp_tool("notepad")); + } + + #[test] + fn translate_matches_agent_declaration_shape() { + let t = tool("search_messages", "Search Gmail.", Some(true)); + let d = translate_tool("gmail", &t); + assert_eq!(d["type"], "function"); + assert_eq!(d["function"]["name"], "mcp__gmail__search_messages"); + assert_eq!(d["function"]["description"], "Search Gmail."); + assert_eq!(d["function"]["parameters"]["type"], "object"); + assert_eq!(d["function"]["parameters"]["required"][0], "q"); + } + + #[test] + fn filter_keeps_only_allowlisted_in_server_order() { + let tools = vec![ + tool("a", "", None), + tool("b", "", None), + tool("c", "", None), + ]; + let allow = vec!["c".to_string(), "a".to_string()]; + let kept: Vec<&str> = filter_allowed(&tools, &allow) + .iter() + .map(|t| t.name.as_ref()) + .collect(); + assert_eq!(kept, vec!["a", "c"]); + assert!(filter_allowed(&tools, &[]).is_empty()); + } + + #[test] + fn write_hint_defaults_conservative() { + assert!(!is_write_tool(&tool("r", "", Some(true)))); + assert!(is_write_tool(&tool("w", "", Some(false)))); + assert!(is_write_tool(&tool("u", "", None))); + } + + #[test] + fn result_text_joins_blocks_and_flags_errors() { + let ok = CallToolResult::success(vec![ + ContentBlock::text("hello"), + ContentBlock::text("world"), + ]); + assert_eq!(result_to_text(&ok), "hello\nworld"); + + let err = CallToolResult::error(vec![ContentBlock::text("boom")]); + assert_eq!(result_to_text(&err), "error: boom"); + + let structured = CallToolResult::structured(json!({"a":1})); + assert!(result_to_text(&structured).contains("\"a\"")); + + let img = CallToolResult::success(vec![ContentBlock::image("base64", "image/png")]); + assert_eq!(result_to_text(&img), "[image content omitted]"); + + let empty = CallToolResult::success(vec![]); + assert_eq!(result_to_text(&empty), "(no content)"); + } + + #[test] + fn surface_builds_declarations_and_context_from_allowlist() { + let tools = vec![ + tool("search", "Search Gmail.", Some(true)), + tool("send", "Send mail.", Some(false)), + ]; + let json = serde_json::to_string(&tools).unwrap(); + let allow = vec!["search".to_string()]; + let s = surface("gmail", &json, &allow); + assert_eq!(s.declarations.len(), 1); + assert_eq!(s.declarations[0]["function"]["name"], "mcp__gmail__search"); + let ctx = s.context.unwrap(); + assert!(ctx.contains("mcp__gmail__search")); + assert!(!ctx.contains("mcp__gmail__send")); + // Opt-in: empty allowlist, or empty/invalid discovery, yields no surface. + assert!(surface("gmail", &json, &[]).declarations.is_empty()); + assert!(surface("gmail", "", &allow).context.is_none()); + assert!(surface("gmail", "not-json", &allow).declarations.is_empty()); + } +} diff --git a/src/store.rs b/src/store.rs index a73825d..2f34abb 100644 --- a/src/store.rs +++ b/src/store.rs @@ -8,6 +8,7 @@ //! Implementations are synchronous and `Send + Sync`; async handlers call them //! through `spawn_blocking` so DB work never blocks the tokio runtime. +use std::collections::BTreeMap; use std::path::Path; use std::sync::atomic::{AtomicU64, Ordering}; use std::sync::Mutex; @@ -53,6 +54,12 @@ pub struct SessionSettings { pub max_tokens: Option, #[serde(default)] pub seed: Option, + /// Per-session MCP opt-in: connector name -> the explicit list of enabled + /// tool NAMES (the allowlist). Empty/absent = no MCP surface for this + /// session. The connector catalog (url/token) is global; only the + /// curated tool selection lives here, copy-on-create like other settings. + #[serde(default)] + pub mcp_enabled: BTreeMap>, } impl SessionSettings { @@ -73,6 +80,11 @@ impl SessionSettings { presence_penalty: self.presence_penalty.or(base.presence_penalty), max_tokens: self.max_tokens.or(base.max_tokens), seed: self.seed.or(base.seed), + mcp_enabled: if self.mcp_enabled.is_empty() { + base.mcp_enabled.clone() + } else { + self.mcp_enabled.clone() + }, } } } @@ -198,6 +210,32 @@ pub struct NotepadEntry { pub updated_at: i64, } +/// One external MCP server in the GLOBAL connector catalog (shared across +/// sessions). Connection parameters, including the Bearer `token`, live in the +/// database like all other persistent state (no env vars / files: that would +/// break cloud deployments). Which tools a session actually exposes is curated +/// separately in `SessionSettings.mcp_enabled`. +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct McpConnector { + /// Stable connector id (namespace segment in `mcp__{name}__{tool}`). + pub name: String, + /// Streamable-HTTP endpoint URL. + pub url: String, + /// Bearer token for the connector (stored in the local DB, never in chat). + pub token: String, + /// Persisted discovery: the server's tools as a JSON array (rmcp `Tool`), + /// refreshed by the picker's live `tools/list`. The agent builds its curated + /// surface from this synchronously, so the real turn and the cache pre-warm + /// share a byte-identical prefix with no network on the generation path. + /// Internal only (not serialized to the GUI catalog); None until discovered. + #[serde(default, skip_serializing)] + pub tools_json: Option, + #[serde(default)] + pub created_at: i64, + #[serde(default)] + pub updated_at: i64, +} + /// Bootstrap templates for the static context sections (seeded once into SQLite; /// the DB rows are the source of truth afterwards). const SYSTEM_PROMPT_SECTION: &str = "{identity}{speaker_note}\n{session_prompt}"; @@ -249,6 +287,15 @@ pub trait Store: Send + Sync { fn clear_notepad(&self, session_id: &str) -> Result<()>; fn save_upload(&self, meta: &UploadMeta) -> Result<()>; fn get_upload(&self, id: &str) -> Result>; + /// The global MCP connector catalog, ordered by name. + fn mcp_connectors(&self) -> Result>; + /// Create or update (upsert by name) a connector's connection parameters. + fn upsert_mcp_connector(&self, connector: &McpConnector) -> Result<()>; + /// Remove a connector from the catalog; returns whether it existed. + fn delete_mcp_connector(&self, name: &str) -> Result; + /// Persist the discovered tool surface (JSON array of rmcp `Tool`) for a + /// connector, refreshed by live discovery. No-op if the connector is absent. + fn set_mcp_tools(&self, name: &str, tools_json: &str) -> Result<()>; } fn now_secs() -> i64 { @@ -320,6 +367,14 @@ CREATE TABLE IF NOT EXISTS notepad_entries ( updated_at INTEGER NOT NULL, PRIMARY KEY (session_id, key) ); +CREATE TABLE IF NOT EXISTS mcp_connectors ( + name TEXT PRIMARY KEY, + url TEXT NOT NULL, + token TEXT NOT NULL, + tools_json TEXT, + created_at INTEGER NOT NULL, + updated_at INTEGER NOT NULL +); "; /// SQLite-backed store (bundled SQLite, compiled into the binary). WAL mode for @@ -403,6 +458,17 @@ fn migrate(conn: &Connection) -> Result<()> { "ALTER TABLE sessions ADD COLUMN window_start INTEGER NOT NULL DEFAULT 0;", )?; } + // The MCP catalog originally stored an env-var NAME (token_env); the token + // now lives directly in the DB. Rename the column in place, preserving rows. + if has_col("mcp_connectors", "token_env")? && !has_col("mcp_connectors", "token")? { + conn.execute_batch("ALTER TABLE mcp_connectors RENAME COLUMN token_env TO token;")?; + } + // Persisted tool discovery (the agent's curated surface is built from this). + // Guard on the table existing: very old databases (and the migration unit + // test) predate mcp_connectors entirely; SCHEMA creates it with tools_json. + if has_col("mcp_connectors", "name")? && !has_col("mcp_connectors", "tools_json")? { + conn.execute_batch("ALTER TABLE mcp_connectors ADD COLUMN tools_json TEXT;")?; + } Ok(()) } @@ -858,6 +924,52 @@ impl Store for SqliteStore { })?; Ok(rows.next().transpose()?) } + + fn mcp_connectors(&self) -> Result> { + let conn = self.lock(); + let mut stmt = conn.prepare( + "SELECT name, url, token, tools_json, created_at, updated_at FROM mcp_connectors ORDER BY name ASC", + )?; + let rows = stmt.query_map([], |r| { + Ok(McpConnector { + name: r.get(0)?, + url: r.get(1)?, + token: r.get(2)?, + tools_json: r.get(3)?, + created_at: r.get(4)?, + updated_at: r.get(5)?, + }) + })?; + Ok(rows.collect::>>()?) + } + + fn upsert_mcp_connector(&self, connector: &McpConnector) -> Result<()> { + let now = now_secs(); + let conn = self.lock(); + // Preserve the original created_at on update; set it on first insert. + conn.execute( + "INSERT INTO mcp_connectors (name, url, token, created_at, updated_at) + VALUES (?1, ?2, ?3, ?4, ?4) + ON CONFLICT(name) DO UPDATE SET url = ?2, token = ?3, updated_at = ?4", + params![connector.name, connector.url, connector.token, now], + )?; + Ok(()) + } + + fn delete_mcp_connector(&self, name: &str) -> Result { + let conn = self.lock(); + let n = conn.execute("DELETE FROM mcp_connectors WHERE name = ?1", params![name])?; + Ok(n > 0) + } + + fn set_mcp_tools(&self, name: &str, tools_json: &str) -> Result<()> { + let conn = self.lock(); + conn.execute( + "UPDATE mcp_connectors SET tools_json = ?2, updated_at = ?3 WHERE name = ?1", + params![name, tools_json, now_secs()], + )?; + Ok(()) + } } #[cfg(test)] @@ -935,6 +1047,70 @@ mod tests { assert_eq!(s.list_sessions().unwrap().len(), 0); } + #[test] + fn mcp_connector_catalog_and_session_allowlist() { + let s = store(); + assert!(s.mcp_connectors().unwrap().is_empty()); + let c = McpConnector { + name: "gmail".into(), + url: "http://192.168.50.117:8080/".into(), + token: "test-token-value".into(), + tools_json: None, + created_at: 0, + updated_at: 0, + }; + s.upsert_mcp_connector(&c).unwrap(); + // Upsert updates url/token, keeps a single row, stamps created_at. + let c2 = McpConnector { + url: "https://mcp1.uncino.eu".into(), + ..c.clone() + }; + s.upsert_mcp_connector(&c2).unwrap(); + let list = s.mcp_connectors().unwrap(); + assert_eq!(list.len(), 1); + assert_eq!(list[0].url, "https://mcp1.uncino.eu"); + assert_eq!(list[0].token, "test-token-value"); + assert!(list[0].created_at > 0); + + // Persisted discovery round-trips and survives a url/token upsert. + assert!(list[0].tools_json.is_none()); + s.set_mcp_tools("gmail", "[{\"name\":\"gmail_search\"}]") + .unwrap(); + assert_eq!( + s.mcp_connectors().unwrap()[0].tools_json.as_deref(), + Some("[{\"name\":\"gmail_search\"}]") + ); + s.upsert_mcp_connector(&c2).unwrap(); + assert_eq!( + s.mcp_connectors().unwrap()[0].tools_json.as_deref(), + Some("[{\"name\":\"gmail_search\"}]"), + "a url/token upsert must not clobber the persisted discovery" + ); + + // The per-session allowlist round-trips through settings_json. + let mut settings = SessionSettings::default(); + settings.mcp_enabled.insert( + "gmail".into(), + vec!["search_messages".into(), "read_message".into()], + ); + let sess = s.create_session("Chat", "m", &settings).unwrap(); + let got = s.get_session(&sess.id).unwrap().unwrap(); + assert_eq!( + got.settings.mcp_enabled.get("gmail").unwrap(), + &vec!["search_messages".to_string(), "read_message".to_string()] + ); + // A session created with default settings has an empty allowlist + // (backward compatible: old settings_json without the field). + let plain = s + .create_session("Plain", "m", &SessionSettings::default()) + .unwrap(); + assert!(plain.settings.mcp_enabled.is_empty()); + + assert!(s.delete_mcp_connector("gmail").unwrap()); + assert!(!s.delete_mcp_connector("gmail").unwrap()); + assert!(s.mcp_connectors().unwrap().is_empty()); + } + #[test] fn stats_breakdown_counts_tools_and_orders_sessions() { let s = store(); @@ -1111,7 +1287,10 @@ mod tests { INSERT INTO sessions VALUES ('s1','t','m','old prompt',0,0); CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id TEXT, role TEXT, content TEXT, reasoning_content TEXT, tool_calls_json TEXT, - prompt_tokens INTEGER, completion_tokens INTEGER, created_at INTEGER);", + prompt_tokens INTEGER, completion_tokens INTEGER, created_at INTEGER); + CREATE TABLE mcp_connectors (name TEXT PRIMARY KEY, url TEXT, token TEXT, + created_at INTEGER, updated_at INTEGER); + INSERT INTO mcp_connectors VALUES ('gmail','http://x/','tok',0,0);", ) .unwrap(); migrate(&conn).unwrap(); @@ -1126,6 +1305,24 @@ mod tests { assert_eq!(has("settings_json"), 1); assert_eq!(has("name_locked"), 1); assert_eq!(has("window_start"), 1); + // The MCP catalog gains tools_json on an old DB that predates it, and the + // existing row is preserved. + let tj: i64 = conn + .prepare( + "SELECT COUNT(*) FROM pragma_table_info('mcp_connectors') WHERE name='tools_json'", + ) + .unwrap() + .query_row([], |r| r.get(0)) + .unwrap(); + assert_eq!(tj, 1); + let tok: String = conn + .query_row( + "SELECT token FROM mcp_connectors WHERE name='gmail'", + [], + |r| r.get(0), + ) + .unwrap(); + assert_eq!(tok, "tok"); // The old system_prompt was backfilled into the settings instance. let sj: String = conn .query_row( diff --git a/tests/api_sessions.rs b/tests/api_sessions.rs index 1c60dfe..87b9123 100644 --- a/tests/api_sessions.rs +++ b/tests/api_sessions.rs @@ -116,6 +116,53 @@ async fn create_session(app: &axum::Router) -> String { v["id"].as_str().unwrap().to_string() } +#[tokio::test] +async fn mcp_connector_crud_and_validation() { + let (app, _store) = build_app().await; + // Empty catalog. + let (st, text) = req(&app, Method::GET, "/api/mcp/connectors", None).await; + assert_eq!(st, StatusCode::OK); + assert_eq!( + serde_json::from_str::(&text) + .unwrap() + .as_array() + .unwrap() + .len(), + 0 + ); + // Upsert; the name is sanitized into a namespace-safe id ("GMail" -> "gmail"). + let (st, _) = req( + &app, + Method::PUT, + "/api/mcp/connectors/GMail", + Some(serde_json::json!({"url":"http://192.168.50.117:8080/","token":"test-token-value"})), + ) + .await; + assert_eq!(st, StatusCode::OK); + let (_, text) = req(&app, Method::GET, "/api/mcp/connectors", None).await; + let v: serde_json::Value = serde_json::from_str(&text).unwrap(); + assert_eq!(v[0]["name"], "gmail"); + assert_eq!(v[0]["url"], "http://192.168.50.117:8080/"); + assert_eq!(v[0]["token"], "test-token-value"); + // An empty token is rejected. + let (st, _) = req( + &app, + Method::PUT, + "/api/mcp/connectors/bad", + Some(serde_json::json!({"url":"http://x/","token":""})), + ) + .await; + assert_eq!(st, StatusCode::BAD_REQUEST); + // Discovery for an unknown connector is a 404 before any network attempt. + let (st, _) = req(&app, Method::POST, "/api/mcp/connectors/nope/tools", None).await; + assert_eq!(st, StatusCode::NOT_FOUND); + // Delete, then deleting again is a 404. + let (st, _) = req(&app, Method::DELETE, "/api/mcp/connectors/gmail", None).await; + assert_eq!(st, StatusCode::NO_CONTENT); + let (st, _) = req(&app, Method::DELETE, "/api/mcp/connectors/gmail", None).await; + assert_eq!(st, StatusCode::NOT_FOUND); +} + #[tokio::test] async fn session_holds_context_and_persists_usage() { let (app, _store) = build_app().await; diff --git a/web/assets/app.css b/web/assets/app.css index 4d0c8f9..c6b31e9 100644 --- a/web/assets/app.css +++ b/web/assets/app.css @@ -307,7 +307,7 @@ details.thinking .reasoning { .queue-chip button:hover { color: var(--danger); } /* ---- Stats modal ---- */ -#stats-modal, #dialog, #settings-modal, #notepad-modal { +#stats-modal, #dialog, #settings-modal, #notepad-modal, #mcp-picker-modal { position: fixed; inset: 0; z-index: 40; background: rgba(0,0,0,0.6); display: flex; align-items: center; justify-content: center; padding: 20px; @@ -317,6 +317,8 @@ details.thinking .reasoning { padding: 20px; max-width: 420px; width: 100%; } .modal-card h2 { margin: 0 0 12px; font-size: 1.1rem; } +/* The MCP tool picker lists many tools with descriptions: give it room to scroll. */ +#mcp-picker-modal .modal-card { width: min(560px, 100%); max-width: 560px; max-height: 85dvh; overflow-y: auto; } /* ---- Stats dashboard ---- */ .stats-card { @@ -454,4 +456,37 @@ details.thinking .reasoning { background: var(--accent); } #splitter:focus-visible { outline: none; } +} + +/* ---- MCP connectors / tool picker (settings) ---- */ +.mcp-block { margin-top: 16px; padding-top: 12px; border-top: 1px solid var(--border); } +.mcp-block h3 { margin: 0 0 4px; font-size: 0.95rem; } +.mcp-list { display: flex; flex-direction: column; gap: 8px; margin: 8px 0; } +.mcp-row { + display: flex; align-items: center; justify-content: space-between; gap: 8px; + padding: 8px 10px; background: var(--panel-2); border: 1px solid var(--border); border-radius: 8px; +} +.mcp-row-info { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.mcp-name { font-weight: 600; } +.mcp-url, .mcp-token { font-size: 0.75rem; color: var(--muted); overflow-wrap: anywhere; } +.mcp-count { font-size: 0.75rem; color: var(--muted); } +.mcp-row-actions { display: flex; gap: 6px; flex-shrink: 0; } +.mcp-add { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 8px; } +.mcp-add input { + flex: 1 1 140px; min-width: 0; padding: 8px; font-size: 0.85rem; + background: var(--panel); border: 1px solid var(--border); border-radius: 6px; color: var(--text); +} +.mcp-picker-list { display: flex; flex-direction: column; gap: 6px; max-height: 50vh; overflow-y: auto; margin: 8px 0; } +.mcp-tool { + display: flex; align-items: flex-start; gap: 8px; padding: 8px; + background: var(--panel-2); border: 1px solid var(--border); border-radius: 8px; cursor: pointer; +} +.mcp-tool input { margin-top: 3px; flex-shrink: 0; } +.mcp-tool-text { display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.mcp-tool-name { font-weight: 600; font-size: 0.85rem; display: flex; align-items: center; gap: 6px; flex-wrap: wrap; } +.mcp-tool-desc { font-size: 0.75rem; color: var(--muted); overflow-wrap: anywhere; } +.mcp-write-badge { + font-size: 0.65rem; text-transform: uppercase; letter-spacing: 0.03em; + padding: 1px 6px; border-radius: 999px; color: var(--danger); + border: 1px solid var(--danger); background: transparent; } \ No newline at end of file diff --git a/web/assets/app.js b/web/assets/app.js index aacf4a3..f354f96 100644 --- a/web/assets/app.js +++ b/web/assets/app.js @@ -49,7 +49,11 @@ async function sendJSON(url, method, body) { body: body === undefined ? undefined : JSON.stringify(body), }); if (!r.ok) throw new Error(await r.text()); - return r.status === 204 ? null : r.json(); + // Several endpoints (PUT/PATCH/DELETE) reply 200/204 with an EMPTY body; + // parse only when there is content, else r.json() throws "Unexpected end of + // JSON input". Treat any bodyless success as null. + const text = await r.text(); + return text ? JSON.parse(text) : null; } // ---- DOM builders --------------------------------------------------------- @@ -793,6 +797,9 @@ function fillSettingsForm(data, scope) { $("#set-maxtokens").value = data.max_tokens ?? ""; // Display preference is device-local and scope-independent. $("#set-fontsize").value = String(loadFontSize()); + // MCP: catalog editor in Generali, per-session tool allowlist in Sessione. + $("#set-mcp-catalog").hidden = scope !== "general"; + $("#set-mcp-tools").hidden = scope !== "session"; } function readSettingsForm() { @@ -834,6 +841,11 @@ async function openSettings(scope) { settingsBase = await getJSON("/api/settings/defaults"); } fillSettingsForm(settingsBase, scope); + // Load the global connector catalog for both scopes (Generali edits it; + // Sessione picks tools from it). Best-effort: a failure leaves it empty. + await loadMcpCatalog(); + if (scope === "general") renderMcpCatalog(); + else renderMcpTools(); $("#settings-modal").hidden = false; } @@ -864,6 +876,152 @@ async function saveSettings() { } } +// ---- MCP connectors (settings) ------------------------------------------- +// Two levels: the global catalog (Generali) holds connection params only; the +// per-session allowlist (Sessione) curates which tools the model may use. The +// picker fetches tools/list live and writes the selection into settingsBase, +// persisted by the main Salva (readSettingsForm leaves mcp_enabled untouched). +let mcpCatalog = []; +let mcpPickerConnector = null; + +async function loadMcpCatalog() { + try { mcpCatalog = await getJSON("/api/mcp/connectors"); } + catch { mcpCatalog = []; } +} + +function renderMcpCatalog() { + const list = $("#mcp-connector-list"); + list.textContent = ""; + if (!mcpCatalog.length) { + list.appendChild(el("p", "muted small", t("settings.mcp.empty"))); + return; + } + for (const c of mcpCatalog) { + const row = el("div", "mcp-row"); + const info = el("div", "mcp-row-info"); + info.appendChild(el("span", "mcp-name", c.name)); + info.appendChild(el("span", "mcp-url", c.url)); + info.appendChild(el("span", "mcp-token", "••••••••")); + row.appendChild(info); + const actions = el("div", "mcp-row-actions"); + const edit = el("button", "btn ghost", t("settings.mcp.edit")); + edit.addEventListener("click", () => { + $("#mcp-new-name").value = c.name; + $("#mcp-new-url").value = c.url; + $("#mcp-new-token").value = c.token; + }); + const del = el("button", "btn ghost danger", t("settings.mcp.delete")); + del.addEventListener("click", async () => { + const ok = await showDialog({ + title: t("settings.mcp.delete"), + message: t("settings.mcp.delete.confirm", { name: c.name }), + }); + if (!ok) return; + try { + await sendJSON(`/api/mcp/connectors/${encodeURIComponent(c.name)}`, "DELETE"); + await loadMcpCatalog(); + renderMcpCatalog(); + } catch (e) { + $("#mcp-catalog-hint").textContent = t("settings.mcp.error", { msg: e.message }); + } + }); + actions.appendChild(edit); + actions.appendChild(del); + row.appendChild(actions); + list.appendChild(row); + } +} + +async function addMcpConnector() { + const name = $("#mcp-new-name").value.trim(); + const url = $("#mcp-new-url").value.trim(); + const token = $("#mcp-new-token").value.trim(); + const hint = $("#mcp-catalog-hint"); + if (!name || !url || !token) { + hint.textContent = t("settings.mcp.fields.required"); + return; + } + try { + await sendJSON(`/api/mcp/connectors/${encodeURIComponent(name)}`, "PUT", { url, token }); + $("#mcp-new-name").value = ""; + $("#mcp-new-url").value = ""; + $("#mcp-new-token").value = ""; + hint.textContent = t("settings.mcp.saved"); + await loadMcpCatalog(); + renderMcpCatalog(); + } catch (e) { + hint.textContent = t("settings.mcp.error", { msg: e.message }); + } +} + +function renderMcpTools() { + const list = $("#mcp-tools-list"); + list.textContent = ""; + if (!mcpCatalog.length) { + list.appendChild(el("p", "muted small", t("settings.mcp.noconnectors"))); + return; + } + const enabled = settingsBase.mcp_enabled || {}; + for (const c of mcpCatalog) { + const row = el("div", "mcp-row"); + const info = el("div", "mcp-row-info"); + info.appendChild(el("span", "mcp-name", c.name)); + const n = (enabled[c.name] || []).length; + info.appendChild(el("span", "mcp-count", t("settings.mcp.enabled.count", { n }))); + row.appendChild(info); + const pick = el("button", "btn ghost", t("settings.mcp.choose")); + pick.addEventListener("click", () => openMcpPicker(c)); + row.appendChild(pick); + list.appendChild(row); + } +} + +async function openMcpPicker(connector) { + mcpPickerConnector = connector.name; + $("#mcp-picker-title").textContent = t("settings.mcp.picker.title", { name: connector.name }); + const list = $("#mcp-picker-list"); + const hint = $("#mcp-picker-hint"); + list.textContent = ""; + hint.textContent = t("settings.mcp.loading"); + $("#mcp-picker-modal").hidden = false; + let tools; + try { + tools = await sendJSON(`/api/mcp/connectors/${encodeURIComponent(connector.name)}/tools`, "POST"); + } catch (e) { + hint.textContent = t("settings.mcp.error", { msg: e.message }); + return; + } + hint.textContent = t("settings.mcp.picker.hint", { n: tools.length }); + const enabled = new Set((settingsBase.mcp_enabled || {})[connector.name] || []); + list.textContent = ""; + for (const tool of tools) { + const label = el("label", "mcp-tool"); + const cb = el("input"); + cb.type = "checkbox"; + cb.value = tool.name; + cb.checked = enabled.has(tool.name); + label.appendChild(cb); + const txt = el("span", "mcp-tool-text"); + const head = el("span", "mcp-tool-name", tool.name); + if (tool.write) head.appendChild(el("span", "mcp-write-badge", t("settings.mcp.write"))); + txt.appendChild(head); + if (tool.description) txt.appendChild(el("span", "mcp-tool-desc", tool.description)); + label.appendChild(txt); + list.appendChild(label); + } +} + +function confirmMcpPicker() { + if (!mcpPickerConnector) return; + const checked = [...$("#mcp-picker-list").querySelectorAll("input[type=checkbox]:checked")] + .map((c) => c.value); + settingsBase.mcp_enabled = settingsBase.mcp_enabled || {}; + if (checked.length) settingsBase.mcp_enabled[mcpPickerConnector] = checked; + else delete settingsBase.mcp_enabled[mcpPickerConnector]; + $("#mcp-picker-modal").hidden = true; + renderMcpTools(); +} + // A custom modal dialog (replaces native prompt/confirm: styled, mobile-friendly, // and inspectable by automation). Resolves with the input string (or null on // cancel) when `input` is given, otherwise true/false. @@ -1003,6 +1161,10 @@ function wire() { $("#set-scope-general").addEventListener("click", () => openSettings("general")); $("#set-save").addEventListener("click", saveSettings); $("#set-cancel").addEventListener("click", () => { $("#settings-modal").hidden = true; }); + $("#mcp-add-btn").addEventListener("click", addMcpConnector); + $("#mcp-picker-ok").addEventListener("click", confirmMcpPicker); + $("#mcp-picker-cancel").addEventListener("click", () => { $("#mcp-picker-modal").hidden = true; }); + $("#mcp-picker-modal").addEventListener("click", (e) => { if (e.target.id === "mcp-picker-modal") $("#mcp-picker-modal").hidden = true; }); const input = $("#input"); input.addEventListener("input", () => autoGrow(input)); input.addEventListener("keydown", (e) => { diff --git a/web/assets/locales/en.json b/web/assets/locales/en.json index 44fbd4a..1ed3a30 100644 --- a/web/assets/locales/en.json +++ b/web/assets/locales/en.json @@ -15,6 +15,29 @@ "settings.maxtokens": "Max tokens", "settings.fontsize": "Font size", "settings.fontsize.hint": "This device's preference (does not affect the model).", + "settings.mcp.catalog": "MCP connectors", + "settings.mcp.catalog.hint": "External MCP servers. Paste the connector's Bearer token here: it is stored in the local database, like everything else.", + "settings.mcp.tools": "MCP tools", + "settings.mcp.tools.hint": "Choose which tools of each connector the model may use in this chat. Save to apply.", + "settings.mcp.name.ph": "name (e.g. gmail)", + "settings.mcp.url.ph": "http://host:port/", + "settings.mcp.token.ph": "Bearer token", + "settings.mcp.add": "Add", + "settings.mcp.edit": "Edit", + "settings.mcp.delete": "Delete", + "settings.mcp.delete.confirm": "Remove connector '{name}' from the catalog?", + "settings.mcp.empty": "No connectors. Add one below.", + "settings.mcp.noconnectors": "No connectors in the catalog. Add them in General settings.", + "settings.mcp.choose": "Choose tools", + "settings.mcp.enabled.count": "{n} enabled", + "settings.mcp.write": "write", + "settings.mcp.ok": "OK", + "settings.mcp.loading": "Connecting and listing tools…", + "settings.mcp.picker.title": "Tools of {name}", + "settings.mcp.picker.hint": "{n} tools available. Check the ones to enable for this chat.", + "settings.mcp.fields.required": "Name, URL and token are required.", + "settings.mcp.saved": "Connector saved.", + "settings.mcp.error": "MCP error: {msg}", "settings.save": "Save", "settings.cancel": "Cancel", "settings.hint.session": "Changes apply only to this session.", diff --git a/web/assets/locales/it.json b/web/assets/locales/it.json index be9b83d..5d01763 100644 --- a/web/assets/locales/it.json +++ b/web/assets/locales/it.json @@ -15,6 +15,29 @@ "settings.maxtokens": "Max token", "settings.fontsize": "Dimensione del font", "settings.fontsize.hint": "Preferenza di questo dispositivo (non influisce sul modello).", + "settings.mcp.catalog": "Connettori MCP", + "settings.mcp.catalog.hint": "Server MCP esterni. Incolla qui il token Bearer del connettore: viene salvato nel database locale, come tutto il resto.", + "settings.mcp.tools": "Strumenti MCP", + "settings.mcp.tools.hint": "Scegli quali tool di ogni connettore il modello può usare in questa chat. Salva per applicare.", + "settings.mcp.name.ph": "nome (es. gmail)", + "settings.mcp.url.ph": "http://host:porta/", + "settings.mcp.token.ph": "Token Bearer", + "settings.mcp.add": "Aggiungi", + "settings.mcp.edit": "Modifica", + "settings.mcp.delete": "Elimina", + "settings.mcp.delete.confirm": "Eliminare il connettore '{name}' dal catalogo?", + "settings.mcp.empty": "Nessun connettore. Aggiungine uno qui sotto.", + "settings.mcp.noconnectors": "Nessun connettore nel catalogo. Aggiungili in Impostazioni generali.", + "settings.mcp.choose": "Scegli strumenti", + "settings.mcp.enabled.count": "{n} abilitati", + "settings.mcp.write": "scrittura", + "settings.mcp.ok": "OK", + "settings.mcp.loading": "Connessione e lettura dei tool…", + "settings.mcp.picker.title": "Strumenti di {name}", + "settings.mcp.picker.hint": "{n} tool disponibili. Spunta quelli da abilitare per questa chat.", + "settings.mcp.fields.required": "Nome, URL e token sono obbligatori.", + "settings.mcp.saved": "Connettore salvato.", + "settings.mcp.error": "Errore MCP: {msg}", "settings.save": "Salva", "settings.cancel": "Annulla", "settings.hint.session": "Modifiche valide solo per questa sessione.", diff --git a/web/index.html b/web/index.html index 7fc1431..b99ac93 100644 --- a/web/index.html +++ b/web/index.html @@ -126,6 +126,25 @@

Preferenza di questo dispositivo.

+ + + +
@@ -133,6 +152,19 @@
+ + + \ No newline at end of file