The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
feat(mcp): serve HTTP and stdio through module-owned sessions
Steven Enamakelefaa91054441
diff --git a/crates/openhuman-core/src/mcp/server/http.rs b/crates/openhuman-core/src/mcp/server/http.rsindex f873d1357c..ec98b1da4f 100644--- a/crates/openhuman-core/src/mcp/server/http.rs+++ b/crates/openhuman-core/src/mcp/server/http.rs@@ -1,31 +1,334 @@-//! OpenHuman's Streamable HTTP + SSE MCP server.-//!-//! The transport is `tinymcp`'s (`tinymcp::run_http`, behind its-//! `server-http` feature, which OpenHuman's `http-server` gate forwards). These-//! entry points bind it to OpenHuman's handler, so callers keep the-//! handler-free signatures this module always had.+//! OpenHuman's thin Streamable HTTP adapter over TinyMCP's server contract.-use std::net::SocketAddr;+use std::{+ collections::HashMap,+ convert::Infallible,+ net::SocketAddr,+ sync::Arc,+ time::Duration,+};-use anyhow::Result;+use axum::{+ body::Bytes,+ extract::State,+ http::{header::AUTHORIZATION, HeaderMap, HeaderName, HeaderValue, StatusCode},+ response::{sse::{Event, KeepAlive, Sse}, IntoResponse, Response},+ routing::post,+ Router,+};+use futures_util::stream;+use serde_json::{Map, Value};+use tinymcp_bus::{+ names, ServerHttpSessionMethod, ServerHttpSessionRequest, HEADER_PROTOCOL_VERSION,+ HEADER_SESSION_ID,+};-pub use tinymcp::HttpServerConfig;+use crate::{config::Config, modules::client::ModuleCallError};-use super::handler::handler;+use super::module::{headers_object, ServerError, ServerPort, ServerSession};-/// Serves OpenHuman's MCP surface over HTTP until the server stops.-pub async fn run_http(config: HttpServerConfig) -> Result<()> {+/// HTTP listener configuration kept at OpenHuman's transport boundary.+#[derive(Debug, Clone)]+pub struct HttpServerConfig {+ pub bind_addr: SocketAddr,+ pub auth_token: Option<String>,+}++#[derive(Clone)]+struct HttpState {+ port: Arc<dyn ServerPort>,+ config: Config,+ auth_token: Option<String>,+ sessions: Arc<tokio::sync::Mutex<HashMap<String, Arc<tokio::sync::Mutex<ServerSession>>>>>,+}++/// Serve the OpenHuman MCP surface over module-owned HTTP protocol state.+pub async fn run_http(config: HttpServerConfig) -> anyhow::Result<()> {run_http_reporting(config, None).await}-/// Like [`run_http`] but reports the actually-bound [`SocketAddr`] through-/// `ready` once the listener is up. Needed when binding an ephemeral port-/// (`127.0.0.1:0`) so the caller can learn the chosen port (e.g. to hand the-/// URL to a local MCP client).+/// Serve the endpoint and report the bound address after the listener is ready.pub async fn run_http_reporting(config: HttpServerConfig,ready: Option<tokio::sync::oneshot::Sender<SocketAddr>>,-) -> Result<()> {- tinymcp::run_http_reporting(handler(), config, ready).await?;- Ok(())+) -> anyhow::Result<()> {+ let host_config = Config::load_or_init().await?;+ let port = ServerSession::port_for_config(&host_config);+ let state = HttpState {+ port,+ config: host_config,+ auth_token: config.auth_token,+ sessions: Arc::default(),+ };+ let listener = tokio::net::TcpListener::bind(config.bind_addr).await?;+ let local_addr = listener.local_addr()?;+ if let Some(sender) = ready {+ let _ = sender.send(local_addr);+ }+ let result = axum::serve(listener, router(state.clone())).await;+ close_http_sessions(&state).await;+ result.map_err(anyhow::Error::from)+}++fn router(state: HttpState) -> Router {+ Router::new()+ .route("/", post(handle_post).get(handle_get).delete(handle_delete))+ .with_state(state)+}++async fn handle_post(State(state): State<HttpState>, headers: HeaderMap, body: Bytes) -> Response {+ if let Some(response) = check_auth(&state, &headers) {+ return response;+ }+ let line = match String::from_utf8(body.to_vec()) {+ Ok(line) => line,+ Err(_) => return text_error(StatusCode::BAD_REQUEST, "invalid request body"),+ };+ let requested_session_id = header_value(&headers, HEADER_SESSION_ID).map(str::to_owned);+ let session = requested_session_id+ .as_deref()+ .and_then(|id| state.sessions.try_lock().ok()?.get(id).cloned());+ let known_session = session.is_some();+ let session = match session {+ Some(session) => session,+ None => match ServerSession::open_http(+ Arc::clone(&state.port),+ requested_session_id.clone(),+ false,+ None,+ )+ .await+ {+ Ok(session) => Arc::new(tokio::sync::Mutex::new(session)),+ Err(error) => return server_error(error),+ },+ };+ let is_temporary = !known_session;+ let protocol = session.lock().await;+ let response = match protocol+ .submit(+ request_headers(&headers),+ line,+ &tokio_util::sync::CancellationToken::new(),+ )+ .await+ {+ Ok(snapshot) => http_operation_response(&state, &protocol, snapshot).await,+ Err(error) => server_error(error),+ };+ if is_temporary {+ let wire_id = response+ .headers()+ .get(HEADER_SESSION_ID)+ .and_then(|header| header.to_str().ok())+ .map(str::to_owned);+ if let Some(wire_id) = wire_id {+ state+ .sessions+ .lock()+ .await+ .insert(wire_id, Arc::clone(&session));+ } else if let Err(error) = protocol.close().await {+ tracing::warn!(?error, "[mcp_server] temporary HTTP session cleanup failed");+ }+ }+ response+}++async fn http_operation_response(+ state: &HttpState,+ session: &ServerSession,+ snapshot: tinymcp_bus::ServerOperationSnapshot,+) -> Response {+ let Some(metadata) = snapshot.http_response else {+ return server_error(ServerError::MissingHttpMetadata);+ };+ let body = match snapshot.state {+ tinymcp_bus::ServerOperationState::Complete { response } => response.unwrap_or_default(),+ _ => String::new(),+ };+ let mut response = response_from_metadata(metadata, body);+ if let Some(wire_id) = response+ .headers()+ .get(HEADER_SESSION_ID)+ .and_then(|header| header.to_str().ok())+ .map(str::to_owned)+ {+ if let Ok(metadata) = session.metadata().await {+ // The protocol version is retained by the module. Asking it here+ // validates that the response's new transport session is ready.+ if metadata.initialized && metadata.protocol_version.is_some() {+ tracing::debug!("[mcp_server] HTTP session initialized id={}", redact_id(&wire_id));+ }+ }+ let _ = state;+ }+ response+}++async fn handle_get(State(state): State<HttpState>, headers: HeaderMap) -> Response {+ http_session_request(&state, &headers, ServerHttpSessionMethod::Get).await+}++async fn handle_delete(State(state): State<HttpState>, headers: HeaderMap) -> Response {+ http_session_request(&state, &headers, ServerHttpSessionMethod::Delete).await+}++async fn http_session_request(+ state: &HttpState,+ headers: &HeaderMap,+ method: ServerHttpSessionMethod,+) -> Response {+ if let Some(response) = check_auth(state, headers) {+ return response;+ }+ let requested_session_id = header_value(headers, HEADER_SESSION_ID).map(str::to_owned);+ let session = requested_session_id+ .as_deref()+ .and_then(|id| state.sessions.try_lock().ok()?.get(id).cloned());+ let internal_session_id = session.as_ref().map(|session| {+ // The state entry was made only from a completed initialization whose+ // module-created session ID is retained in this client session.+ session+ .try_lock()+ .map(|session| session.id().to_owned())+ .unwrap_or_default()+ });+ let request = ServerHttpSessionRequest {+ method: method.clone(),+ requested_session_id: requested_session_id.clone(),+ internal_session_id: internal_session_id.clone(),+ headers: request_headers(headers),+ };+ let metadata = match state.port.http_session(request).await {+ Ok(metadata) => metadata,+ Err(error) => return server_error(ServerError::Module(error)),+ };+ let response = response_from_metadata(metadata, String::new());+ if method == ServerHttpSessionMethod::Get && response.status() == StatusCode::OK {+ return Sse::new(stream::pending::<Result<Event, Infallible>>()).keep_alive(+ KeepAlive::new()+ .interval(Duration::from_secs(10))+ .text("keepalive"),+ )+ .into_response();+ }+ if method == ServerHttpSessionMethod::Delete && response.status() == StatusCode::NO_CONTENT {+ if let Some(requested_session_id) = requested_session_id {+ state.sessions.lock().await.remove(&requested_session_id);+ }+ }+ response+}++async fn close_http_sessions(state: &HttpState) {+ let sessions = std::mem::take(&mut *state.sessions.lock().await);+ for (_, session) in sessions {+ if let Err(error) = session.lock().await.close().await {+ tracing::warn!(?error, "[mcp_server] HTTP session cleanup failed");+ }+ }+}++fn check_auth(state: &HttpState, headers: &HeaderMap) -> Option<Response> {+ let expected = state.auth_token.as_deref()?;+ let provided = header_value(headers, AUTHORIZATION)+ .and_then(|value| value.strip_prefix("Bearer "))+ .map(str::trim);+ (provided != Some(expected)).then(|| {+ (+ StatusCode::UNAUTHORIZED,+ [("content-type", "text/plain")],+ "unauthorized",+ )+ .into_response()+ })+}++fn request_headers(headers: &HeaderMap) -> Map<String, Value> {+ headers_object(headers.iter().filter_map(|(name, value)| {+ value+ .to_str()+ .ok()+ .map(|value| (name.as_str().to_ascii_lowercase(), value.to_owned()))+ }))+}++fn response_from_metadata(+ metadata: tinymcp_bus::ServerHttpResponseMetadata,+ body: String,+) -> Response {+ let status = StatusCode::from_u16(metadata.status_code)+ .unwrap_or(StatusCode::INTERNAL_SERVER_ERROR);+ let mut response = if let Some(error_body) = metadata.error_body {+ (status, error_body).into_response()+ } else if body.is_empty() {+ status.into_response()+ } else {+ (status, [("content-type", "application/json")], body).into_response()+ };+ for (name, value) in metadata.headers {+ if let (Ok(name), Ok(value)) = (+ HeaderName::from_bytes(name.as_bytes()),+ HeaderValue::from_str(&value),+ ) {+ response.headers_mut().insert(name, value);+ }+ }+ if let Some(content_type) = metadata.content_type {+ if let Ok(value) = HeaderValue::from_str(&content_type) {+ response.headers_mut().insert(axum::http::header::CONTENT_TYPE, value);+ }+ }+ response+}++fn server_error(error: ServerError) -> Response {+ let status = match error {+ ServerError::Module(ModuleCallError::Unavailable) => StatusCode::SERVICE_UNAVAILABLE,+ ServerError::Module(_) => StatusCode::BAD_GATEWAY,+ _ => StatusCode::INTERNAL_SERVER_ERROR,+ };+ text_error(status, "MCP server unavailable")+}++fn text_error(status: StatusCode, body: &'static str) -> Response {+ (+ status,+ [("content-type", "text/plain; charset=utf-8")],+ body,+ )+ .into_response()+}++fn header_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {+ headers.get(name).and_then(|value| value.to_str().ok())+}++fn redact_id(id: &str) -> String {+ use sha2::{Digest, Sha256};+ let digest = Sha256::digest(id.as_bytes());+ format!("sha256:{:02x}{:02x}{:02x}{:02x}", digest[0], digest[1], digest[2], digest[3])+}++pub(super) async fn run_http_with_port_for_test(+ config: HttpServerConfig,+ port: Arc<dyn ServerPort>,+ ready: Option<tokio::sync::oneshot::Sender<SocketAddr>>,+) -> anyhow::Result<()> {+ let host_config = Config::load_or_init().await?;+ let state = HttpState {+ port,+ config: host_config,+ auth_token: config.auth_token,+ sessions: Arc::default(),+ };+ let listener = tokio::net::TcpListener::bind(config.bind_addr).await?;+ let local_addr = listener.local_addr()?;+ if let Some(sender) = ready {+ let _ = sender.send(local_addr);+ }+ let result = axum::serve(listener, router(state.clone())).await;+ close_http_sessions(&state).await;+ result.map_err(anyhow::Error::from)}diff --git a/crates/openhuman-core/src/mcp/server/module.rs b/crates/openhuman-core/src/mcp/server/module.rsnew file mode 100644index 0000000000..d243a0cdf5--- /dev/null+++ b/crates/openhuman-core/src/mcp/server/module.rs@@ -0,0 +1,354 @@+//! TinyMCP server-protocol adapter over the published bus contract.++use std::{+ sync::{+ atomic::{AtomicU64, Ordering},+ Arc,+ },+ time::Duration,+};++use async_trait::async_trait;+use serde::Serialize;+use serde_json::{Map, Value};+use tinymcp_bus::{+ names, ServerHostReply, ServerHttpResponseMetadata, ServerHttpSessionConfig,+ ServerHttpSessionRequest, ServerInput, ServerOperationRef, ServerOperationSnapshot,+ ServerOperationState, ServerSessionConfig,+};+use tokio_util::sync::CancellationToken;+use uuid::Uuid;++use crate::{+ config::Config,+ modules::{client::ModuleCallError, client::ModuleClient},+};++use super::handler;++const MODULE: &str = "tinymcp";+const POLL_INTERVAL: Duration = Duration::from_millis(5);+static NEXT_SESSION_ID: AtomicU64 = AtomicU64::new(1);++#[derive(Debug, thiserror::Error)]+pub(super) enum ServerError {+ #[error("MCP module {0}")]+ Module(ModuleCallError),+ #[error("MCP server operation was cancelled")]+ Cancelled,+ #[error("MCP server module returned an unknown operation state")]+ UnknownState,+ #[error("MCP server module operation failed: {0}")]+ Failed(String),+ #[error("MCP server module returned no response metadata")]+ MissingHttpMetadata,+ #[error("MCP server module returned an invalid HTTP status")]+ InvalidHttpStatus,+}++#[async_trait]+pub(super) trait ServerPort: Send + Sync {+ async fn open(&self, config: ServerSessionConfig) -> Result<String, ModuleCallError>;+ async fn open_http(&self, config: ServerHttpSessionConfig)+ -> Result<String, ModuleCallError>;+ async fn submit(+ &self,+ session: &str,+ headers: Map<String, Value>,+ input: ServerInput,+ ) -> Result<(), ModuleCallError>;+ async fn poll(&self, session: &str) -> Result<ServerOperationSnapshot, ModuleCallError>;+ async fn complete(+ &self,+ session: &str,+ callback: &str,+ reply: ServerHostReply,+ ) -> Result<(), ModuleCallError>;+ async fn cancel(&self, operation: ServerOperationRef) -> Result<(), ModuleCallError>;+ async fn close(&self, session: &str) -> Result<(), ModuleCallError>;+ async fn http_session(+ &self,+ request: ServerHttpSessionRequest,+ ) -> Result<ServerHttpResponseMetadata, ModuleCallError>;+ async fn metadata(+ &self,+ session: &str,+ ) -> Result<tinymcp_bus::ServerSessionMetadata, ModuleCallError>;+ async fn shutdown(&self) -> Result<usize, ModuleCallError>;+}++struct TinyMcpPort {+ client: ModuleClient,+}++#[async_trait]+impl ServerPort for TinyMcpPort {+ async fn open(&self, config: ServerSessionConfig) -> Result<String, ModuleCallError> {+ self.client.call(MODULE, names::methods::SERVER_OPEN, (config,)).await+ }++ async fn open_http(+ &self,+ config: ServerHttpSessionConfig,+ ) -> Result<String, ModuleCallError> {+ self.client+ .call(MODULE, names::methods::SERVER_OPEN_HTTP, (config,))+ .await+ }++ async fn submit(+ &self,+ session: &str,+ headers: Map<String, Value>,+ input: ServerInput,+ ) -> Result<(), ModuleCallError> {+ self.client+ .call(+ MODULE,+ names::methods::SERVER_SUBMIT,+ (session.to_owned(), headers, input),+ )+ .await+ }++ async fn poll(&self, session: &str) -> Result<ServerOperationSnapshot, ModuleCallError> {+ self.client+ .call(MODULE, names::methods::SERVER_POLL, (session.to_owned(),))+ .await+ }++ async fn complete(+ &self,+ session: &str,+ callback: &str,+ reply: ServerHostReply,+ ) -> Result<(), ModuleCallError> {+ self.client+ .call(+ MODULE,+ names::methods::SERVER_COMPLETE,+ (session.to_owned(), callback.to_owned(), reply),+ )+ .await+ }++ async fn cancel(&self, operation: ServerOperationRef) -> Result<(), ModuleCallError> {+ self.client+ .call(MODULE, names::methods::SERVER_CANCEL, (operation,))+ .await+ }++ async fn close(&self, session: &str) -> Result<(), ModuleCallError> {+ self.client+ .call(MODULE, names::methods::SERVER_CLOSE, (session.to_owned(),))+ .await+ }++ async fn http_session(+ &self,+ request: ServerHttpSessionRequest,+ ) -> Result<ServerHttpResponseMetadata, ModuleCallError> {+ self.client+ .call(MODULE, names::methods::SERVER_HTTP_SESSION, (request,))+ .await+ }++ async fn metadata(+ &self,+ session: &str,+ ) -> Result<tinymcp_bus::ServerSessionMetadata, ModuleCallError> {+ self.client+ .call(+ MODULE,+ names::methods::SERVER_SESSION_METADATA,+ (session.to_owned(),),+ )+ .await+ }++ async fn shutdown(&self) -> Result<usize, ModuleCallError> {+ self.client+ .call(MODULE, names::methods::SERVER_SHUTDOWN, ())+ .await+ }+}++pub(super) struct ServerSession {+ port: Arc<dyn ServerPort>,+ id: String,+ next_operation: AtomicU64,+}++impl ServerSession {+ pub(super) fn port_for_config(config: &Config) -> Arc<dyn ServerPort> {+ Arc::new(TinyMcpPort {+ client: ModuleClient::new(config.clone()),+ })+ }++ pub(super) async fn open(config: &Config) -> Result<Self, ServerError> {+ Self::open_with_port(Self::port_for_config(config)).await+ }++ async fn open_with_port(port: Arc<dyn ServerPort>) -> Result<Self, ServerError> {+ let (info, source_type_prefix, resources) = handler::declarations();+ let sequence = NEXT_SESSION_ID.fetch_add(1, Ordering::Relaxed).max(1);+ let id = port+ .open(ServerSessionConfig {+ session_id: Uuid::from_u128(u128::from(sequence)).to_string(),+ info,+ source_type_prefix,+ resources,+ })+ .await+ .map_err(ServerError::Module)?;+ Ok(Self {+ port,+ id,+ next_operation: AtomicU64::new(1),+ })+ }++ pub(super) async fn open_http(+ port: Arc<dyn ServerPort>,+ requested_session_id: Option<String>,+ known_session: bool,+ expected_protocol_version: Option<String>,+ ) -> Result<Self, ServerError> {+ let (info, source_type_prefix, resources) = handler::declarations();+ let sequence = NEXT_SESSION_ID.fetch_add(1, Ordering::Relaxed).max(1);+ let id = port+ .open_http(ServerHttpSessionConfig {+ server: ServerSessionConfig {+ session_id: Uuid::from_u128(u128::from(sequence)).to_string(),+ info,+ source_type_prefix,+ resources,+ },+ requested_session_id,+ known_session,+ expected_protocol_version,+ })+ .await+ .map_err(ServerError::Module)?;+ Ok(Self {+ port,+ id,+ next_operation: AtomicU64::new(1),+ })+ }++ pub(super) fn id(&self) -> &str {+ &self.id+ }++ pub(super) fn port(&self) -> Arc<dyn ServerPort> {+ Arc::clone(&self.port)+ }++ pub(super) async fn submit(+ &self,+ headers: Map<String, Value>,+ line: String,+ cancellation: &CancellationToken,+ ) -> Result<ServerOperationSnapshot, ServerError> {+ let operation_id = Uuid::from_u128(u128::from(+ self.next_operation.fetch_add(1, Ordering::Relaxed).max(1),+ ))+ .to_string();+ self.port+ .submit(+ &self.id,+ headers,+ ServerInput {+ operation_id: operation_id.clone(),+ line,+ },+ )+ .await+ .map_err(ServerError::Module)?;++ loop {+ let snapshot = tokio::select! {+ _ = cancellation.cancelled() => {+ self.port.cancel(ServerOperationRef {+ session_id: self.id.clone(),+ operation_id,+ }).await.map_err(ServerError::Module)?;+ return Err(ServerError::Cancelled);+ }+ result = self.port.poll(&self.id) => result.map_err(ServerError::Module)?,+ };+ match snapshot.state.clone() {+ ServerOperationState::Pending => tokio::time::sleep(POLL_INTERVAL).await,+ ServerOperationState::Callback { callback } => {+ let reply = handler::dispatch(callback.call).await;+ self.port+ .complete(&self.id, &callback.id, reply)+ .await+ .map_err(ServerError::Module)?;+ }+ ServerOperationState::Complete { .. } => return Ok(snapshot),+ ServerOperationState::Cancelled => return Err(ServerError::Cancelled),+ ServerOperationState::Failed { message } => {+ return Err(ServerError::Failed(message));+ }+ ServerOperationState::Unknown => return Err(ServerError::UnknownState),+ }+ }+ }++ pub(super) async fn close(&self) -> Result<(), ServerError> {+ self.port+ .close(&self.id)+ .await+ .map_err(ServerError::Module)+ }++ pub(super) async fn http_session(+ &self,+ request: ServerHttpSessionRequest,+ ) -> Result<ServerHttpResponseMetadata, ServerError> {+ self.port+ .http_session(request)+ .await+ .map_err(ServerError::Module)+ }++ pub(super) async fn metadata(+ &self,+ ) -> Result<tinymcp_bus::ServerSessionMetadata, ServerError> {+ self.port+ .metadata(&self.id)+ .await+ .map_err(ServerError::Module)+ }++ pub(super) async fn shutdown(&self) -> Result<usize, ServerError> {+ self.port.shutdown().await.map_err(ServerError::Module)+ }+}++pub(super) fn headers_object(headers: impl Iterator<Item = (String, String)>) -> Map<String, Value> {+ headers+ .map(|(name, value)| (name, Value::String(value)))+ .collect()+}++pub(super) fn session_config(+ session_id: String,+ info: Value,+ source_type_prefix: String,+ resources: Vec<Value>,+) -> ServerSessionConfig {+ ServerSessionConfig {+ session_id,+ info,+ source_type_prefix,+ resources,+ }+}++pub(super) fn module_string<T: Serialize>(value: &T) -> Result<String, serde_json::Error> {+ serde_json::to_string(value)+}diff --git a/crates/openhuman-core/src/mcp/server/stdio.rs b/crates/openhuman-core/src/mcp/server/stdio.rsindex c5bcce28ed..f96d1293f0 100644--- a/crates/openhuman-core/src/mcp/server/stdio.rs+++ b/crates/openhuman-core/src/mcp/server/stdio.rs@@ -5,9 +5,9 @@ use anyhow::{bail, Result};#[cfg(feature = "http-server")]use std::net::SocketAddr;-use crate::core::logging::CliLogDefault;+use crate::{config::Config, core::logging::CliLogDefault};-use super::handler::handler;+use super::module::ServerSession;#[cfg(feature = "http-server")]use super::http::{run_http, HttpServerConfig};@@ -85,11 +85,7 @@ pub fn run_stdio_from_cli(args: &[String]) -> Result<()> {match transport {McpTransport::Stdio => {log::debug!("[mcp_server] starting stdio MCP server");- rt.block_on(tinymcp::run_stdio(- handler(),- tokio::io::stdin(),- tokio::io::stdout(),- ))?;+ rt.block_on(run_stdio_module())?;}McpTransport::Http => {#[cfg(feature = "http-server")]@@ -119,6 +115,37 @@ pub fn run_stdio_from_cli(args: &[String]) -> Result<()> {Ok(())}+async fn run_stdio_module() -> Result<()> {+ use tokio::io::{AsyncBufReadExt, AsyncWriteExt};++ let config = Config::load_or_init().await?;+ let session = ServerSession::open(&config).await?;+ let cancellation = tokio_util::sync::CancellationToken::new();+ let result = async {+ let mut input = tokio::io::BufReader::new(tokio::io::stdin()).lines();+ let mut output = tokio::io::stdout();+ while let Some(line) = input.next_line().await? {+ let snapshot = session+ .submit(serde_json::Map::new(), line, &cancellation)+ .await?;+ if let tinymcp_bus::ServerOperationState::Complete {+ response: Some(response),+ } = snapshot.state+ {+ output.write_all(response.as_bytes()).await?;+ output.write_all(b"\n").await?;+ output.flush().await?;+ }+ }+ Ok::<(), anyhow::Error>(())+ }+ .await;+ let cleanup = session.close().await;+ result?;+ cleanup?;+ Ok(())+}+/// Initialize logging for the MCP server.////// MCP servers run as subprocesses of clients (Claude Desktop, Cursor, …) which