//! 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 ToolExecutor>>>, invocation_scope: String, } impl MessageBoardMcpServer { pub fn new( tools: &[MessageBoardTool], board: Arc, 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, _context: RequestContext, ) -> Result { list_tools_result(request, self.tools.iter().map(|executor| executor.spec())) } async fn call_tool( &self, request: CallToolRequestParams, context: RequestContext, ) -> Result { 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, specs: impl Iterator, ) -> Result { 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::, _>>()?; Ok(ListToolsResult::with_all_items(tools)) }