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.
This commit is contained in:
1 parent
2f5b263d4e
commit
0d335b808c
18 files changed
+2266
-17
No files matched your search
+198
-1
@@ -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<u32>,
|
||||
#[serde(default)]
|
||||
pub seed: Option<u64>,
|
||||
/// 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<String, Vec<String>>,
|
||||
}
|
||||
|
||||
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<String>,
|
||||
#[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<Option<UploadMeta>>;
|
||||
/// The global MCP connector catalog, ordered by name.
|
||||
fn mcp_connectors(&self) -> Result<Vec<McpConnector>>;
|
||||
/// 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<bool>;
|
||||
/// 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<Vec<McpConnector>> {
|
||||
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::<rusqlite::Result<Vec<_>>>()?)
|
||||
}
|
||||
|
||||
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<bool> {
|
||||
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(
|
||||
|
||||
Reference in new issue
Block a user