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
+106
-1
@@ -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<dyn Store>, 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<McpConnector>, 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<dyn Store> = 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<dyn ShellRunner> = 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<dyn Store> = Arc::new(SqliteStore::open_in_memory().unwrap());
|
||||
|
||||
+148
@@ -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<AppState>,
|
||||
) -> Result<Json<Vec<McpConnector>>, 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<AppState>,
|
||||
Path(name): Path<String>,
|
||||
Json(body): Json<ConnectorBody>,
|
||||
) -> Result<StatusCode, Error> {
|
||||
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<AppState>,
|
||||
Path(name): Path<String>,
|
||||
) -> Result<StatusCode, Error> {
|
||||
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<AppState>,
|
||||
Path(name): Path<String>,
|
||||
) -> Result<Json<Vec<ToolView>>, 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 <MCP_*> 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())),
|
||||
)
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
pub mod anthropic;
|
||||
mod files;
|
||||
pub mod formatter;
|
||||
mod mcp;
|
||||
pub mod routes;
|
||||
pub mod service;
|
||||
mod sessions;
|
||||
|
||||
+7
-1
@@ -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));
|
||||
}
|
||||
|
||||
+67
-7
@@ -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 `<MCP_*>` 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<String, Vec<String>>,
|
||||
) -> (Vec<serde_json::Value>, Vec<ContextSection>) {
|
||||
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::<AgentEvent>();
|
||||
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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<RoleClient, ClientConfig>,
|
||||
}
|
||||
|
||||
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<Self, String> {
|
||||
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<Vec<Tool>, 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<CallToolResult, String> {
|
||||
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(""), "");
|
||||
}
|
||||
}
|
||||
+319
@@ -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<String> = 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 `<MCP_*>` 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<Json>,
|
||||
pub context: Option<String>,
|
||||
}
|
||||
|
||||
pub fn surface(connector: &str, tools_json: &str, allow: &[String]) -> Surface {
|
||||
let tools: Vec<Tool> = 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::<Vec<_>>()
|
||||
.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<bool>) -> 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());
|
||||
}
|
||||
}
|
||||
+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