Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions crates/openab-core/src/adapter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -352,6 +352,26 @@ pub trait ChatAdapter: Send + Sync + 'static {
title: &str,
) -> Result<ChannelRef>;

/// 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<ChannelRef> {
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<()>;

Expand Down
34 changes: 33 additions & 1 deletion crates/openab-core/src/discord.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::*;
Expand Down Expand Up @@ -182,6 +182,38 @@ impl ChatAdapter for DiscordAdapter {
})
}

async fn create_thread_in_channel(
&self,
channel: &ChannelRef,
title: &str,
content: &str,
) -> anyhow::Result<ChannelRef> {
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()?;
Expand Down
30 changes: 18 additions & 12 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -536,19 +537,34 @@ 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<Arc<dyn adapter::ChatAdapter>> =
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<dyn adapter::ChatAdapter>
});
#[cfg(not(feature = "discord"))]
let shared_discord_adapter: Option<Arc<dyn adapter::ChatAdapter>> = None;
if let Some(mcp_cfg) = cfg.mcp.clone() {
let listen = mcp_cfg.listen.clone();
let tokens = facade_sessions.clone();
// The ACP tunnel source is registered unconditionally under the `acp` feature. It used to
// 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<Arc<dyn openab_mcp::mcp::sources::CapabilitySource>> =
let mut sources: Vec<Arc<dyn openab_mcp::mcp::sources::CapabilitySource>> =
vec![Arc::new(acp_tunnel_source::AcpTunnelSource::new(
acp_tunnel.clone(),
))];
#[cfg(not(feature = "acp"))]
let sources: Vec<Arc<dyn openab_mcp::mcp::sources::CapabilitySource>> = Vec::new();
let mut sources: Vec<Arc<dyn openab_mcp::mcp::sources::CapabilitySource>> = 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
Expand Down Expand Up @@ -892,16 +908,6 @@ async fn main() -> anyhow::Result<()> {
}
});

// Pre-build shared adapters for cron scheduler
#[cfg(feature = "discord")]
let shared_discord_adapter: Option<Arc<dyn adapter::ChatAdapter>> =
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<dyn adapter::ChatAdapter>
});
#[cfg(not(feature = "discord"))]
let shared_discord_adapter: Option<Arc<dyn adapter::ChatAdapter>> = None;

let session_ttl_dur = std::time::Duration::from_secs(ttl_secs);

// Initialize multibot cache
Expand Down
117 changes: 117 additions & 0 deletions src/thread_source.rs
Original file line number Diff line number Diff line change
@@ -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<dyn ChatAdapter>,
}

impl ThreadSource {
pub fn new(adapter: Arc<dyn ChatAdapter>) -> Self {
Self { adapter }
}
}

#[async_trait::async_trait]
impl CapabilitySource for ThreadSource {
fn provider(&self) -> &str {
"openab"
}

fn tools(&self, _ctx: Option<&SessionCtx>) -> Vec<Tool> {
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<String, Value>,
) -> 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
}
}
Loading