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:
adm committed 2026-11-30 02:29:55 +01:00
1 parent 2f5b263d4e
commit 0d335b808c
18 files changed
+2266 -17

No files matched your search

+148
View File
@@ -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())),
)
}
+1
View File
@@ -7,6 +7,7 @@
pub mod anthropic;
mod files;
pub mod formatter;
mod mcp;
pub mod routes;
pub mod service;
mod sessions;
+7 -1
View File
@@ -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
View File
@@ -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: &sections,
sections: &all_sections,
notepad: &notepad,
},
);
@@ -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,
&sections,
&all_sections,
&notepad,
);
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