feat(mcp): opt-in plugin tools on external server and built-in AI

This commit is contained in:
Jinpy authored and GitHub committed 2026-09-28 21:34:17 +08:00
1 parent b3bffe8c71
commit f61f64f727
36 files changed
+2181 -81

No files matched your search

+213 -36
View File
@@ -4,9 +4,12 @@
//! and `mcp/call` (execution). This module turns them into agent tools under
//! three host-owned rules:
//!
//! * **Opt-in per plugin.** Only plugins the user enabled for the built-in AI
//! in the Plugin Center contribute tools, so a plugin cannot put its tools —
//! and whatever they read — in front of the model on install alone.
//! * **Detected plugins, revocable.** Every installed, compatible plugin with
//! a backend contributes tools automatically — implementing the optional
//! `mcp/tools` bridge is the author's declaration of intent (a manifest
//! `mcp` contribution with `ai_tools: false` narrows it). The Plugin Center
//! switch still turns a plugin off for good, and the opt-out outlives
//! restarts and plugin updates.
//! * **Open connections only.** Tools run against plugin connections DBX
//! already has open. The host binds the connection: the model picks among
//! the open ones by DBX id, the lifecycle payload (credentials, runtime
@@ -23,7 +26,10 @@
//! Tool definitions are reduced to a JSON-Schema subset every supported
//! provider accepts (OpenAI, Anthropic, and Gemini's OpenAPI-style
//! `parameters`), and exposed as `<plugin>__<tool>` names that satisfy all of
//! their naming rules.
//! their naming rules. The naming, schema-reduction, and listing helpers are
//! shared with the external `dbx` MCP server
//! (`crates/dbx-mcp/src/plugin_tools.rs`) so one plugin tool surfaces under
//! the same exposed name on both automatic surfaces.
use std::collections::{BTreeMap, HashMap, HashSet};
use std::future::Future;
@@ -46,8 +52,10 @@ const DISCOVERY_TIMEOUT: Duration = Duration::from_secs(8);
/// task tools (e.g. SSH `ssh_run_bg`), not in one blocking call.
const CALL_TIMEOUT: Duration = Duration::from_secs(120);
const MAX_OPEN_CONNECTIONS: usize = 8;
const MAX_TOOLS_PER_PLUGIN: usize = 64;
const MAX_TOTAL_TOOLS: usize = 96;
/// Shared with the external `dbx` MCP server so one plugin tool keeps the
/// same bounds on both automatic surfaces.
pub const MAX_TOOLS_PER_PLUGIN: usize = 64;
pub const MAX_TOTAL_TOOLS: usize = 96;
const MAX_DESCRIPTION_CHARS: usize = 1_500;
const MAX_SCHEMA_PROPERTIES: usize = 64;
const MAX_SCHEMA_DEPTH: usize = 6;
@@ -62,7 +70,7 @@ const PLUGIN_PREFIX_MAX_CHARS: usize = 20;
pub const CONNECTION_ARGUMENT: &str = "dbx_connection";
/// Plugin arguments the host fills from the bound connection; the model never
/// supplies them, so it cannot address a connection the user did not open.
const HOST_BOUND_ARGUMENTS: &[&str] = &["connectionId", "connectionName"];
pub const HOST_BOUND_ARGUMENTS: &[&str] = &["connectionId", "connectionName"];
/// An open plugin connection whose tools the agent may call.
#[derive(Debug, Clone)]
@@ -249,6 +257,53 @@ impl PluginToolBinding {
}
}
/// Plugin ids whose sidecar tools the built-in AI agent may use.
///
/// Opt-in only: the Plugin Center list is the single source — a plugin
/// contributes AI tools only after the user enabled it there, so installing
/// alone never puts anything in front of the model. A manifest `mcp`
/// contribution with `ai_tools: false` keeps a plugin off this surface even
/// when opted in, the ids the user explicitly turned off always win, and an
/// opted-in plugin must still be installed, compatible, and backend-capable.
/// If the setting or the plugin registry cannot be read, the surface degrades
/// to empty so a transient failure never widens exposure.
pub async fn effective_ai_tool_plugin_ids(state: &AppState) -> HashSet<String> {
let opted_in: HashSet<String> = match state.storage.load_ai_plugin_tool_plugin_ids().await {
Ok(ids) if !ids.is_empty() => ids.into_iter().collect(),
Ok(_) => return HashSet::new(),
Err(error) => {
log::warn!("[agent][plugin-tools] cannot read AI plugin tool settings: {error}");
return HashSet::new();
}
};
let installed = match state.plugins.list_installed() {
Ok(plugins) => plugins
.iter()
.filter(|plugin| {
plugin.compatibility.compatible
&& plugin.manifest.backend_entrypoint().is_some()
&& !plugin.manifest.ai_tools_excluded()
})
.map(|plugin| plugin.manifest.id.clone())
.collect::<HashSet<_>>(),
Err(error) => {
log::warn!("[agent][plugin-tools] cannot list installed plugins: {error}");
return HashSet::new();
}
};
let disabled: HashSet<String> = state
.storage
.load_ai_plugin_tool_disabled_plugin_ids()
.await
.unwrap_or_else(|error| {
log::warn!("[agent][plugin-tools] cannot read AI plugin opt-outs: {error}");
Vec::new()
})
.into_iter()
.collect();
opted_in.into_iter().filter(|plugin_id| installed.contains(plugin_id) && !disabled.contains(plugin_id)).collect()
}
/// Collects the plugin tools the built-in agent may use right now. Any
/// failure degrades to fewer (or no) plugin tools; it never fails the run.
pub async fn discover_plugin_tools(
@@ -256,14 +311,10 @@ pub async fn discover_plugin_tools(
host_runtime: Option<&tokio::runtime::Handle>,
connection_id: Option<&str>,
) -> PluginToolSet {
let enabled = match state.storage.load_ai_plugin_tool_plugin_ids().await {
Ok(ids) if !ids.is_empty() => ids.into_iter().collect::<HashSet<_>>(),
Ok(_) => return PluginToolSet::default(),
Err(error) => {
log::warn!("[agent][plugin-tools] cannot read AI plugin tool settings: {error}");
return PluginToolSet::default();
}
};
let enabled = effective_ai_tool_plugin_ids(state).await;
if enabled.is_empty() {
return PluginToolSet::default();
}
let plugin_names = match tool_capable_plugins(state, &enabled) {
Ok(names) if !names.is_empty() => names,
Ok(_) => return PluginToolSet::default(),
@@ -398,7 +449,7 @@ pub async fn execute_plugin_tool(
prepared: &PreparedPluginToolCall,
) -> ToolResult {
let outcome = async {
let enabled = state.storage.load_ai_plugin_tool_plugin_ids().await?;
let enabled = effective_ai_tool_plugin_ids(state).await;
if !enabled.contains(&prepared.plugin_id) {
return Err("Built-in AI access to this plugin has been disabled".to_string());
}
@@ -568,15 +619,18 @@ impl<T> Drop for AbortOnDrop<T> {
}
#[derive(Debug, Clone, PartialEq)]
struct RawPluginTool {
name: String,
description: String,
input_schema: Value,
read_only: bool,
pub struct RawPluginTool {
pub name: String,
pub description: String,
pub input_schema: Value,
pub read_only: bool,
/// Raw MCP `annotations` object; the external `dbx` MCP server passes it
/// through on `tools/list`, the AI surface only reads `readOnlyHint`.
pub annotations: Value,
}
/// Parses an `mcp/tools` answer (`{ tools: [...] }` or a bare array).
fn parse_tool_list(value: &Value) -> Vec<RawPluginTool> {
pub fn parse_tool_list(value: &Value) -> Vec<RawPluginTool> {
let tools = value.get("tools").and_then(Value::as_array).or_else(|| value.as_array());
let Some(tools) = tools else {
return Vec::new();
@@ -600,6 +654,7 @@ fn parse_tool_list(value: &Value) -> Vec<RawPluginTool> {
description: tool.get("description").and_then(Value::as_str).unwrap_or_default().trim().to_string(),
input_schema,
read_only: tool.pointer("/annotations/readOnlyHint").and_then(Value::as_bool) == Some(true),
annotations: tool.get("annotations").cloned().unwrap_or_else(|| json!({})),
})
})
.take(MAX_TOOLS_PER_PLUGIN)
@@ -662,14 +717,62 @@ fn tool_description(plugin_name: &str, tool: &RawPluginTool, connections: &[Open
}
/// A short, stable, name-safe prefix per plugin (`io.dbx.ssh` → `ssh`).
/// Plugins that reduce to the same prefix are told apart by a counter, in
/// plugin-id order so the assignment is deterministic.
fn plugin_prefixes<'a>(plugin_ids: impl Iterator<Item = &'a str>) -> HashMap<String, String> {
let mut used = HashSet::new();
///
/// The prefix starts at the id's last segment and **extends leftward only
/// when two installed plugins reduce to the same candidate** (`a.files` →
/// `a_files`, `b.files` → `b_files`), so ordinary ids stay short while
/// same-named plugins remain distinguishable by their own id — not by an
/// install-order counter that would silently reassign names when plugins are
/// uninstalled. Sanitization can still collapse two distinct ids to the same
/// prefix (`a.b-c` vs `a.b_c`); those fall to a counter suffix, assigned in
/// plugin-id order so the result is deterministic for a given installed set.
pub fn plugin_prefixes<'a>(plugin_ids: impl Iterator<Item = &'a str>) -> HashMap<String, String> {
let mut ids = plugin_ids.into_iter().map(str::to_string).collect::<Vec<_>>();
ids.sort();
// Sanitized segments in original id order, without empties.
let segments_of = |id: &str| -> Vec<String> {
let mut segments: Vec<String> =
id.split('.').map(sanitize_identifier).filter(|segment| !segment.is_empty()).collect();
if segments.is_empty() {
segments.push("plugin".to_string());
}
segments
};
let segment_lists: Vec<Vec<String>> = ids.iter().map(|id| segments_of(id)).collect();
// The prefix is the id's LAST `depth` segments in natural order, so the
// extension reads like the id itself (`a.files` → `a_files`).
let joined = |index: usize, depth: usize| -> String {
let list = &segment_lists[index];
let start = list.len().saturating_sub(depth);
list[start..].join("_")
};
// Extend colliding plugins leftward until every prefix is unique. Full
// ids are unique, so the loop terminates; sanitization can still collapse
// distinct ids at full depth, which the counter fallback below resolves.
let mut depths = vec![1usize; ids.len()];
for _ in 0..ids.iter().map(|id| id.split('.').count()).max().unwrap_or(1) {
let candidates: Vec<String> = (0..ids.len()).map(|index| joined(index, depths[index])).collect();
let mut extended = false;
for index in 0..ids.len() {
let collides = candidates.iter().enumerate().any(|(other, candidate)| {
other != index && candidate == &candidates[index] && depths[index] < segment_lists[index].len()
});
if collides {
depths[index] += 1;
extended = true;
}
}
if !extended {
break;
}
}
let mut prefixes = HashMap::new();
for plugin_id in plugin_ids {
let last_segment = plugin_id.rsplit('.').next().unwrap_or(plugin_id);
let mut base = sanitize_identifier(last_segment);
let mut used = HashSet::new();
for (index, plugin_id) in ids.iter().enumerate() {
let mut base = joined(index, depths[index]);
base.truncate(PLUGIN_PREFIX_MAX_CHARS);
let base = base.trim_end_matches('_').to_string();
let base = if base.is_empty() { "plugin".to_string() } else { base };
@@ -679,14 +782,15 @@ fn plugin_prefixes<'a>(plugin_ids: impl Iterator<Item = &'a str>) -> HashMap<Str
candidate = format!("{base}{counter}");
counter += 1;
}
prefixes.insert(plugin_id.to_string(), candidate);
prefixes.insert(plugin_id.clone(), candidate);
}
prefixes
}
/// `<prefix>__<tool>`: starts with a letter, only `[A-Za-z0-9_]`, at most 64
/// characters. Truncated or colliding names get a hash of the original.
fn exposed_tool_name(prefix: &str, tool_name: &str, used: &mut HashSet<String>) -> String {
/// Shared with the external `dbx` MCP server.
pub fn exposed_tool_name(prefix: &str, tool_name: &str, used: &mut HashSet<String>) -> String {
let sanitized = sanitize_identifier(tool_name);
let mut name = format!("{prefix}__{sanitized}");
if name.chars().count() > MAX_EXPOSED_NAME_CHARS || used.contains(&name) {
@@ -771,8 +875,9 @@ fn tool_parameters(input_schema: &Value, connections: &[OpenPluginConnection]) -
/// Reduces a JSON Schema to keywords OpenAI, Anthropic, and Gemini's
/// OpenAPI-style `parameters` all accept. Anything outside the subset is
/// dropped rather than passed through: one unsupported keyword makes a
/// provider reject the whole request, not just this tool.
fn sanitize_schema(schema: &Value, depth: usize) -> Value {
/// provider reject the whole request, not just this tool. Shared with the
/// external `dbx` MCP server.
pub fn sanitize_schema(schema: &Value, depth: usize) -> Value {
let Some(object) = schema.as_object() else {
return json!({ "type": "string" });
};
@@ -947,6 +1052,26 @@ mod tests {
}
}
/// Writes a minimal installable plugin container: one manifest, one
/// backend executable. `contributions` carries extra entries such as the
/// `mcp` surface override.
fn write_fake_plugin(plugins_dir: &std::path::Path, plugin_id: &str, contributions: Value) {
let container = plugins_dir.join(plugin_id);
std::fs::create_dir_all(container.join("bin")).unwrap();
std::fs::write(container.join("bin").join("backend"), b"backend").unwrap();
let manifest = json!({
"manifest_version": 1,
"id": plugin_id,
"name": plugin_id,
"version": "1.0.0",
"publisher": "test",
"engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
"entrypoints": { "backend": { "executable": "bin/backend" } },
"contributions": contributions,
});
std::fs::write(container.join("manifest.json"), serde_json::to_vec(&manifest).unwrap()).unwrap();
}
fn tool_call(name: &str, arguments: Value) -> ToolCall {
ToolCall { id: "call-1".to_string(), name: name.to_string(), arguments, provider_payload: None }
}
@@ -1127,9 +1252,20 @@ mod tests {
}
let prefixes = plugin_prefixes(["a.files", "b.files", "io.dbx.9lives"].into_iter());
assert_eq!(prefixes["a.files"], "files");
assert_eq!(prefixes["b.files"], "files2");
assert_eq!(prefixes["a.files"], "a_files");
assert_eq!(prefixes["b.files"], "b_files");
assert_eq!(prefixes["io.dbx.9lives"], "t9lives");
// Distinct last segments keep the short form.
let prefixes = plugin_prefixes(["io.dbx.ssh", "io.dbx.files"].into_iter());
assert_eq!(prefixes["io.dbx.ssh"], "ssh");
assert_eq!(prefixes["io.dbx.files"], "files");
// Sanitization collapses `a.b-c` and `a.b_c` even at full depth;
// the counter is the deterministic last resort.
let prefixes = plugin_prefixes(["a.b-c", "a.b_c"].into_iter());
assert_eq!(prefixes["a.b-c"], "a_b_c");
assert_eq!(prefixes["a.b_c"], "a_b_c2");
}
#[test]
@@ -1144,11 +1280,52 @@ mod tests {
assert_eq!(structured, "{\"ok\":true}");
}
#[tokio::test]
async fn opt_in_gates_ai_tools_and_opt_outs_win() {
let root = tempfile::tempdir().unwrap();
let storage = crate::persistence::test_storage::open(&root.path().join("dbx.db")).await.unwrap();
let plugins_dir = root.path().join("plugins");
write_fake_plugin(&plugins_dir, "io.test.ssh", serde_json::json!([]));
write_fake_plugin(
&plugins_dir,
"io.test.quiet",
serde_json::json!([{ "type": "mcp", "id": "io.test.quiet.mcp", "ai_tools": false }]),
);
write_fake_plugin(&plugins_dir, "io.test.ui_only", serde_json::json!([]));
// Remove the backend from the UI-only plugin after writing it.
let backend = plugins_dir.join("io.test.ui_only").join("bin").join("backend");
std::fs::remove_file(&backend).unwrap();
let state = Arc::new(AppState::new_with_plugin_dir(storage, plugins_dir));
// Installing alone exposes nothing: the Plugin Center opt-in gates the AI surface.
let ids = effective_ai_tool_plugin_ids(&state).await;
assert!(ids.is_empty(), "nothing is exposed before the user opts in");
// Opting in enables a tool-capable plugin.
state.storage.set_ai_plugin_tool_plugin_enabled("io.test.ssh", true).await.unwrap();
let ids = effective_ai_tool_plugin_ids(&state).await;
assert!(ids.contains("io.test.ssh"), "the opt-in enables the tool-capable plugin");
// The manifest declaration and the backend guard still bind opted-in plugins.
state.storage.set_ai_plugin_tool_plugin_enabled("io.test.quiet", true).await.unwrap();
state.storage.set_ai_plugin_tool_plugin_enabled("io.test.ui_only", true).await.unwrap();
let ids = effective_ai_tool_plugin_ids(&state).await;
assert!(!ids.contains("io.test.quiet"), "ai_tools:false excludes the AI surface even when opted in");
assert!(!ids.contains("io.test.ui_only"), "plugins without a backend stay invisible");
// The Plugin Center opt-out always wins over the opt-in.
state.storage.set_ai_plugin_tool_plugin_enabled("io.test.ssh", false).await.unwrap();
let ids = effective_ai_tool_plugin_ids(&state).await;
assert!(!ids.contains("io.test.ssh"));
}
#[tokio::test]
async fn stale_tool_bindings_cannot_bypass_revoked_ai_access() {
let root = tempfile::tempdir().unwrap();
let storage = crate::persistence::test_storage::open(&root.path().join("dbx.db")).await.unwrap();
let state = Arc::new(AppState::new(storage));
let plugins_dir = root.path().join("plugins");
write_fake_plugin(&plugins_dir, "io.dbx.kafka", serde_json::json!([]));
let state = Arc::new(AppState::new_with_plugin_dir(storage, plugins_dir));
state.storage.set_ai_plugin_tool_plugin_enabled("io.dbx.kafka", true).await.unwrap();
let set = build_tool_set(
&names(),
+40 -3
View File
@@ -60,8 +60,14 @@ const MAX_RETRIES_KEY: &str = "max_retries";
const HISTORY_RETENTION_LIMIT_KEY: &str = "history_retention_limit";
const MCP_HISTORY_RETENTION_LIMIT_KEY: &str = "mcp_history_retention_limit";
const SQL_FILE_UPLOAD_MAX_MB_KEY: &str = "sql_file_upload_max_mb";
/// Plugin ids whose MCP tools the built-in AI agent may call.
/// Plugin ids whose MCP tools the built-in AI agent may call. The opt-in
/// list is the single source: a plugin contributes AI tools only after the
/// user enabled it in the Plugin Center.
const AI_PLUGIN_TOOL_PLUGINS_KEY: &str = "ai_plugin_tool_plugins";
/// Plugin ids the user explicitly turned off in the Plugin Center; they stay
/// excluded even if they reappear on the opt-in list, so a revocation
/// survives restarts and plugin updates.
const AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY: &str = "ai_plugin_tool_disabled_plugins";
/// `{ pluginId: [connectionId, ...] }` — connections a plugin may read through
/// the `host.data:read` Host API. Written only after an explicit user consent.
const PLUGIN_DATA_GRANTS_KEY: &str = "plugin_data_grants";
@@ -4347,9 +4353,19 @@ impl Storage {
Ok(normalized_string_list(settings.get(AI_PLUGIN_TOOL_PLUGINS_KEY)))
}
/// Plugin ids the user explicitly turned off for the built-in AI agent.
/// Only records explicit revocations; combined with the enabled list and
/// the manifest `mcp` declarations it yields the effective AI tool set.
pub async fn load_ai_plugin_tool_disabled_plugin_ids(&self) -> Result<Vec<String>, String> {
let settings = self.load_app_settings_json().await?;
Ok(normalized_string_list(settings.get(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY)))
}
/// Enables or disables built-in AI access to one plugin's tools and returns
/// the updated list. The read-modify-write runs inside one connection
/// closure so concurrent settings saves cannot drop the change.
/// closure so concurrent settings saves cannot drop the change. Disabling
/// also records the opt-out so a detection-enabled plugin (the default)
/// stays off across restarts and plugin updates.
pub async fn set_ai_plugin_tool_plugin_enabled(
&self,
plugin_id: &str,
@@ -4361,8 +4377,19 @@ impl Storage {
let mut plugin_ids = normalized_string_list(settings.get(AI_PLUGIN_TOOL_PLUGINS_KEY));
plugin_ids.retain(|candidate| candidate != &plugin_id);
if enabled {
plugin_ids.push(plugin_id);
plugin_ids.push(plugin_id.clone());
plugin_ids.sort();
// Re-enable after an explicit opt-out of a manifest-declared plugin.
let mut disabled = normalized_string_list(settings.get(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY));
disabled.retain(|candidate| candidate != &plugin_id);
settings.insert(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY.to_string(), serde_json::json!(disabled));
} else {
let mut disabled = normalized_string_list(settings.get(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY));
if !disabled.contains(&plugin_id) {
disabled.push(plugin_id.clone());
disabled.sort();
}
settings.insert(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY.to_string(), serde_json::json!(disabled));
}
settings.insert(AI_PLUGIN_TOOL_PLUGINS_KEY.to_string(), serde_json::json!(plugin_ids));
write_app_settings_map(conn, &settings)?;
@@ -4427,6 +4454,9 @@ impl Storage {
let mut plugin_ids = normalized_string_list(settings.get(AI_PLUGIN_TOOL_PLUGINS_KEY));
plugin_ids.retain(|candidate| candidate != &plugin_id);
settings.insert(AI_PLUGIN_TOOL_PLUGINS_KEY.to_string(), serde_json::json!(plugin_ids));
let mut disabled = normalized_string_list(settings.get(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY));
disabled.retain(|candidate| candidate != &plugin_id);
settings.insert(AI_PLUGIN_TOOL_DISABLED_PLUGINS_KEY.to_string(), serde_json::json!(disabled));
if let Some(serde_json::Value::Object(grants)) = settings.get_mut(PLUGIN_DATA_GRANTS_KEY) {
grants.remove(&plugin_id);
}
@@ -12019,6 +12049,9 @@ mod tests {
assert_eq!(storage.set_plugin_data_grant("io.dbx.chart", "conn-b", false).await.unwrap(), ["conn-a"]);
assert_eq!(storage.set_ai_plugin_tool_plugin_enabled("io.dbx.kafka", false).await.unwrap(), ["io.dbx.ssh"]);
// Disabling records an explicit opt-out (manifest-declared plugins are
// enabled by default, so the opt-out must persist separately).
assert_eq!(storage.load_ai_plugin_tool_disabled_plugin_ids().await.unwrap(), ["io.dbx.kafka"]);
assert!(storage.set_plugin_data_grant("io.dbx.chart", " ", true).await.is_err());
storage.set_ai_plugin_tool_plugin_enabled("io.dbx.chart", true).await.unwrap();
@@ -12026,6 +12059,10 @@ mod tests {
assert_eq!(storage.load_ai_plugin_tool_plugin_ids().await.unwrap(), ["io.dbx.ssh"]);
assert!(storage.load_plugin_data_grants("io.dbx.chart").await.unwrap().is_empty());
assert_eq!(storage.load_plugin_data_grants("io.dbx.other").await.unwrap(), ["conn-a"]);
// Re-enabling clears the recorded opt-out again.
storage.set_ai_plugin_tool_plugin_enabled("io.dbx.kafka", true).await.unwrap();
assert_eq!(storage.load_ai_plugin_tool_plugin_ids().await.unwrap(), ["io.dbx.kafka", "io.dbx.ssh"]);
assert!(storage.load_ai_plugin_tool_disabled_plugin_ids().await.unwrap().is_empty());
}
#[tokio::test]
+2
View File
@@ -24,8 +24,10 @@ path = "src/main.rs"
[dependencies]
async-trait = "0.1"
futures = "0.3"
dbx-core = { path = "../dbx-core", default-features = false }
dirs = "6"
env_logger = "0.11"
log = "0.4"
mysql_async = { version = "0.37", default-features = false, features = ["default-rustls", "client_ed25519", "chrono", "rust_decimal"] }
axum = "0.8"
+97 -1
View File
@@ -424,6 +424,29 @@ pub trait DbxBackend: Send + Sync {
let _ = (connection, database, options);
Err("Documentation snapshots are not supported by this backend.".to_string())
}
/// Tool-capable plugins for the external `dbx` MCP surface, with their
/// discovered `mcp/tools` listings. Author opt-in: installed +
/// compatible + backend entrypoint + a manifest `external_tools: true`
/// declaration. An error means "no plugin tools on this backend" (e.g.
/// the web backend); the server degrades to the static tools.
async fn list_plugin_mcp_tools(&self) -> Result<Vec<crate::plugin_tools::PluginToolProvider>, String> {
let _ = self;
Err("Plugin tools are not supported by this backend.".to_string())
}
/// Calls one plugin MCP tool. `connection_id` (already policy-checked by
/// the server) selects the saved connection whose host-generated
/// lifecycle payload is sent to the plugin; `None` targets
/// connection-less tools.
async fn call_plugin_mcp_tool(
&self,
plugin_id: &str,
tool: &str,
connection_id: Option<&str>,
arguments: &Value,
) -> Result<Value, String> {
let _ = (self, plugin_id, tool, connection_id, arguments);
Err("Plugin tools are not supported by this backend.".to_string())
}
}
pub struct LocalBackend {
@@ -653,6 +676,11 @@ fn plugin_lacks_mcp_surface(err: &str) -> bool {
lower.contains("unknown method") || lower.contains("method not found") || lower.contains("-32601")
}
/// Probe budget for one plugin's `mcp/tools` during external discovery —
/// aligned with the AI surface's discovery timeout so one hung sidecar
/// cannot stall `tools/list` beyond a few seconds.
const PLUGIN_TOOLS_PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(8);
impl LocalBackend {
fn spawn_connection_lifecycle_watcher(
&self,
@@ -812,7 +840,9 @@ impl LocalBackend {
/// Call one plugin MCP tool through the host-managed sidecar session.
/// When a saved connection is supplied, only its host-generated lifecycle
/// payload is sent to the plugin; credentials remain host-managed.
/// payload is sent to the plugin; credentials remain host-managed. The
/// saved config must still belong to the target plugin, so a connection
/// re-bound to another plugin can never leak its lifecycle here.
pub async fn call_plugin_tool(
&self,
plugin_id: &str,
@@ -830,6 +860,9 @@ impl LocalBackend {
.get(connection_id)
.cloned()
.ok_or_else(|| format!("Connection not found: {connection_id}"))?;
if config.plugin_id.as_deref() != Some(plugin_id) {
return Err(format!("Connection \"{connection_id}\" is not bound to plugin \"{plugin_id}\""));
}
let lifecycle = self.state.plugin_host.connection_params_standalone(&config)?;
params["lifecycle"] = lifecycle;
}
@@ -839,6 +872,55 @@ impl LocalBackend {
.await
}
/// Opt-in, parallel `mcp/tools` discovery for the external surface:
/// installed + compatible + backend plugins whose manifest declares
/// `external_tools: true`. A plugin that fails to list skips itself
/// (with a warning) instead of failing the whole `tools/list`.
pub async fn detect_plugin_tool_providers(&self) -> Result<Vec<crate::plugin_tools::PluginToolProvider>, String> {
let plugins = self.state.plugins.list_installed()?;
let candidates: Vec<(String, String)> = plugins
.into_iter()
.filter(|plugin| {
plugin.compatibility.compatible
&& plugin.manifest.backend_entrypoint().is_some()
&& !plugin.manifest.external_tools_excluded()
})
.map(|plugin| (plugin.manifest.id.clone(), plugin.manifest.name.clone()))
.collect();
// Probe every candidate's sidecar concurrently; the probes share the
// plugin sidecar sessions, so repeated listings are cheap.
let probes = candidates.into_iter().map(|(plugin_id, plugin_name)| {
let state = Arc::clone(&self.state);
async move {
let listing = state
.plugin_host
.invoke::<Value>(&plugin_id, "mcp/tools", json!({}), None, Some(PLUGIN_TOOLS_PROBE_TIMEOUT))
.await;
(plugin_id, plugin_name, listing)
}
});
let mut providers = Vec::new();
for (plugin_id, plugin_name, listing) in futures::future::join_all(probes).await {
match listing {
Ok(value) => {
let tools = dbx_core::ai::plugin_tools::parse_tool_list(&value);
if tools.is_empty() {
log::debug!("[mcp] plugin {plugin_id} exposes no MCP tools");
} else {
providers.push(crate::plugin_tools::PluginToolProvider { plugin_id, plugin_name, tools });
}
}
Err(err) if plugin_lacks_mcp_surface(&err) => {
log::debug!("[mcp] plugin {plugin_id} exposes no MCP tool surface: {err}");
}
Err(err) => {
log::warn!("[mcp] plugin {plugin_id} tool discovery failed: {err}");
}
}
}
Ok(providers)
}
/// Sync the latest connection list from storage into the `AppState.configs` in-memory cache:
/// upsert new/changed entries and remove connections deleted from storage. Only LocalBackend
/// needs this — WebBackend talks HTTP and holds no local AppState, and the desktop mcp_bridge
@@ -928,6 +1010,20 @@ impl DbxBackend for LocalBackend {
self.state.storage.load_mcp_global_policy().await.map(effective_mcp_policy)
}
async fn list_plugin_mcp_tools(&self) -> Result<Vec<crate::plugin_tools::PluginToolProvider>, String> {
self.detect_plugin_tool_providers().await
}
async fn call_plugin_mcp_tool(
&self,
plugin_id: &str,
tool: &str,
connection_id: Option<&str>,
arguments: &Value,
) -> Result<Value, String> {
self.call_plugin_tool(plugin_id, tool, connection_id, arguments).await
}
async fn load_connections(&self) -> Result<Vec<ConnectionConfig>, String> {
let configs = self.state.storage.load_connections().await?;
// Connections created/modified/deleted in the DBX desktop UI after this process started
+1
View File
@@ -5,6 +5,7 @@ pub mod diagnostics;
pub mod http;
pub mod http_auth;
pub mod paths;
pub mod plugin_tools;
pub mod runtime;
pub mod server;
pub mod session;
+4
View File
@@ -12,6 +12,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("dbx-mcp {}", env!("CARGO_PKG_VERSION"));
return Ok(());
}
// Diagnostics (plugin-tool discovery, bridge fallbacks) go to stderr,
// which is safe under the stdio transport. RUST_LOG controls the level;
// warnings are on by default so silent degradation stays visible.
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")).init();
let runtime = RuntimeConfig::from_environment_and_args()?;
let backend: Arc<dyn DbxBackend> = if let Ok(base_url) = std::env::var("DBX_WEB_URL") {
Arc::new(
+360
View File
@@ -0,0 +1,360 @@
//! External exposure of plugin MCP tools on the `dbx` MCP server.
//!
//! Author opt-in: installed, compatible plugins with a backend contribute
//! their `mcp/tools` listing under `dbx_<prefix>__<tool>` names only when the
//! manifest declares `external_tools: true`. Naming, parsing, and schema
//! reduction are shared with the built-in AI agent
//! (`dbx_core::ai::plugin_tools`) so one plugin tool surfaces under the same
//! exposed name on both surfaces.
//!
//! Calls stay host-bound: the caller picks among the plugin's saved
//! connections that the global MCP policy allows through `dbx_connection`
//! (`connectionId` / `connectionName` are accepted as aliases), and the host
//! generates the lifecycle payload from the saved connection — credentials
//! never cross the process boundary, and a connection saved for plugin A can
//! never be reached through plugin B's tools.
use std::collections::HashSet;
use std::sync::Arc;
use serde_json::{json, Value};
#[doc(hidden)]
pub use dbx_core::ai::plugin_tools::CONNECTION_ARGUMENT as PLUGIN_CONNECTION_ARGUMENT;
use dbx_core::ai::plugin_tools::{
exposed_tool_name, plugin_prefixes, sanitize_schema, RawPluginTool, CONNECTION_ARGUMENT, HOST_BOUND_ARGUMENTS,
};
/// Upper bound for the merged tools/list. Higher than the AI surface's cap:
/// MCP clients paginate and let their users enable/disable tools themselves,
/// so the host does not need to ration as aggressively.
pub const MAX_TOTAL_PLUGIN_TOOLS: usize = 512;
/// Plugin arguments the host resolves from the saved connection before the
/// call is forwarded.
pub const CONNECTION_SELECTOR_ARGUMENTS: &[&str] = &[CONNECTION_ARGUMENT, "connectionId", "connectionName"];
/// One plugin's discovered `mcp/tools` listing, keyed for exposure.
#[derive(Debug, Clone)]
pub struct PluginToolProvider {
pub plugin_id: String,
pub plugin_name: String,
pub tools: Vec<RawPluginTool>,
}
/// One externally exposed plugin tool.
#[derive(Debug, Clone)]
pub struct PluginToolEntry {
pub plugin_id: String,
pub plugin_name: String,
pub exposed_name: String,
pub tool: RawPluginTool,
/// The plugin schema declares `connectionId`, so the host injects the
/// bound connection's id into the forwarded arguments.
pub injects_connection_id: bool,
}
/// Whether `name` sits in the plugin-tool namespace (`dbx_<prefix>__<tool>`).
/// The static `dbx_*` router tools never contain `__`, so this cannot swallow
/// one, and unknown plugin names simply fail resolution at call time.
pub fn is_plugin_tool_name(name: &str) -> bool {
let Some(rest) = name.strip_prefix("dbx_") else { return false };
let Some((prefix, _)) = rest.split_once("__") else { return false };
!prefix.is_empty()
}
/// Builds the exposed entries from raw provider listings. Deterministic:
/// providers are ordered by plugin id (so prefix de-duplication is stable)
/// and each plugin keeps its listing order. Exposed names live in the
/// `dbx_<prefix>__<tool>` namespace: the shared AI-surface name plus the
/// `dbx_` router prefix, which static tools never use with a `__` separator.
pub fn build_catalog(providers: &[PluginToolProvider]) -> Vec<PluginToolEntry> {
let mut sorted: Vec<&PluginToolProvider> = providers.iter().collect();
sorted.sort_by(|left, right| left.plugin_id.cmp(&right.plugin_id));
let prefixes = plugin_prefixes(sorted.iter().map(|provider| provider.plugin_id.as_str()));
let mut entries = Vec::new();
'providers: for provider in sorted {
let prefix = &prefixes[&provider.plugin_id];
let mut used = HashSet::new();
for tool in &provider.tools {
if entries.len() >= MAX_TOTAL_PLUGIN_TOOLS {
log::warn!(
"[mcp][plugin-tools] tool limit {MAX_TOTAL_PLUGIN_TOOLS} reached; remaining plugin tools skipped"
);
break 'providers;
}
entries.push(PluginToolEntry {
exposed_name: format!("dbx_{}", exposed_tool_name(prefix, &tool.name, &mut used)),
plugin_id: provider.plugin_id.clone(),
plugin_name: provider.plugin_name.clone(),
injects_connection_id: tool.input_schema.pointer("/properties/connectionId").is_some(),
tool: tool.clone(),
});
}
}
entries
}
/// The caller-facing parameter schema: the plugin schema reduced to the same
/// portable subset the AI surface uses, host-bound arguments removed, and an
/// optional connection selector added when the plugin has allowed
/// connections. The selector stays optional: with exactly one connection the
/// host binds it, and connection-less tools work without one.
pub fn external_tool_parameters(input_schema: &Value, connections: &[(String, String)]) -> Value {
let mut schema = sanitize_schema(input_schema, 0);
if schema.get("type").and_then(Value::as_str) != Some("object") {
schema = json!({ "type": "object", "properties": {} });
}
let object = schema.as_object_mut().expect("object schema");
let properties = object.entry("properties").or_insert_with(|| json!({}));
if let Some(properties) = properties.as_object_mut() {
for key in HOST_BOUND_ARGUMENTS {
properties.remove(*key);
}
}
let required = object
.get("required")
.and_then(Value::as_array)
.map(|items| {
items
.iter()
.filter_map(Value::as_str)
.filter(|key| !HOST_BOUND_ARGUMENTS.contains(key))
.map(str::to_string)
.collect::<Vec<_>>()
})
.unwrap_or_default();
if !required.is_empty() {
object.insert("required".to_string(), json!(required));
} else {
object.remove("required");
}
if !connections.is_empty() {
let choices = connections.iter().map(|(id, name)| format!("{id} = {name}")).collect::<Vec<_>>().join("; ");
let mut selector = json!({
"type": "string",
"description": format!(
"DBX connection to run this tool on. Omit to use the only allowed connection. ({choices})"
),
});
if connections.len() > 1 {
selector["enum"] = json!(connections.iter().map(|(id, _)| id.clone()).collect::<Vec<_>>());
}
object["properties"][CONNECTION_ARGUMENT] = selector;
}
schema
}
/// Caller-facing description, attributed to the owning plugin.
pub fn external_tool_description(plugin_name: &str, tool: &RawPluginTool) -> String {
let body = if tool.description.trim().is_empty() { tool.name.as_str() } else { tool.description.as_str() };
format!("[{plugin_name} plugin] {body}").chars().take(1_500).collect()
}
/// Resolves the connection binding for one external call. `selector` is the
/// trimmed `dbx_connection` / `connectionId` / `connectionName` value, when
/// the caller supplied one. Matching mirrors the AI surface: exact id first,
/// then an unambiguous name.
pub fn select_connection<'a>(
connections: &'a [(String, String)],
selector: Option<&str>,
) -> Result<Option<&'a (String, String)>, String> {
let available = || connections.iter().map(|(id, name)| format!("{id} ({name})")).collect::<Vec<_>>().join(", ");
let Some(selector) = selector.filter(|selector| !selector.trim().is_empty()) else {
return match connections {
[only] => Ok(Some(only)),
[] => Ok(None),
_ => Err(format!(
"Pass `{CONNECTION_ARGUMENT}` to choose the connection. Allowed connections: {}",
available()
)),
};
};
let requested = selector.trim();
connections
.iter()
.find(|(id, _)| id == requested)
.or_else(|| {
let mut by_name = connections.iter().filter(|(_, name)| name == requested);
let first = by_name.next();
// A name is only a valid selector when it is unambiguous.
first.filter(|_| by_name.next().is_none())
})
.map(Some)
.ok_or_else(|| {
format!("`{requested}` is not an allowed connection for this tool. Allowed connections: {}", available())
})
}
/// Extracts the connection selector from raw call arguments (without
/// consuming them), preferring the canonical `dbx_connection` key.
pub fn connection_selector_from(arguments: &Value) -> Option<&str> {
CONNECTION_SELECTOR_ARGUMENTS.iter().find_map(|key| arguments.get(*key).and_then(Value::as_str))
}
/// Converts a plugin `mcp/call` answer (MCP `CallToolResult`-shaped JSON)
/// into the rmcp wire type, degrading to a plain text payload for plugins
/// that return something else.
pub fn call_result_to_rmcp(value: Value) -> rmcp::model::CallToolResult {
use rmcp::model::{CallToolResult, ContentBlock};
if let Ok(result) = serde_json::from_value::<CallToolResult>(value.clone()) {
return result;
}
let text = if value.is_null() { "(the tool returned no output)".to_string() } else { value.to_string() };
let mut result = CallToolResult::success(vec![ContentBlock::text(text)]);
result.is_error = None;
result
}
/// The rmcp `Tool` for the external `tools/list` view.
pub fn to_rmcp_tool(entry: &PluginToolEntry, connections: &[(String, String)]) -> rmcp::model::Tool {
let annotations =
entry.tool.annotations.as_object().filter(|annotations| !annotations.is_empty()).and_then(|annotations| {
serde_json::from_value::<rmcp::model::ToolAnnotations>(Value::Object(annotations.clone())).ok()
});
let schema = external_tool_parameters(&entry.tool.input_schema, connections);
let mut tool = rmcp::model::Tool::new(
entry.exposed_name.clone(),
external_tool_description(&entry.plugin_name, &entry.tool),
Arc::new(schema.as_object().cloned().unwrap_or_default()),
);
tool.annotations = annotations;
tool
}
#[cfg(test)]
mod tests {
use super::*;
use dbx_core::ai::plugin_tools::parse_tool_list;
fn provider(plugin_id: &str, plugin_name: &str, tools: Value) -> PluginToolProvider {
PluginToolProvider {
plugin_id: plugin_id.to_string(),
plugin_name: plugin_name.to_string(),
tools: parse_tool_list(&tools),
}
}
fn ssh_listing() -> Value {
json!({
"tools": [
{
"name": "sftp_list_dir",
"description": "List a remote directory",
"annotations": { "readOnlyHint": true },
"inputSchema": {
"type": "object",
"properties": {
"connectionId": { "type": "string" },
"path": { "type": "string", "description": "Absolute path" }
},
"required": ["connectionId", "path"]
}
},
{
"name": "ssh_exec",
"description": "Run a command",
"inputSchema": { "type": "object", "properties": { "command": { "type": "string" } }, "required": ["command"] }
}
]
})
}
#[test]
fn plugin_namespace_cannot_swallow_static_router_names() {
assert!(is_plugin_tool_name("dbx_ssh__sftp_list_dir"));
assert!(is_plugin_tool_name("dbx_ssh__x__y"));
assert!(!is_plugin_tool_name("dbx_list_connections"));
assert!(!is_plugin_tool_name("dbx_ssh_underscore"));
assert!(!is_plugin_tool_name("ssh__sftp_list_dir"));
assert!(!is_plugin_tool_name("dbx____"));
}
#[test]
fn catalog_exposes_prefixed_names_in_provider_order() {
let providers = vec![
provider("io.dbx.ssh", "Terminal", ssh_listing()),
provider("io.dbx.files", "Files", json!({ "tools": [{ "name": "files_list", "description": "List" }] })),
];
let entries = build_catalog(&providers);
let names = entries.iter().map(|entry| entry.exposed_name.as_str()).collect::<Vec<_>>();
assert_eq!(names, ["dbx_files__files_list", "dbx_ssh__sftp_list_dir", "dbx_ssh__ssh_exec"]);
let sftp = entries.iter().find(|entry| entry.exposed_name == "dbx_ssh__sftp_list_dir").unwrap();
assert!(sftp.tool.read_only);
assert!(sftp.injects_connection_id, "the plugin schema declares connectionId");
}
#[test]
fn catalog_is_plugin_agnostic_and_disambiguates_prefix_clashes() {
// Any plugin id works; the prefix is the id's last segment, extended
// leftward only when two plugins share it — the distinguishing part
// of the id stays in the name instead of an install-order counter.
let providers = vec![
provider("a.files", "Files A", json!({ "tools": [{ "name": "list", "description": "List" }] })),
provider("b.files", "Files B", json!({ "tools": [{ "name": "list", "description": "List" }] })),
provider("com.vendor.kubernetes", "K8s", json!({ "tools": [{ "name": "apply", "description": "Apply" }] })),
];
let entries = build_catalog(&providers);
let names = entries.iter().map(|entry| entry.exposed_name.as_str()).collect::<Vec<_>>();
assert_eq!(names, ["dbx_a_files__list", "dbx_b_files__list", "dbx_kubernetes__apply"]);
}
#[test]
fn external_schema_strips_host_bound_arguments_and_adds_selector() {
let providers = vec![provider("io.dbx.ssh", "Terminal", ssh_listing())];
let entries = build_catalog(&providers);
let sftp = entries.iter().find(|entry| entry.exposed_name == "dbx_ssh__sftp_list_dir").unwrap();
let schema = external_tool_parameters(
&sftp.tool.input_schema,
&[("c1".to_string(), "prod".to_string()), ("c2".to_string(), "test".to_string())],
);
assert!(schema.pointer("/properties/connectionId").is_none());
assert_eq!(schema["required"], json!(["path"]), "connectionId leaves the required list");
assert_eq!(schema["properties"][CONNECTION_ARGUMENT]["enum"], json!(["c1", "c2"]));
let single = external_tool_parameters(&sftp.tool.input_schema, &[("c1".to_string(), "prod".to_string())]);
assert!(single.pointer(&format!("/properties/{CONNECTION_ARGUMENT}/enum")).is_none());
assert!(single.pointer(&format!("/properties/{CONNECTION_ARGUMENT}")).is_some());
let none = external_tool_parameters(&sftp.tool.input_schema, &[]);
assert!(none.pointer(&format!("/properties/{CONNECTION_ARGUMENT}")).is_none());
}
#[test]
fn selector_resolution_mirrors_the_ai_surface() {
let connections = vec![("c1".to_string(), "prod".to_string()), ("c2".to_string(), "test".to_string())];
// Multiple connections need an explicit selector.
assert!(select_connection(&connections, None).is_err());
// Exact id, unique name, unknown.
assert_eq!(select_connection(&connections, Some("c2")).unwrap().unwrap().0, "c2");
assert_eq!(select_connection(&connections, Some("prod")).unwrap().unwrap().0, "c1");
assert!(select_connection(&connections, Some("c9")).is_err());
let single = vec![("c1".to_string(), "prod".to_string())];
assert_eq!(select_connection(&single, None).unwrap().unwrap().0, "c1");
let empty: Vec<(String, String)> = Vec::new();
assert!(select_connection(&empty, None).unwrap().is_none(), "connection-less tools stay callable");
}
#[test]
fn selector_extraction_prefers_the_canonical_argument() {
let args = json!({ "connectionId": "k1", "path": "/" });
assert_eq!(connection_selector_from(&args), Some("k1"));
let canonical = json!({ "dbx_connection": "k2", "connectionId": "k1" });
assert_eq!(connection_selector_from(&canonical), Some("k2"));
assert_eq!(connection_selector_from(&json!({ "path": "/" })), None);
}
#[test]
fn call_results_convert_with_a_text_fallback() {
let shaped = call_result_to_rmcp(json!({
"content": [{ "type": "text", "text": "done" }],
"isError": true
}));
assert_eq!(shaped.content.len(), 1);
assert_eq!(shaped.is_error, Some(true));
let fallback = call_result_to_rmcp(json!({ "unexpected": "shape" }));
assert_eq!(fallback.content.len(), 1);
assert_eq!(fallback.is_error, None);
}
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,66 @@
//! End-to-end external plugin-tools test against a real `.dbxp` package:
//! install → opt-in-filtered discovery → merged `tools/list` → server
//! dispatch of a connection-less tool through the real sidecar. The packaged
//! plugin must declare `external_tools: true` to be exposed here.
//!
//! The mechanism under test is plugin-agnostic; the ssh plugin is only the
//! concrete vehicle available here (mirroring `plugin_tools_bridge.rs`).
//! Set DBX_SSH_PACKAGE to a packaged `io.dbx.ssh` artifact; the test skips
//! itself otherwise.
use dbx_core::plugins::{PluginInstallPolicy, PluginPackageInstaller};
use dbx_mcp::{DbxMcpServer, LocalBackend, McpScope};
#[tokio::test]
async fn ssh_package_tools_are_detected_listed_and_dispatched() {
let Ok(package) = std::env::var("DBX_SSH_PACKAGE") else {
eprintln!("skipping: DBX_SSH_PACKAGE is not set");
return;
};
let package = std::path::PathBuf::from(package);
assert!(package.is_file(), "package missing: {}", package.display());
let data_dir = tempfile::tempdir().unwrap();
let plugins_root = data_dir.path().join("plugins");
let installer = PluginPackageInstaller::new(plugins_root.clone(), "0.7.0").expect("installer");
let result = installer.install_file(&package, PluginInstallPolicy::LocalDevelopment).expect("install .dbxp");
assert_eq!(result.response().plugin.manifest.id, "io.dbx.ssh");
let database_path = data_dir.path().join("dbx.db");
let storage = dbx_core::storage::Storage::open(&database_path).await.unwrap();
drop(storage);
// No saved connections: every tool below must bind connection-less.
let backend = LocalBackend::open_with_app_version(&database_path, "0.7.0").await.unwrap();
// 1. Opt-in-filtered discovery over the real sidecar.
let providers = backend.detect_plugin_tool_providers().await.expect("detect plugin tools");
let ssh = providers.iter().find(|provider| provider.plugin_id == "io.dbx.ssh").expect("ssh detected");
assert!(
ssh.tools.iter().any(|tool| tool.name == "ssh_list_known_hosts"),
"expected ssh_list_known_hosts in {:?}",
ssh.tools.iter().map(|tool| tool.name.as_str()).collect::<Vec<_>>()
);
// 2. The server merges the detected tools into tools/list under the
// shared dbx_<prefix>__<tool> namespace.
let backend = std::sync::Arc::new(backend);
let server = DbxMcpServer::with_runtime_options(backend, McpScope::default(), false);
let tools = server.policy_filtered_tools().await;
let exposed = "dbx_ssh__ssh_list_known_hosts";
let tool = tools.iter().find(|tool| tool.name.as_ref() == exposed).expect("plugin tool merged into tools/list");
assert!(
tool.input_schema
.get("properties")
.map(|properties| properties.get("dbx_connection"))
.unwrap_or(None)
.is_none(),
"no saved connections, so no connection selector is advertised"
);
// 3. Dispatch a real call through the host-bound path.
let result = server.call_plugin_tool_dispatch(exposed, serde_json::json!({})).await.expect("dispatch ok");
assert_ne!(result.is_error, Some(true), "tool failed: {result:?}");
let text = result.content[0].as_text().expect("text result").text.as_str();
let parsed: serde_json::Value = serde_json::from_str(text).expect("result JSON");
assert!(parsed["knownHosts"].is_array(), "unexpected result: {parsed}");
}
@@ -250,6 +250,7 @@ pub enum PluginContribution {
ResultView(PluginResultViewContribution),
Command(PluginCommandContribution),
Menus(PluginMenusContribution),
Mcp(PluginMcpContribution),
}
impl PluginContribution {
@@ -262,10 +263,46 @@ impl PluginContribution {
Self::ResultView(contribution) => &contribution.id,
Self::Command(contribution) => &contribution.id,
Self::Menus(contribution) => &contribution.id,
Self::Mcp(contribution) => &contribution.id,
}
}
}
/// Optional surface override for a sidecar that implements the MCP tool
/// bridge (`mcp/tools` + `mcp/call`, see `plugins/README.md` "Tools for the
/// built-in AI assistant").
///
/// Neither surface is exposed by install alone: the built-in AI agent only
/// sees a plugin after the user enabled it in the Plugin Center, and the
/// external `dbx` MCP server only sees plugins that declare
/// `external_tools: true` here. This contribution narrows or widens those
/// surfaces per author: `ai_tools: false` keeps the tools off the built-in AI
/// agent even when the user opts in, and `external_tools` (default `false`)
/// opts the tools into the external `dbx` MCP server. The Plugin Center
/// switch and the global MCP policy still override either surface per user.
/// Note that declaring this contribution makes the manifest unreadable to
/// hosts that predate it, so plugins that must install on older hosts should
/// not declare it.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PluginMcpContribution {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub description: Option<String>,
/// Keep the tools on the built-in AI agent. Defaults to `true`; set to
/// `false` to keep them off that surface even when the user opts in.
#[serde(default = "default_true", skip_serializing_if = "is_true")]
pub ai_tools: bool,
/// Expose the tools on the external `dbx` MCP server. Defaults to
/// `false`; set to `true` to opt in to that surface.
#[serde(default, skip_serializing_if = "is_false")]
pub external_tools: bool,
}
fn default_true() -> bool {
true
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PluginFormFieldDefinition {
@@ -995,6 +1032,29 @@ impl PluginManifest {
}))
}
/// The plugin's single MCP tool declaration, if any. A manifest declaring
/// more than one is rejected during validation, so first match is exact.
pub fn mcp_contribution(&self) -> Option<&PluginMcpContribution> {
self.contributions.iter().find_map(|contribution| match contribution {
PluginContribution::Mcp(mcp) => Some(mcp),
_ => None,
})
}
/// Whether the optional `mcp` declaration keeps the sidecar tools off the
/// built-in AI agent (`ai_tools: false`) even when the user opts in via
/// the Plugin Center. Without it the tools participate once opted in.
pub fn ai_tools_excluded(&self) -> bool {
self.mcp_contribution().is_some_and(|mcp| !mcp.ai_tools)
}
/// Whether the optional `mcp` declaration does not opt the sidecar tools
/// into the external `dbx` MCP server. `external_tools` defaults to
/// `false`, so only an explicit `true` exposes them there.
pub fn external_tools_excluded(&self) -> bool {
self.mcp_contribution().is_some_and(|mcp| !mcp.external_tools)
}
pub fn compatibility(&self, plugin_dir: &Path, dbx_version: &str) -> PluginCompatibility {
let mut errors = Vec::new();
let mut warnings = Vec::new();
@@ -1276,6 +1336,7 @@ fn validate_contributions(
let mut command_ids = HashSet::new();
let mut command_workbench_references = Vec::new();
let mut menu_command_references = Vec::new();
let mut mcp_contributions = 0usize;
for (index, contribution) in contributions.iter().enumerate() {
let id = contribution.id();
@@ -1481,9 +1542,23 @@ fn validate_contributions(
menu_command_references.push((id.to_string(), item.command.clone()));
}
}
PluginContribution::Mcp(mcp) => {
mcp_contributions += 1;
validate_optional_text(
mcp.description.as_deref(),
&format!("Mcp contribution '{id}' description"),
errors,
);
if !has_backend {
errors.push(format!("Mcp contribution '{id}' requires a backend entrypoint"));
}
}
}
}
if mcp_contributions > 1 {
errors.push(format!("A manifest declares {mcp_contributions} mcp contributions; at most one is allowed"));
}
for (provider, workbench) in workbench_references {
if !workbench_ids.contains(&workbench) {
errors.push(format!("Connection provider '{provider}' references missing workbench '{workbench}'"));
@@ -1963,8 +2038,8 @@ mod tests {
parse_host_network_permission, resolve_safe_plugin_path, validate_connection_actions, validate_contributions,
PluginCommandAction, PluginCommandContribution, PluginCommandPresentation, PluginCommandRestore,
PluginCommandReuse, PluginConnectionActionContribution, PluginConnectionProviderContribution,
PluginContribution, PluginFormFieldBinding, PluginManifest, PluginMenuItem, PluginMenuLocation,
PluginMenusContribution, PluginOpenWorkbenchAction, SUPPORTED_PLUGIN_HOST_API_VERSION,
PluginContribution, PluginFormFieldBinding, PluginManifest, PluginMcpContribution, PluginMenuItem,
PluginMenuLocation, PluginMenusContribution, PluginOpenWorkbenchAction, SUPPORTED_PLUGIN_HOST_API_VERSION,
SUPPORTED_PLUGIN_PERMISSIONS,
};
@@ -1992,6 +2067,85 @@ mod tests {
Ok((dir, manifest))
}
#[test]
fn mcp_contribution_parses_the_frozen_contract() {
// Defaults: the built-in AI surface participates (subject to the
// Plugin Center opt-in), the external `dbx` server does not.
let mcp: PluginContribution = serde_json::from_value(serde_json::json!({
"type": "mcp",
"id": "io.dbx.example.mcp"
}))
.unwrap();
let PluginContribution::Mcp(mcp) = mcp else { unreachable!("parsed as mcp above") };
assert!(mcp.ai_tools);
assert!(!mcp.external_tools);
let widened: PluginContribution = serde_json::from_value(serde_json::json!({
"type": "mcp",
"id": "io.dbx.example.mcp",
"external_tools": true
}))
.unwrap();
let PluginContribution::Mcp(widened) = widened else { unreachable!() };
assert!(widened.ai_tools);
assert!(widened.external_tools);
// Unknown fields inside the contribution reject (frozen contract).
assert!(serde_json::from_value::<PluginContribution>(serde_json::json!({
"type": "mcp", "id": "x", "entrypoint": "bin/example"
}))
.is_err());
}
#[test]
fn mcp_contribution_requires_a_backend_and_stays_single() {
let plugin_dir = std::env::temp_dir();
let mcp = PluginContribution::Mcp(PluginMcpContribution {
id: "io.dbx.example.mcp".to_string(),
description: None,
ai_tools: true,
external_tools: true,
});
let mut errors = Vec::new();
validate_contributions(std::slice::from_ref(&mcp), false, false, &plugin_dir, &mut errors);
assert!(errors.iter().any(|error| error.contains("requires a backend entrypoint")), "{errors:?}");
let mut errors = Vec::new();
validate_contributions(std::slice::from_ref(&mcp), true, false, &plugin_dir, &mut errors);
assert!(errors.is_empty(), "{errors:?}");
let two = vec![mcp.clone(), mcp];
let mut errors = Vec::new();
validate_contributions(&two, true, false, &plugin_dir, &mut errors);
assert!(errors.iter().any(|error| error.contains("at most one")), "{errors:?}");
}
#[test]
fn full_manifest_parses_the_mcp_declaration() {
let dir = tempfile::tempdir().unwrap();
let binary_dir = dir.path().join("bin");
std::fs::create_dir_all(&binary_dir).unwrap();
std::fs::write(binary_dir.join("example"), b"example").unwrap();
let manifest: PluginManifest = serde_json::from_value(serde_json::json!({
"manifest_version": 1,
"id": "io.dbx.example",
"name": "Example",
"version": "1.0.0",
"publisher": "example",
"engines": { "dbx": ">=0.1.0", "host_api": "^1.0" },
"entrypoints": { "backend": { "executable": "bin/example" } },
"contributions": [{
"type": "mcp",
"id": "io.dbx.example.mcp"
}]
}))
.unwrap();
assert!(!manifest.ai_tools_excluded(), "ai_tools defaults to participating");
assert!(manifest.external_tools_excluded(), "external_tools defaults to off");
let compatibility = manifest.compatibility(dir.path(), "0.6.0");
assert!(compatibility.compatible, "{:?}", compatibility.errors);
}
#[test]
fn command_and_menus_contributions_parse_the_frozen_contract() {
let command: PluginContribution = serde_json::from_value(serde_json::json!({
@@ -2603,6 +2757,7 @@ mod tests {
("result-view", "resultViewContribution"),
("command", "commandContribution"),
("menus", "menusContribution"),
("mcp", "mcpContribution"),
];
assert_eq!(referenced, kinds.iter().map(|(_, def)| def.to_string()).collect::<Vec<_>>());
for (tag, def) in kinds {
+4 -1
View File
@@ -370,7 +370,10 @@ pub async fn ai_resolve_tool_approval(Json(body): Json<AiResolveToolApprovalRequ
}
pub async fn get_ai_plugin_tool_plugins(State(state): State<Arc<WebState>>) -> Result<Json<Vec<String>>, AppError> {
Ok(Json(state.app.storage.load_ai_plugin_tool_plugin_ids().await.map_err(AppError::from)?))
let mut ids =
dbx_core::ai::plugin_tools::effective_ai_tool_plugin_ids(&state.app).await.into_iter().collect::<Vec<_>>();
ids.sort();
Ok(Json(ids))
}
pub async fn set_ai_plugin_tool_plugin_enabled(