feat(mcp): Connectors — catalog + global vs per-user runtimes (§7/§14/§15)

Re-architects MCP from one owner table + agent-written registration into an
admin-curated catalog with two runtimes unioned per session, surfaced in the UI
as "Connectors" (mcp/schema stays neutral, §0.1).

Two runtimes behind one seam (§7):
- Global runtime: shared, stateless connectors (web-search, Tavily…) on the
  HOST, connected at boot from mcp_global_servers, access-filtered per user via
  mcp_global_access.
- Per-user runtime: a user's activated connectors run INSIDE their container,
  started at first login from mcp_user_servers and living until restart (§9);
  docker exec -i children die via kill_on_drop when the UserContext drops.
- McpProvider trait (mcp/provider.rs): the session round-loop never learns which
  runtime owns a server. McpManager implements it directly (inert ownerless
  bundle); UserMcpView implements global ∪ user with an accessible_global
  snapshot. Both share McpManager::connect_all; McpServerSpec +
  global_row_spec/user_row_spec turn a DB row into a connectable spec.
- mcp-client: McpServerConfig.launch_in runs a stdio command inside a container
  via docker exec -i (set at runtime, never parsed from config).

Authorization is a capability on the role, not `if role==admin` (§0.1/§14):
role_capabilities table + db/role_capabilities.rs — register_remote and
register_local_from_catalog are self-service (seeded on every new role), while
register_local_script and manage_catalog are admin-only. admin holds every
capability by construction. This removes the agent-facing register_mcp/delete_mcp
tools and the mcp kinds of list_items/toggle_item, closing the §14 RCE vector.

Schema:
- Registry: mcp_catalog (vetted templates — schema only, no live creds),
  mcp_global_servers + mcp_global_access, role_capabilities.
- Owner: mcp_user_servers (per-user activations; api_key encrypted at rest,
  catalog_name a bare TEXT snapshot, never an owner→registry FK).
- Drops the old owner table mcp_servers.

API + UI: src/frontend/api/mcp.rs (admin catalog/global/access + user
available/activate/activated, all capability-gated via require_cap);
web/components/connectors.js (<connectors-page>) renders the user view always
and the admin view for role_id === 'admin'.

