Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
169
akode-rs/message-board-mcp/src/http.rs
Normal file
169
akode-rs/message-board-mcp/src/http.rs
Normal file
@@ -0,0 +1,169 @@
|
||||
//! Streamable HTTP and trusted-host caller metadata for the shared MCP contract.
|
||||
//! Backend selection and membership validation belong to the supplied adapter binding.
|
||||
//! Shutdown cancels pending bindings and drains session handlers before releasing their state.
|
||||
|
||||
use crate::MessageBoardMcpServer;
|
||||
use crate::list_tools_result;
|
||||
use crate::server_info;
|
||||
use axum::Router;
|
||||
use axum::extract::Request;
|
||||
use axum::http::HeaderValue;
|
||||
use axum::http::StatusCode;
|
||||
use axum::http::header::AUTHORIZATION;
|
||||
use axum::middleware;
|
||||
use axum::middleware::Next;
|
||||
use akode_message_board::MessageBoardTool;
|
||||
use akode_protocol::SessionId;
|
||||
use akode_protocol::ThreadId;
|
||||
use rmcp::ErrorData;
|
||||
use rmcp::ServerHandler;
|
||||
use rmcp::model::CallToolRequestParams;
|
||||
use rmcp::model::CallToolResponse;
|
||||
use rmcp::model::ListToolsResult;
|
||||
use rmcp::model::PaginatedRequestParams;
|
||||
use rmcp::model::ServerConfig;
|
||||
use rmcp::service::RequestContext;
|
||||
use rmcp::service::RoleServer;
|
||||
use rmcp::transport::StreamableHttpServerConfig;
|
||||
use rmcp::transport::StreamableHttpService;
|
||||
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
|
||||
use serde::Deserialize;
|
||||
use std::future::Future;
|
||||
use std::sync::Arc;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
use tokio_util::task::TaskTracker;
|
||||
use tokio_util::task::task_tracker::TaskTrackerToken;
|
||||
|
||||
/// Serves the discussion tools on `/mcp`. The binding must validate membership and
|
||||
/// return the existing adapter with an authoritative board, caller and path.
|
||||
/// The bearer authorizes a trusted host to assert `threadId` and `sessionId` metadata.
|
||||
/// Use TLS at the deployment boundary outside loopback. Cancellation closes HTTP and MCP sessions,
|
||||
/// cancels pending bindings, and waits for already-dispatched board operations to finish.
|
||||
pub async fn serve_http<F, Fut>(
|
||||
listener: TcpListener,
|
||||
token: String,
|
||||
config: StreamableHttpServerConfig,
|
||||
bind: F,
|
||||
) -> anyhow::Result<()>
|
||||
where
|
||||
F: Fn(ThreadId, SessionId) -> Fut + Clone + Send + Sync + 'static,
|
||||
Fut: Future<Output = Result<MessageBoardMcpServer, ErrorData>> + Send + 'static,
|
||||
{
|
||||
anyhow::ensure!(!token.is_empty(), "MCP bearer token must not be empty");
|
||||
let mut authorization = HeaderValue::from_str(&format!("Bearer {token}"))?;
|
||||
authorization.set_sensitive(true);
|
||||
let cancellation = config.cancellation_token.clone();
|
||||
let sessions = Arc::new(LocalSessionManager::default());
|
||||
let handlers = TaskTracker::new();
|
||||
// Track the factory even when a connection never creates an MCP handler.
|
||||
// The tuple drops the binding before its completion token.
|
||||
let binding = (bind, handlers.token());
|
||||
let shutdown = cancellation.clone();
|
||||
let app = Router::new()
|
||||
.nest_service(
|
||||
"/mcp",
|
||||
StreamableHttpService::new(
|
||||
move || {
|
||||
let (bind, lifetime) = binding.clone();
|
||||
Ok(HttpServer {
|
||||
bind,
|
||||
invocation_scope: uuid::Uuid::now_v7().to_string(),
|
||||
cancellation: shutdown.clone(),
|
||||
_lifetime: lifetime,
|
||||
})
|
||||
},
|
||||
sessions.clone(),
|
||||
config,
|
||||
),
|
||||
)
|
||||
.layer(middleware::from_fn(move |request: Request, next: Next| {
|
||||
let authorization = authorization.clone();
|
||||
async move {
|
||||
if request.headers().get(AUTHORIZATION) != Some(&authorization) {
|
||||
return Err(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
Ok(next.run(request).await)
|
||||
}
|
||||
}));
|
||||
let result = axum::serve(listener, app)
|
||||
.with_graceful_shutdown(cancellation.clone().cancelled_owned())
|
||||
.await;
|
||||
cancellation.cancel();
|
||||
// HTTP has drained, so no new sessions can be registered. rmcp's HTTP token
|
||||
// does not stop legacy session workers; explicitly close their transports.
|
||||
let sessions = std::mem::take(&mut *sessions.sessions.write().await);
|
||||
for session in sessions.into_values() {
|
||||
// The only close error means the worker has already terminated.
|
||||
let _ = session.close().await;
|
||||
}
|
||||
// close() only queues a message. Wait for the factory, services, and outstanding
|
||||
// calls to drop their bindings, including calls from already-removed sessions.
|
||||
handlers.close();
|
||||
handlers.wait().await;
|
||||
result.map_err(Into::into)
|
||||
}
|
||||
|
||||
struct HttpServer<F> {
|
||||
bind: F,
|
||||
invocation_scope: String,
|
||||
cancellation: CancellationToken,
|
||||
// Drop last so shutdown cannot return before the binding releases its state.
|
||||
_lifetime: TaskTrackerToken,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Caller {
|
||||
thread_id: ThreadId,
|
||||
session_id: SessionId,
|
||||
}
|
||||
|
||||
impl<F, Fut> ServerHandler for HttpServer<F>
|
||||
where
|
||||
F: Fn(ThreadId, SessionId) -> Fut + Send + Sync + 'static,
|
||||
Fut: Future<Output = Result<MessageBoardMcpServer, ErrorData>> + Send + 'static,
|
||||
{
|
||||
fn get_info(&self) -> ServerConfig {
|
||||
server_info()
|
||||
}
|
||||
|
||||
async fn list_tools(
|
||||
&self,
|
||||
request: Option<PaginatedRequestParams>,
|
||||
_context: RequestContext<RoleServer>,
|
||||
) -> Result<ListToolsResult, ErrorData> {
|
||||
list_tools_result(
|
||||
request,
|
||||
MessageBoardTool::DISCUSSION
|
||||
.into_iter()
|
||||
.map(MessageBoardTool::spec),
|
||||
)
|
||||
}
|
||||
|
||||
async fn call_tool(
|
||||
&self,
|
||||
request: CallToolRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResponse, ErrorData> {
|
||||
let caller: Caller = serde_json::from_value(serde_json::Value::Object(
|
||||
context.meta.0.0.clone(),
|
||||
))
|
||||
.map_err(|_| {
|
||||
ErrorData::invalid_params(
|
||||
"Calls require threadId and sessionId metadata",
|
||||
/*data*/ None,
|
||||
)
|
||||
})?;
|
||||
let mut adapter = tokio::select! {
|
||||
biased;
|
||||
_ = self.cancellation.cancelled() => {
|
||||
return Err(ErrorData::internal_error("Message-board server is shutting down", /*data*/ None));
|
||||
}
|
||||
adapter = async { (self.bind)(caller.thread_id, caller.session_id).await } => adapter?,
|
||||
};
|
||||
// Preserve retry identity across calls in this MCP session, scoped to the caller.
|
||||
adapter.invocation_scope = format!("{}:{}", self.invocation_scope, caller.thread_id);
|
||||
adapter.call_tool(request, context).await
|
||||
}
|
||||
}
|
||||
186
akode-rs/message-board-mcp/src/lib.rs
Normal file
186
akode-rs/message-board-mcp/src/lib.rs
Normal file
@@ -0,0 +1,186 @@
|
||||
//! MCP adapters and HTTP transport for existing board tools.
|
||||
//! Bound adapters fix caller identity; HTTP validates it against the configured host.
|
||||
//! Storage, permissions and notification delivery remain owned by the board.
|
||||
|
||||
mod http;
|
||||
mod local;
|
||||
|
||||
pub use http::serve_http;
|
||||
pub use local::LocalServer;
|
||||
pub use local::launch_in_memory;
|
||||
|
||||
use akode_attachment_store::InlineAttachmentStore;
|
||||
use akode_message_board::AgentMessageBoard;
|
||||
use akode_message_board::MessageBoardTool;
|
||||
use akode_message_board::message_board_tools;
|
||||
use akode_protocol::AgentPath;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_tools::ConversationHistory;
|
||||
use akode_tools::FunctionCallError;
|
||||
use akode_tools::NoopTurnItemEmitter;
|
||||
use akode_tools::ToolCall;
|
||||
use akode_tools::ToolCallSource;
|
||||
use akode_tools::ToolExecutor;
|
||||
use akode_tools::ToolPayload;
|
||||
use akode_tools::ToolSpec;
|
||||
use akode_utils_output_truncation::TruncationPolicy;
|
||||
use rmcp::ErrorData;
|
||||
use rmcp::ServerHandler;
|
||||
use rmcp::model::CallToolRequestParams;
|
||||
use rmcp::model::CallToolResponse;
|
||||
use rmcp::model::CallToolResult;
|
||||
use rmcp::model::ContentBlock;
|
||||
use rmcp::model::Implementation;
|
||||
use rmcp::model::ListToolsResult;
|
||||
use rmcp::model::PaginatedRequestParams;
|
||||
use rmcp::model::ServerCapabilities;
|
||||
use rmcp::model::ServerConfig;
|
||||
use rmcp::model::Tool;
|
||||
use rmcp::service::RequestContext;
|
||||
use rmcp::service::RoleServer;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// A caller-bound MCP service, usable with any `rmcp` server transport.
|
||||
///
|
||||
/// Create one instance per MCP session. The host must authenticate the caller
|
||||
/// and supply its authoritative path and board connection; request arguments or
|
||||
/// metadata never select an identity. Selecting tools does not grant permissions.
|
||||
/// The board's host continues to handle notifications; this service adds no
|
||||
/// Core delivery, lifecycle registration, or MCP push notifications.
|
||||
pub struct MessageBoardMcpServer {
|
||||
tools: Vec<Arc<dyn for<'call> ToolExecutor<ToolCall<'call>>>>,
|
||||
invocation_scope: String,
|
||||
}
|
||||
|
||||
impl MessageBoardMcpServer {
|
||||
pub fn new(
|
||||
tools: &[MessageBoardTool],
|
||||
board: Arc<dyn AgentMessageBoard>,
|
||||
caller: ThreadId,
|
||||
caller_path: AgentPath,
|
||||
) -> Self {
|
||||
Self {
|
||||
tools: message_board_tools(
|
||||
tools,
|
||||
board,
|
||||
caller,
|
||||
caller_path,
|
||||
/*namespace*/ None,
|
||||
/*namespace_description*/ "",
|
||||
/*tool_messages*/ None,
|
||||
),
|
||||
// JSON-RPC request IDs are connection-local, unlike board request IDs.
|
||||
invocation_scope: Uuid::now_v7().to_string(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ServerHandler for MessageBoardMcpServer {
|
||||
fn get_info(&self) -> ServerConfig {
|
||||
server_info()
|
||||
}
|
||||
|
||||
async fn list_tools(
|
||||
&self,
|
||||
request: Option<PaginatedRequestParams>,
|
||||
_context: RequestContext<RoleServer>,
|
||||
) -> Result<ListToolsResult, ErrorData> {
|
||||
list_tools_result(request, self.tools.iter().map(|executor| executor.spec()))
|
||||
}
|
||||
|
||||
async fn call_tool(
|
||||
&self,
|
||||
request: CallToolRequestParams,
|
||||
context: RequestContext<RoleServer>,
|
||||
) -> Result<CallToolResponse, ErrorData> {
|
||||
let executor = self
|
||||
.tools
|
||||
.iter()
|
||||
.find(|executor| executor.tool_name().name == request.name)
|
||||
.ok_or_else(|| {
|
||||
ErrorData::invalid_params("Unknown message-board tool", /*data*/ None)
|
||||
})?;
|
||||
// Serialization preserves the distinction between numeric and string IDs.
|
||||
let call_id = serde_json::to_string(&context.id).map_err(|_| {
|
||||
ErrorData::internal_error("Invalid MCP request ID", /*data*/ None)
|
||||
})?;
|
||||
let payload = ToolPayload::Function {
|
||||
arguments: serde_json::Value::Object(request.arguments.unwrap_or_default()).to_string(),
|
||||
};
|
||||
let call = ToolCall {
|
||||
turn_id: self.invocation_scope.clone(),
|
||||
call_id,
|
||||
tool_name: executor.tool_name(),
|
||||
model: String::new(),
|
||||
codex_turn_metadata: None,
|
||||
// Let the shared handler impose its existing response budget.
|
||||
truncation_policy: TruncationPolicy::Bytes(usize::MAX),
|
||||
source: ToolCallSource::Direct,
|
||||
conversation_history: ConversationHistory::default(),
|
||||
turn_item_emitter: Arc::new(NoopTurnItemEmitter),
|
||||
attachment_store: Arc::new(InlineAttachmentStore),
|
||||
ephemeral: false,
|
||||
environments: Vec::new(),
|
||||
payload: payload.clone(),
|
||||
};
|
||||
let result = match executor.handle(call).await {
|
||||
Ok(output) => {
|
||||
let value = output.code_mode_result(&payload);
|
||||
let mut result = if value.is_object() {
|
||||
CallToolResult::structured(value)
|
||||
} else {
|
||||
// Legacy MCP structuredContent must be an object (upsert returns null).
|
||||
CallToolResult::success(vec![ContentBlock::text(value.to_string())])
|
||||
};
|
||||
result.is_error = Some(!output.success_for_logging());
|
||||
result
|
||||
}
|
||||
Err(FunctionCallError::RespondToModel(message)) => {
|
||||
CallToolResult::error(vec![ContentBlock::text(message)])
|
||||
}
|
||||
Err(FunctionCallError::Fatal(_)) => {
|
||||
return Err(ErrorData::internal_error(
|
||||
"Message-board tool failed",
|
||||
/*data*/ None,
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(result.into())
|
||||
}
|
||||
}
|
||||
|
||||
fn server_info() -> ServerConfig {
|
||||
ServerConfig::new(ServerCapabilities::builder().enable_tools().build()).with_server_info(
|
||||
Implementation::new("akode-message-board", env!("CARGO_PKG_VERSION")),
|
||||
)
|
||||
}
|
||||
|
||||
fn list_tools_result(
|
||||
request: Option<PaginatedRequestParams>,
|
||||
specs: impl Iterator<Item = ToolSpec>,
|
||||
) -> Result<ListToolsResult, ErrorData> {
|
||||
if request.is_some_and(|request| request.cursor.is_some()) {
|
||||
return Err(ErrorData::invalid_params(
|
||||
"Message-board tools do not use pagination cursors",
|
||||
/*data*/ None,
|
||||
));
|
||||
}
|
||||
let tools = specs
|
||||
.map(|spec| {
|
||||
let ToolSpec::Function(spec) = spec else {
|
||||
return Err(ErrorData::internal_error(
|
||||
"Message-board tool is not a function",
|
||||
/*data*/ None,
|
||||
));
|
||||
};
|
||||
let schema = serde_json::to_value(spec.parameters)
|
||||
.and_then(serde_json::from_value)
|
||||
.map_err(|_| {
|
||||
ErrorData::internal_error("Invalid message-board schema", /*data*/ None)
|
||||
})?;
|
||||
Ok(Tool::new(spec.name, spec.description, Arc::new(schema)))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
Ok(ListToolsResult::with_all_items(tools))
|
||||
}
|
||||
157
akode-rs/message-board-mcp/src/local.rs
Normal file
157
akode-rs/message-board-mcp/src/local.rs
Normal file
@@ -0,0 +1,157 @@
|
||||
//! Runner-owned HTTP lifecycle over the existing in-memory board and host interfaces.
|
||||
//! Agent-specific bindings share tree state while retaining each caller's host.
|
||||
|
||||
use crate::MessageBoardMcpServer;
|
||||
use crate::serve_http;
|
||||
use axum::http::HeaderValue;
|
||||
use akode_message_board::AgentMessageBoard;
|
||||
use akode_message_board::InMemoryAgentMessageBoard;
|
||||
use akode_message_board::InMemoryMessageBoards;
|
||||
use akode_message_board::MessageBoardHost;
|
||||
use akode_message_board::MessageBoardTool;
|
||||
use akode_protocol::SessionId;
|
||||
use akode_protocol::ThreadId;
|
||||
use rmcp::ErrorData;
|
||||
use rmcp::transport::StreamableHttpServerConfig;
|
||||
use std::collections::HashMap;
|
||||
use std::sync::Arc;
|
||||
use std::sync::RwLock;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio::task::JoinHandle;
|
||||
use tokio_util::sync::CancellationToken;
|
||||
|
||||
type BoardBinding = (Arc<dyn AgentMessageBoard>, Arc<dyn MessageBoardHost>);
|
||||
type Boards = Arc<RwLock<HashMap<(SessionId, Option<ThreadId>), BoardBinding>>>;
|
||||
|
||||
/// One runner-owned endpoint. Dropping it initiates HTTP and MCP session cleanup.
|
||||
/// Call [`Self::shutdown`] to wait until that cleanup has finished.
|
||||
/// Credentials are deliberately excluded from Debug and startup output.
|
||||
pub struct LocalServer {
|
||||
url: String,
|
||||
authorization: HeaderValue,
|
||||
boards: Boards,
|
||||
states: InMemoryMessageBoards,
|
||||
cancellation: CancellationToken,
|
||||
task: Option<JoinHandle<anyhow::Result<()>>>,
|
||||
}
|
||||
|
||||
impl LocalServer {
|
||||
pub fn url(&self) -> &str {
|
||||
&self.url
|
||||
}
|
||||
|
||||
pub fn authorization(&self) -> &HeaderValue {
|
||||
&self.authorization
|
||||
}
|
||||
|
||||
/// Registers a tree before its first tool call. The runner supplies authoritative
|
||||
/// membership and clocks; the service never registers or spawns agents itself.
|
||||
pub fn add_board(
|
||||
&self,
|
||||
identity: SessionId,
|
||||
host: Arc<dyn MessageBoardHost>,
|
||||
) -> anyhow::Result<()> {
|
||||
let mut boards = self
|
||||
.boards
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
anyhow::ensure!(
|
||||
!boards.keys().any(|(tree, _)| *tree == identity),
|
||||
"board session already registered"
|
||||
);
|
||||
boards.insert(
|
||||
(identity, None),
|
||||
(
|
||||
Arc::new(InMemoryAgentMessageBoard::new(identity, host.clone())),
|
||||
host,
|
||||
),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Binds one caller's host to shared tree state, instead of using a tree-wide host.
|
||||
pub async fn bind_agent(
|
||||
&self,
|
||||
identity: SessionId,
|
||||
caller: ThreadId,
|
||||
host: Arc<dyn MessageBoardHost>,
|
||||
) -> anyhow::Result<()> {
|
||||
let board = self.states.open(identity, host.clone()).await;
|
||||
let mut boards = self
|
||||
.boards
|
||||
.write()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
anyhow::ensure!(
|
||||
!boards.contains_key(&(identity, None)),
|
||||
"board session already has a tree-wide host"
|
||||
);
|
||||
boards.insert((identity, Some(caller)), (Arc::new(board), host));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Closes sessions, cancels pending bindings, and drains dispatched board operations.
|
||||
pub async fn shutdown(mut self) -> anyhow::Result<()> {
|
||||
self.cancellation.cancel();
|
||||
if let Some(task) = self.task.take() {
|
||||
task.await??;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for LocalServer {
|
||||
fn drop(&mut self) {
|
||||
self.cancellation.cancel();
|
||||
}
|
||||
}
|
||||
|
||||
/// Binds a loopback endpoint for a local run. Register hosts before tool calls.
|
||||
/// All connections for a tree share one board; the last owner releases its state.
|
||||
pub async fn launch_in_memory() -> anyhow::Result<LocalServer> {
|
||||
let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0)).await?;
|
||||
let url = format!("http://{}/mcp", listener.local_addr()?);
|
||||
let token = uuid::Uuid::new_v4().to_string();
|
||||
let mut authorization = HeaderValue::from_str(&format!("Bearer {token}"))?;
|
||||
authorization.set_sensitive(true);
|
||||
let boards = Boards::default();
|
||||
let binding = boards.clone();
|
||||
let cancellation = CancellationToken::new();
|
||||
let task = tokio::spawn(serve_http(
|
||||
listener,
|
||||
token,
|
||||
StreamableHttpServerConfig::default().with_cancellation_token(cancellation.clone()),
|
||||
move |caller, session_id| {
|
||||
let board = {
|
||||
let boards = binding
|
||||
.read()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
boards
|
||||
.get(&(session_id, Some(caller)))
|
||||
.or_else(|| boards.get(&(session_id, None)))
|
||||
.cloned()
|
||||
};
|
||||
async move {
|
||||
let (board, host) = board.ok_or_else(|| {
|
||||
ErrorData::invalid_params("Unknown board session", /*data*/ None)
|
||||
})?;
|
||||
let path = host.agent_path(caller).await.map_err(|error| {
|
||||
ErrorData::invalid_params(error.to_string(), /*data*/ None)
|
||||
})?;
|
||||
Ok(MessageBoardMcpServer::new(
|
||||
&MessageBoardTool::DISCUSSION,
|
||||
board,
|
||||
caller,
|
||||
path,
|
||||
))
|
||||
}
|
||||
},
|
||||
));
|
||||
Ok(LocalServer {
|
||||
url,
|
||||
authorization,
|
||||
boards,
|
||||
states: InMemoryMessageBoards::default(),
|
||||
cancellation,
|
||||
task: Some(task),
|
||||
})
|
||||
}
|
||||
99
akode-rs/message-board-mcp/src/main.rs
Normal file
99
akode-rs/message-board-mcp/src/main.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
//! Detached HTTP entry point; endpoint configuration and process lifetime belong to the deployer.
|
||||
|
||||
mod persisted;
|
||||
|
||||
use clap::Parser;
|
||||
use akode_message_board::LocalAgentMessageBoard;
|
||||
use akode_message_board::LocalBoardOptions;
|
||||
use akode_message_board::MessageBoardHost;
|
||||
use akode_message_board::MessageBoardTool;
|
||||
use akode_message_board_mcp::MessageBoardMcpServer;
|
||||
use akode_state::SqliteConfig;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use rmcp::ErrorData;
|
||||
use rmcp::transport::StreamableHttpServerConfig;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[derive(Parser)]
|
||||
struct Args {
|
||||
/// Absolute directory containing Codex's state and message-board databases.
|
||||
#[arg(long)]
|
||||
sqlite_home: std::path::PathBuf,
|
||||
#[arg(long, default_value = "127.0.0.1:7777")]
|
||||
listen: std::net::SocketAddr,
|
||||
/// Additional allowed HTTP Host names or host:port authorities. Loopback remains allowed.
|
||||
#[arg(long = "allowed-host")]
|
||||
allowed_hosts: Vec<String>,
|
||||
/// Name of the environment variable containing the trusted-host bearer token.
|
||||
#[arg(long, default_value = "AKODE_MESSAGE_BOARD_TOKEN")]
|
||||
bearer_token_env: String,
|
||||
}
|
||||
|
||||
#[tokio::main(flavor = "current_thread")]
|
||||
async fn main() -> anyhow::Result<()> {
|
||||
let args = Args::parse();
|
||||
let token = std::env::var(&args.bearer_token_env).map_err(|_| {
|
||||
anyhow::anyhow!("MCP bearer token environment variable is missing or invalid")
|
||||
})?;
|
||||
let sqlite = SqliteConfig::from_sqlite_home_with_nfs_enforcement(
|
||||
AbsolutePathBuf::try_from(args.sqlite_home)?,
|
||||
/*enforce_delete_on_nfs*/ false,
|
||||
);
|
||||
let registry = sqlite
|
||||
.open_read_only_pool(&sqlite.state_db_path(), /*busy_timeout*/ None)
|
||||
.await?;
|
||||
let listener = tokio::net::TcpListener::bind(args.listen).await?;
|
||||
println!(
|
||||
"{}",
|
||||
serde_json::json!({"url": format!("http://{}/mcp", listener.local_addr()?)})
|
||||
);
|
||||
let cancellation = tokio_util::sync::CancellationToken::new();
|
||||
let mut http =
|
||||
StreamableHttpServerConfig::default().with_cancellation_token(cancellation.clone());
|
||||
http.allowed_hosts.extend(args.allowed_hosts);
|
||||
// All sessions share one SQLite file. Retain a board between calls so the
|
||||
// weak pool registry reuses its connections instead of initializing again.
|
||||
let pool_owner = Arc::new(Mutex::new(None));
|
||||
let serving =
|
||||
akode_message_board_mcp::serve_http(listener, token, http, move |caller, session_id| {
|
||||
let pool_owner = Arc::clone(&pool_owner);
|
||||
let sqlite = sqlite.clone();
|
||||
let host = Arc::new(persisted::PersistedHost {
|
||||
registry: registry.clone(),
|
||||
root: session_id.into(),
|
||||
});
|
||||
async move {
|
||||
let path = host.agent_path(caller).await.map_err(|error| {
|
||||
ErrorData::invalid_params(error.to_string(), /*data*/ None)
|
||||
})?;
|
||||
let board = LocalAgentMessageBoard::open(
|
||||
&sqlite,
|
||||
&LocalBoardOptions::default(),
|
||||
session_id,
|
||||
host,
|
||||
)
|
||||
.await
|
||||
.map_err(|error| {
|
||||
ErrorData::internal_error(error.to_string(), /*data*/ None)
|
||||
})?;
|
||||
*pool_owner
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner) = Some(board.clone());
|
||||
Ok(MessageBoardMcpServer::new(
|
||||
&MessageBoardTool::DISCUSSION,
|
||||
Arc::new(board),
|
||||
caller,
|
||||
path,
|
||||
))
|
||||
}
|
||||
});
|
||||
tokio::pin!(serving);
|
||||
tokio::select! {
|
||||
result = &mut serving => result,
|
||||
_ = tokio::signal::ctrl_c() => {
|
||||
cancellation.cancel();
|
||||
serving.await
|
||||
}
|
||||
}
|
||||
}
|
||||
99
akode-rs/message-board-mcp/src/persisted.rs
Normal file
99
akode-rs/message-board-mcp/src/persisted.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
//! Reads persisted membership without starting runtimes or modifying Codex's registry.
|
||||
//! Standalone posts use system time; Core notification delivery is a separate integration.
|
||||
|
||||
use chrono::DateTime;
|
||||
use chrono::Utc;
|
||||
use akode_message_board::MessageBoardHost;
|
||||
use akode_message_board::NotificationDelivery;
|
||||
use akode_message_board::PostPreview;
|
||||
use akode_protocol::AgentPath;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::error::CodexErr;
|
||||
use akode_protocol::error::Result;
|
||||
use futures::future::BoxFuture;
|
||||
use sqlx::SqlitePool;
|
||||
|
||||
pub(super) struct PersistedHost {
|
||||
pub registry: SqlitePool,
|
||||
pub root: ThreadId,
|
||||
}
|
||||
|
||||
impl MessageBoardHost for PersistedHost {
|
||||
fn agent_path(&self, caller: ThreadId) -> BoxFuture<'_, Result<AgentPath>> {
|
||||
Box::pin(async move {
|
||||
let stored: Option<Option<String>> =
|
||||
sqlx::query_scalar("SELECT agent_path FROM threads WHERE id = ?")
|
||||
.bind(caller.to_string())
|
||||
.fetch_optional(&self.registry)
|
||||
.await
|
||||
.map_err(storage_error)?;
|
||||
let path = match stored.ok_or(CodexErr::ThreadNotFound(caller))? {
|
||||
Some(path) => AgentPath::from_string(path).map_err(CodexErr::InvalidRequest)?,
|
||||
None if caller == self.root => AgentPath::root(),
|
||||
None => {
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"caller has no persisted agent path".into(),
|
||||
));
|
||||
}
|
||||
};
|
||||
if self.resolve_agent(path.clone()).await? != caller {
|
||||
return Err(CodexErr::InvalidRequest(
|
||||
"caller does not belong to this board".into(),
|
||||
));
|
||||
}
|
||||
Ok(path)
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_agent(&self, path: AgentPath) -> BoxFuture<'_, Result<ThreadId>> {
|
||||
Box::pin(async move {
|
||||
let ids: Vec<String> = sqlx::query_scalar(
|
||||
r#"
|
||||
WITH RECURSIVE tree(id) AS (
|
||||
SELECT id FROM threads WHERE id = ?
|
||||
UNION
|
||||
SELECT child_thread_id FROM thread_spawn_edges JOIN tree ON parent_thread_id = tree.id
|
||||
)
|
||||
SELECT threads.id FROM tree JOIN threads ON threads.id = tree.id
|
||||
WHERE (threads.id = ? AND ? = '/root' AND (agent_path IS NULL OR agent_path = '/root'))
|
||||
OR (threads.id != ? AND agent_path = ?)
|
||||
LIMIT 2
|
||||
"#,
|
||||
)
|
||||
.bind(self.root.to_string())
|
||||
.bind(self.root.to_string())
|
||||
.bind(path.as_str())
|
||||
.bind(self.root.to_string())
|
||||
.bind(path.as_str())
|
||||
.fetch_all(&self.registry)
|
||||
.await
|
||||
.map_err(storage_error)?;
|
||||
match ids.as_slice() {
|
||||
[id] => ThreadId::from_string(id)
|
||||
.map_err(|error| CodexErr::InvalidRequest(error.to_string())),
|
||||
_ => Err(CodexErr::InvalidRequest(
|
||||
"unknown or ambiguous agent path in this board".into(),
|
||||
)),
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
fn current_time(&self, caller: ThreadId) -> BoxFuture<'_, Result<DateTime<Utc>>> {
|
||||
Box::pin(async move {
|
||||
self.agent_path(caller).await?;
|
||||
Ok(Utc::now())
|
||||
})
|
||||
}
|
||||
|
||||
fn notify(
|
||||
&self,
|
||||
_recipient: ThreadId,
|
||||
_post: PostPreview,
|
||||
) -> BoxFuture<'_, Result<NotificationDelivery>> {
|
||||
Box::pin(async { Ok(NotificationDelivery::SkippedInactive) })
|
||||
}
|
||||
}
|
||||
|
||||
fn storage_error(error: sqlx::Error) -> CodexErr {
|
||||
CodexErr::Io(std::io::Error::other(error))
|
||||
}
|
||||
Reference in New Issue
Block a user