diff --git a/crates/openab-core/src/adapter.rs b/crates/openab-core/src/adapter.rs index 2bf3a7c6d..6da7061d0 100644 --- a/crates/openab-core/src/adapter.rs +++ b/crates/openab-core/src/adapter.rs @@ -352,6 +352,26 @@ pub trait ChatAdapter: Send + Sync + 'static { title: &str, ) -> Result; + /// Create a standalone thread in a channel (not from a specific message). + /// + /// Used by the MCP facade's `create_thread` capability so agents can open + /// threads in a target channel without directly handling platform + /// credentials. The adapter uses its own authenticated HTTP client, so + /// the thread owner is the bot itself — no token is exposed to the agent. + /// + /// `content` is sent as the thread's starter message (Discord requires a + /// message body when creating a thread via `POST /channels/{id}/threads`). + /// + /// Default: unsupported (platforms that don't support standalone threads). + async fn create_thread_in_channel( + &self, + _channel: &ChannelRef, + _title: &str, + _content: &str, + ) -> Result { + Err(anyhow::anyhow!("create_thread_in_channel not supported")) + } + /// Add a reaction/emoji to a message. async fn add_reaction(&self, msg: &MessageRef, emoji: &str) -> Result<()>; diff --git a/crates/openab-core/src/discord.rs b/crates/openab-core/src/discord.rs index 609bd7459..6961e967e 100644 --- a/crates/openab-core/src/discord.rs +++ b/crates/openab-core/src/discord.rs @@ -18,7 +18,7 @@ use serenity::builder::{ use serenity::http::Http; use serenity::model::application::ButtonStyle; use serenity::model::application::{Command, CommandOptionType, ComponentInteractionDataKind, Interaction}; -use serenity::model::channel::{AutoArchiveDuration, Message, MessageType, Reaction, ReactionType}; +use serenity::model::channel::{AutoArchiveDuration, ChannelType, Message, MessageType, Reaction, ReactionType}; use serenity::model::gateway::Ready; use serenity::model::id::{ChannelId, MessageId, UserId}; use serenity::prelude::*; @@ -182,6 +182,38 @@ impl ChatAdapter for DiscordAdapter { }) } + async fn create_thread_in_channel( + &self, + channel: &ChannelRef, + title: &str, + content: &str, + ) -> anyhow::Result { + let ch_id: u64 = channel.channel_id.parse()?; + // Truncate title at char boundary to avoid panic on multi-byte chars. + let truncated_title: String = title.chars().take(100).collect(); + // Create the thread (Discord "start thread without message"). + let thread = ChannelId::new(ch_id) + .create_thread( + &self.http, + CreateThread::new(&truncated_title) + .auto_archive_duration(AutoArchiveDuration::OneDay) + .kind(ChannelType::PublicThread), + ) + .await?; + let thread_ref = ChannelRef { + platform: "discord".into(), + channel_id: thread.id.to_string(), + thread_id: None, + parent_id: Some(channel.channel_id.clone()), + origin_event_id: None, + }; + // Send the starter message so the thread has visible content. + if !content.is_empty() { + self.send_message(&thread_ref, content).await?; + } + Ok(thread_ref) + } + async fn add_reaction(&self, msg: &MessageRef, emoji: &str) -> anyhow::Result<()> { let ch_id: u64 = Self::resolve_channel(&msg.channel).parse()?; let msg_id: u64 = msg.message_id.parse()?; diff --git a/src/main.rs b/src/main.rs index f49879778..797f7b0ce 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,6 +14,7 @@ mod unified_adapter; mod acp_tunnel; #[cfg(feature = "acp")] mod acp_tunnel_source; +mod thread_source; use openab_core::acp; use openab_core::adapter::{self, AdapterRouter}; use openab_core::bot_turns; @@ -536,6 +537,16 @@ async fn main() -> anyhow::Result<()> { // that is a core feature and naming it here is an unknown-cfg error. #[cfg(feature = "acp")] openab_core::acp_mcp::report_facade_status(cfg.mcp.is_some(), &cfg.agent.working_dir); + // Pre-build shared Discord adapter (used by both the MCP facade thread + // source and the cron scheduler). + #[cfg(feature = "discord")] + let shared_discord_adapter: Option> = + cfg.discord.as_ref().map(|dc| { + let http = Arc::new(serenity::http::Http::new(&dc.bot_token)); + Arc::new(discord::DiscordAdapter::new(http)) as Arc + }); + #[cfg(not(feature = "discord"))] + let shared_discord_adapter: Option> = None; if let Some(mcp_cfg) = cfg.mcp.clone() { let listen = mcp_cfg.listen.clone(); let tokens = facade_sessions.clone(); @@ -543,12 +554,17 @@ async fn main() -> anyhow::Result<()> { // be skipped in bridge mode; with the bridge gone there is no mode in which the facade // runs without it. #[cfg(feature = "acp")] - let sources: Vec> = + let mut sources: Vec> = vec![Arc::new(acp_tunnel_source::AcpTunnelSource::new( acp_tunnel.clone(), ))]; #[cfg(not(feature = "acp"))] - let sources: Vec> = Vec::new(); + let mut sources: Vec> = Vec::new(); + // Register the thread-creation capability so agents can open threads + // via `execute_capability` without handling platform credentials. + if let Some(ref discord) = shared_discord_adapter { + sources.push(Arc::new(thread_source::ThreadSource::new(discord.clone()))); + } tokio::spawn(async move { if let Err(e) = openab_mcp::mcp::facade::serve_http_with(&listen, sources, tokens).await @@ -892,16 +908,6 @@ async fn main() -> anyhow::Result<()> { } }); - // Pre-build shared adapters for cron scheduler - #[cfg(feature = "discord")] - let shared_discord_adapter: Option> = - cfg.discord.as_ref().map(|dc| { - let http = Arc::new(serenity::http::Http::new(&dc.bot_token)); - Arc::new(discord::DiscordAdapter::new(http)) as Arc - }); - #[cfg(not(feature = "discord"))] - let shared_discord_adapter: Option> = None; - let session_ttl_dur = std::time::Duration::from_secs(ttl_secs); // Initialize multibot cache diff --git a/src/thread_source.rs b/src/thread_source.rs new file mode 100644 index 000000000..b388e02f0 --- /dev/null +++ b/src/thread_source.rs @@ -0,0 +1,117 @@ +//! Thread capability source for the OAB MCP Facade. +//! +//! Exposes a `create_thread` tool that agents can call via `execute_capability` +//! to create a thread in a target channel. The adapter uses its own authenticated +//! HTTP client, so the thread owner is the bot itself — no token is exposed to +//! the agent subprocess. +//! +//! This closes the identity-safety gap where agents would otherwise call the +//! Discord REST API directly (via `exec` + `requests`), risking use of the wrong +//! bot's token or leaking credentials into logs and LLM context. + +use std::sync::Arc; + +use anyhow::Result; +use openab_core::adapter::{ChannelRef, ChatAdapter}; +use openab_mcp::mcp::sources::{CapabilitySource, SessionCtx}; +use openab_mcp::rmcp::model::Tool; +use serde_json::{json, Map, Value}; + +/// Facade capability source exposing platform thread-creation to agents. +/// +/// Registered when a chat adapter is available, so the agent can open threads +/// in channels it is authorized for without handling credentials itself. +pub struct ThreadSource { + adapter: Arc, +} + +impl ThreadSource { + pub fn new(adapter: Arc) -> Self { + Self { adapter } + } +} + +#[async_trait::async_trait] +impl CapabilitySource for ThreadSource { + fn provider(&self) -> &str { + "openab" + } + + fn tools(&self, _ctx: Option<&SessionCtx>) -> Vec { + let schema = json!({ + "type": "object", + "properties": { + "channel_id": { + "type": "string", + "description": "The parent channel ID to create the thread in." + }, + "name": { + "type": "string", + "description": "The thread title (max 100 characters)." + }, + "content": { + "type": "string", + "description": "Optional starter message content for the thread." + } + }, + "required": ["channel_id", "name"] + }); + vec![Tool::new( + "create_thread", + "Create a thread in a channel. The thread owner is the bot itself — no token is exposed to the caller. Returns the new thread's channel ID.", + Arc::new(schema.as_object().unwrap().clone()), + )] + } + + async fn call( + &self, + _ctx: Option<&SessionCtx>, + tool: &str, + args: &Map, + ) -> Result<(Value, bool)> { + if tool != "create_thread" { + return Ok((json!({"error": format!("unknown tool: {tool}")}), true)); + } + + let channel_id = args + .get("channel_id") + .and_then(|v| v.as_str()) + .ok_or_else(|| anyhow::anyhow!("channel_id is required"))?; + let name = args + .get("name") + .and_then(|v| v.as_str()) + .ok_or_else(|| anyhow::anyhow!("name is required"))?; + let content = args + .get("content") + .and_then(|v| v.as_str()) + .unwrap_or(""); + + let channel = ChannelRef { + platform: self.adapter.platform().into(), + channel_id: channel_id.into(), + thread_id: None, + parent_id: None, + origin_event_id: None, + }; + + match self + .adapter + .create_thread_in_channel(&channel, name, content) + .await + { + Ok(thread_ref) => Ok(( + json!({ + "thread_id": thread_ref.channel_id, + "parent_id": thread_ref.parent_id, + "platform": thread_ref.platform, + }), + false, + )), + Err(e) => Ok((json!({"error": format!("{e:#}")}), true)), + } + } + + fn requires_session(&self) -> bool { + false + } +}