Deferred: interactive per-user auth (OAuth callback / QR / SSH elicitation, §15)
— only none/api_key wired; no boot seed of catalog presets; per-(user, session)
MCP grant model still open.
This commit is contained in:
2026-07-16 16:44:12 +01:00
parent 8dac783878
commit 6d299472e3
36 changed files with 2100 additions and 484 deletions
@@ -5,7 +5,7 @@ use anyhow::Result;
use serde_json::{Value, json};
use sqlx::SqlitePool;
use crate::mcp::McpManager;
use crate::mcp::McpProvider;
use crate::tools::tool_names::CONFIG_GROUP;
use crate::tools::{Tool, ToolDescriptionLength, truncate_label, MAX_LABEL_SHORT};
@@ -37,7 +37,7 @@ pub struct ActivateTools {
/// `None` for root agents (session-scoped grants).
/// `Some(stack_id)` for sub-agents (stack-scoped grants, deleted on frame exit).
pub stack_id: Option<i64>,
pub mcp: Arc<McpManager>,
pub mcp: Arc<dyn McpProvider>,
/// Shared in-memory grant set. Updated in-place on every call so subsequent
/// rounds within the same turn see the new tools via `all_tool_defs()`.
pub active_mcp_grants: Arc<RwLock<HashSet<String>>>,
+4 -13
View File
@@ -5,7 +5,6 @@ use serde_json::{Value, json};
use crate::agents;
use crate::cron::TaskManager;
use crate::mcp::McpManager;
use crate::plugin::PluginManager;
use crate::tools::{Tool, ToolDescriptionLength};
@@ -19,14 +18,13 @@ use crate::tools::{Tool, ToolDescriptionLength};
/// the ability to enumerate secret key names) and carries a `pattern` filter
/// that would only apply to that one type.
pub struct ListItems {
mcp: Arc<McpManager>,
plugins: Arc<PluginManager>,
cron: Arc<TaskManager>,
}
impl ListItems {
pub fn new(mcp: Arc<McpManager>, plugins: Arc<PluginManager>, cron: Arc<TaskManager>) -> Self {
Self { mcp, plugins, cron }
pub fn new(plugins: Arc<PluginManager>, cron: Arc<TaskManager>) -> Self {
Self { plugins, cron }
}
}
@@ -36,7 +34,6 @@ impl Tool for ListItems {
fn description(&self) -> &str {
"List configured items of a given type. Pass `type`:\n\
• `mcp` — MCP servers with status (running, error, disabled), description, friendly_name, and exposed tools.\n\
• `plugins` — plugins with id, name, description, enabled flag (persisted), and running flag (live).\n\
• `cron` — scheduled tasks/cron jobs with id, title, cron expression, agent_id, enabled, kind, last/next run.\n\
• `agents` — sub-agents available to delegate to (id, name, description, optional `instructions` on how to call the agent well, optional client). Do NOT invoke the `main` agent.\n\
@@ -50,7 +47,7 @@ impl Tool for ListItems {
"properties": {
"type": {
"type": "string",
"enum": ["mcp", "plugins", "cron", "agents"],
"enum": ["plugins", "cron", "agents"],
"description": "Which kind of item to list."
}
}
@@ -67,12 +64,6 @@ impl Tool for ListItems {
.ok_or_else(|| anyhow::anyhow!("list_items: missing required argument `type`"))?;
match kind {
"mcp" => {
let infos = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(self.mcp.list())
})?;
Ok(serde_json::to_string_pretty(&infos)?)
}
"plugins" => {
let plugins = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(self.plugins.list())
@@ -124,7 +115,7 @@ impl Tool for ListItems {
.collect();
Ok(serde_json::to_string_pretty(&arr)?)
}
other => anyhow::bail!("list_items: unknown type `{other}` (expected one of: mcp, plugins, cron, agents)"),
other => anyhow::bail!("list_items: unknown type `{other}` (expected one of: plugins, cron, agents)"),
}
}
}
-1
View File
@@ -43,7 +43,6 @@ pub mod list_secrets;
pub mod notify;
pub mod set_secret;
pub mod read_notification;
pub mod register_mcp;
pub mod restart;
pub mod show_file;
pub mod toggle_item;
-175
View File
@@ -1,175 +0,0 @@
use std::sync::Arc;
use anyhow::Result;
use serde_json::{Value, json};
use crate::db::mcp_servers::UpsertParams;
use crate::mcp::McpManager;
use crate::tools::{Tool, ToolDescriptionLength};
pub struct RegisterMcp {
mcp: Arc<McpManager>,
}
impl RegisterMcp {
pub fn new(mcp: Arc<McpManager>) -> Self { Self { mcp } }
}
impl Tool for RegisterMcp {
fn name(&self) -> &str { "register_mcp" }
fn category(&self) -> crate::tools::ToolCategory { crate::tools::ToolCategory::Config }
fn description(&self) -> &str {
"Register (or update) an MCP server and connect to it immediately. \
For stdio servers supply `command` and optionally `args` and `env`. \
For HTTP/SSE servers supply `url` and optionally `api_key`. \
Optionally provide `description` (what the server does) and `friendly_name` (display name for UI). \
Returns the list of tools exposed by the server once connected."
}
fn parameters_schema(&self) -> Value {
json!({
"type": "object",
"properties": {
"name": {
"type": "string",
"description": "Unique name for this MCP server (used to reference it in tool calls)."
},
"transport": {
"type": "string",
"enum": ["stdio", "http", "sse"],
"description": "Connection transport. Use `stdio` for local processes, `http` for remote servers."
},
"command": {
"type": "string",
"description": "stdio only: executable to spawn (e.g. `npx`, `uvx`, path to binary)."
},
"args": {
"type": "array",
"items": { "type": "string" },
"description": "stdio only: command-line arguments passed to the executable."
},
"env": {
"type": "object",
"additionalProperties": { "type": "string" },
"description": "stdio only: extra environment variables. Values support `${VAR}` interpolation."
},
"url": {
"type": "string",
"description": "http/sse only: base URL of the remote MCP server."
},
"api_key": {
"type": "string",
"description": "http/sse only: API key sent as `Authorization: Bearer <key>`."
},
"description": {
"type": "string",
"description": "A short description of what this MCP server provides (shown in list_items type=mcp)."
},
"friendly_name": {
"type": "string",
"description": "A human-readable display name for this MCP server (e.g. 'Google Calendar')."
}
},
"required": ["name", "transport"]
})
}
fn describe(&self, args: &Value, _length: ToolDescriptionLength) -> String {
let name = args["name"].as_str().unwrap_or("?");
format!("register MCP `{name}`")
}
fn execute(&self, args: Value) -> Result<String> {
let name = args["name"].as_str()
.ok_or_else(|| anyhow::anyhow!("register_mcp: missing required argument `name`"))?;
let transport = args["transport"].as_str()
.ok_or_else(|| anyhow::anyhow!("register_mcp: missing required argument `transport`"))?;
let args_json = args["args"].as_array()
.map(|a| serde_json::to_string(a))
.transpose()?;
let env_json = args["env"].as_object()
.map(|o| serde_json::to_string(o))
.transpose()?;
let p = UpsertParams {
name,
transport,
command: args["command"].as_str(),
args_json,
env_json,
url: args["url"].as_str(),
api_key: args["api_key"].as_str(),
description: args["description"].as_str(),
friendly_name: args["friendly_name"].as_str(),
};
let tool_names = tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(self.mcp.register(p))
})?;
Ok(format!(
"MCP server '{}' registered and connected. Tools: {}",
name,
if tool_names.is_empty() { "(none)".to_string() } else { tool_names.join(", ") },
))
}
}
// ── delete_mcp ────────────────────────────────────────────────────────────────
//
// Destructive counterpart to `register_mcp`. Kept separate from `toggle_item`
// (kind=mcp) for the same reason `delete_cron_job` is: toggling is reversible,
// deletion is not, so the distinct tool can carry its own approval rule and the
// LLM can't conflate "disable" with "remove". Both live here because both manage
// the MCP-server lifecycle and hold only `Arc<McpManager>`.
pub struct DeleteMcp {
mcp: Arc<McpManager>,
}
impl DeleteMcp {
pub fn new(mcp: Arc<McpManager>) -> Self { Self { mcp } }
}
impl Tool for DeleteMcp {
fn name(&self) -> &str { "delete_mcp" }
fn category(&self) -> crate::tools::ToolCategory { crate::tools::ToolCategory::Config }
fn description(&self) -> &str {
"Permanently delete (unregister) an MCP server by name: removes it from the \
database and disconnects it. This is irreversible — to temporarily turn a \
server off without losing its configuration, use \
`toggle_item(kind=\"mcp\", enabled=false)` instead."
}
fn parameters_schema(&self) -> Value {
json!({
"type": "object",
"required": ["name"],
"properties": {
"name": {
"type": "string",
"description": "Name of the MCP server to delete (from list_items type=mcp)."
}
}
})
}
fn describe(&self, args: &Value, _length: ToolDescriptionLength) -> String {
let name = args["name"].as_str().unwrap_or("?");
format!("delete MCP `{name}`")
}
fn execute(&self, args: Value) -> Result<String> {
let name = args["name"].as_str()
.ok_or_else(|| anyhow::anyhow!("delete_mcp: missing required argument `name`"))?;
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(self.mcp.unregister(name))
})?;
Ok(format!("MCP server '{name}' deleted and disconnected."))
}
}
+5 -18
View File
@@ -4,7 +4,6 @@ use anyhow::Result;
use serde_json::{Value, json};
use crate::cron::TaskManager;
use crate::mcp::McpManager;
use crate::plugin::PluginManager;
use crate::tools::{Tool, ToolDescriptionLength};
@@ -16,14 +15,13 @@ use crate::tools::{Tool, ToolDescriptionLength};
/// (irreversible) whereas toggling is reversible, and keeping it separate lets
/// it carry a distinct approval rule.
pub struct ToggleItem {
mcp: Arc<McpManager>,
plugins: Arc<PluginManager>,
cron: Arc<TaskManager>,
}
impl ToggleItem {
pub fn new(mcp: Arc<McpManager>, plugins: Arc<PluginManager>, cron: Arc<TaskManager>) -> Self {
Self { mcp, plugins, cron }
pub fn new(plugins: Arc<PluginManager>, cron: Arc<TaskManager>) -> Self {
Self { plugins, cron }
}
}
@@ -33,7 +31,6 @@ impl Tool for ToggleItem {
fn description(&self) -> &str {
"Enable or disable an item by kind. Pass `kind`, `id`, and `enabled`:\n\
• `mcp` — `id` is the server name. NOTE: a restart is required for the change to take full effect on running servers.\n\
• `plugin` — `id` is the plugin id (e.g. \"telegram\"). Takes effect immediately (the plugin is started/stopped at once).\n\
• `cron` — `id` is the numeric job id (from `list_items` type=cron). Re-enabling recalculates next_run_at.\n\
Use `list_items` to find current names/ids and statuses."
@@ -46,12 +43,12 @@ impl Tool for ToggleItem {
"properties": {
"kind": {
"type": "string",
"enum": ["mcp", "plugin", "cron"],
"enum": ["plugin", "cron"],
"description": "Which kind of item to toggle."
},
"id": {
"type": "string",
"description": "MCP server name | plugin id | numeric cron job id (as a string)."
"description": "plugin id | numeric cron job id (as a string)."
},
"enabled": {
"type": "boolean",
@@ -78,16 +75,6 @@ impl Tool for ToggleItem {
.ok_or_else(|| anyhow::anyhow!("toggle_item: missing required argument `enabled`"))?;
match kind {
"mcp" => {
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(self.mcp.set_enabled(id, enabled))
})?;
Ok(format!(
"MCP server '{}' is now {}. Note: a restart is required for the change to take effect on running servers.",
id,
if enabled { "enabled" } else { "disabled" }
))
}
"plugin" => {
tokio::task::block_in_place(|| {
tokio::runtime::Handle::current().block_on(self.plugins.toggle(id, enabled))
@@ -107,7 +94,7 @@ impl Tool for ToggleItem {
Ok(format!("No task with id {job_id}."))
}
}
other => anyhow::bail!("toggle_item: unknown kind `{other}` (expected one of: mcp, plugin, cron)"),
other => anyhow::bail!("toggle_item: unknown kind `{other}` (expected one of: plugin, cron)"),
}
}
}