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());
|
||||
|
||||
Reference in new issue
Block a user