Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(preview): list SharePreview without a session and log MCP failures (#7164)
Wolf Mermelstein78250f7787fa
diff --git a/crates/agent_egress/src/domain/service.rs b/crates/agent_egress/src/domain/service.rsindex 81aada130f..5b3a03ddd3 100644--- a/crates/agent_egress/src/domain/service.rs+++ b/crates/agent_egress/src/domain/service.rs@@ -220,8 +220,18 @@ wherelet mut response = self.forward.forward(request).await?;sanitize_response_headers(response.headers_mut());- tracing::Span::current().record("upstream_status", response.status().as_u16());- tracing::debug!(status = %response.status(), "upstream answered");+ let status = response.status();+ tracing::Span::current().record("upstream_status", status.as_u16());+ if status.is_success() {+ tracing::debug!(%status, "upstream answered");+ } else {+ tracing::warn!(+ session = %grant.session,+ upstream = %target.name(),+ %status,+ "upstream answered with a failure status"+ );+ }Ok(response)}diff --git a/crates/agent_preview/src/inbound/toolset.rs b/crates/agent_preview/src/inbound/toolset.rsindex 6aa0323713..a3bd6f847b 100644--- a/crates/agent_preview/src/inbound/toolset.rs+++ b/crates/agent_preview/src/inbound/toolset.rs@@ -3,7 +3,13 @@ use crate::domain::{AgentIdentity, PreviewService};use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,};-use axum::Router;+use axum::{+ Router,+ extract::{Request, State},+ http::{HeaderMap, HeaderValue, Uri, header},+ middleware::{self, Next},+ response::Response,+};use rmcp::{ServerHandler,model::{@@ -203,19 +209,41 @@ impl Mcp {&self,context: &McpContext<rmcp::RoleServer>,) -> Result<AgentIdentity, rmcp::ErrorData> {- let token = context- .extensions- .get::<axum::http::request::Parts>()- .and_then(|p| p.headers.get(axum::http::header::AUTHORIZATION))- .and_then(|v| v.to_str().ok())- .and_then(|v| v.strip_prefix("Bearer "))- .filter(|v| v.len() <= 256)- .ok_or_else(|| {- rmcp::ErrorData::invalid_request("agent session authentication required", None)- })?;- self.0.agent(token).await.map_err(|_| {- rmcp::ErrorData::invalid_request("agent session authentication failed", None)- })+ let Some(parts) = context.extensions.get::<axum::http::request::Parts>() else {+ tracing::warn!("preview mcp request had no http parts");+ return Err(rmcp::ErrorData::invalid_request(+ "agent session authentication required",+ None,+ ));+ };+ let Some(header) = parts.headers.get(header::AUTHORIZATION) else {+ tracing::warn!("preview mcp request missing authorization");+ return Err(rmcp::ErrorData::invalid_request(+ "agent session authentication required",+ None,+ ));+ };+ let Some(token) = header+ .to_str()+ .ok()+ .and_then(|value| value.strip_prefix("Bearer "))+ .filter(|value| value.len() <= 256)+ else {+ tracing::warn!("preview mcp bearer was unreadable or longer than 256 bytes");+ return Err(rmcp::ErrorData::invalid_request(+ "agent session authentication required",+ None,+ ));+ };+ self.0+ .agent(token)+ .await+ .inspect_err(|error| {+ tracing::warn!(error = %error, "preview mcp session authentication failed");+ })+ .map_err(|_| {+ rmcp::ErrorData::invalid_request("agent session authentication failed", None)+ })}}impl ServerHandler for Mcp {@@ -229,25 +257,17 @@ impl ServerHandler for Mcp {async fn list_tools(&self,_: Option<PaginatedRequestParams>,- context: McpContext<rmcp::RoleServer>,+ _: McpContext<rmcp::RoleServer>,) -> Result<ListToolsResult, rmcp::ErrorData> {- self.identity(&context).await?;- let schema = schemars::schema_for!(SharePreview);- let value = serde_json::to_value(schema)- .map_err(|_| rmcp::ErrorData::internal_error("tool schema unavailable", None))?;- let object = value- .as_object()- .cloned()- .ok_or_else(|| rmcp::ErrorData::internal_error("tool schema unavailable", None))?;+ // Schema only: Cursor's live discovery calls tools/list before a tool+ // runs. Requiring a session here made the whole server look broken+ // while SharePreview itself still needed the credential.Ok(ListToolsResult {- tools: vec![Tool::new(- "SharePreview",- "Share a local HTTP development server with this session's viewers. Execute the returned OpenSSH script to connect it; supports WebSockets and HMR.",- Arc::new(object),- )],+ tools: vec![share_preview_tool()?],..Default::default()})}+ #[tracing::instrument(skip_all, err, fields(tool = %request.name))]async fn call_tool(&self,request: CallToolRequestParams,@@ -280,9 +300,109 @@ impl ServerHandler for Mcp {})}}-/// Build a stateless MCP server: every tool request authenticates its session credential.+fn share_preview_tool() -> Result<Tool, rmcp::ErrorData> {+ let schema = schemars::schema_for!(SharePreview);+ let value = serde_json::to_value(schema)+ .map_err(|_| rmcp::ErrorData::internal_error("tool schema unavailable", None))?;+ let object = value+ .as_object()+ .cloned()+ .ok_or_else(|| rmcp::ErrorData::internal_error("tool schema unavailable", None))?;+ Ok(Tool::new(+ "SharePreview",+ "Share a local HTTP development server with this session's viewers. Execute the returned OpenSSH script to connect it; supports WebSockets and HMR.",+ Arc::new(object),+ ))+}++/// Loopback plus the configured control hosts. rmcp matches a hostname+/// without a port against any port, so `preview-gateway` covers `:8080`.+fn mcp_allowed_hosts(configured: Vec<String>) -> Vec<String> {+ let mut hosts = vec![+ "localhost".to_owned(),+ "127.0.0.1".to_owned(),+ "::1".to_owned(),+ ];+ for host in configured {+ let host = host.trim();+ if !host.is_empty() && !hosts.iter().any(|existing| existing == host) {+ hosts.push(host.to_owned());+ }+ }+ hosts+}++/// `Router::nest` can drop the Host header hyper synthesized from HTTP/2+/// `:authority`. The public gateway reaches MCP at `/preview/mcp` that way.+fn restore_dropped_host(headers: &mut HeaderMap, uri: &Uri, allowed: &[String]) {+ if headers.contains_key(header::HOST) {+ return;+ }+ if let Some(value) = headers.get("x-forwarded-host")+ && let Ok(host) = value.to_str()+ && host_name_allowed(host, allowed)+ {+ headers.insert(header::HOST, value.clone());+ return;+ }+ if let Some(authority) = uri.authority()+ && host_name_allowed(authority.as_str(), allowed)+ && let Ok(value) = HeaderValue::from_str(authority.as_str())+ {+ headers.insert(header::HOST, value);+ }+}++fn host_name_allowed(host: &str, allowed: &[String]) -> bool {+ let name = host_name(host);+ allowed+ .iter()+ .any(|allowed| host_name(allowed).eq_ignore_ascii_case(&name))+}++fn host_name(host: &str) -> String {+ let host = host.rsplit_once('@').map_or(host, |(_, host)| host);+ host.split(':')+ .next()+ .unwrap_or(host)+ .trim()+ .trim_matches(['[', ']'])+ .to_ascii_lowercase()+}++#[derive(Clone)]+struct McpHttp {+ allowed_hosts: Vec<String>,+}++async fn prepare_mcp(State(state): State<McpHttp>, mut request: Request, next: Next) -> Response {+ let uri = request.uri().clone();+ restore_dropped_host(request.headers_mut(), &uri, &state.allowed_hosts);+ let host = request+ .headers()+ .get(header::HOST)+ .and_then(|value| value.to_str().ok())+ .unwrap_or("-")+ .to_owned();+ let method = request.method().clone();+ let path = request.uri().path().to_owned();+ let response = next.run(request).await;+ let status = response.status();+ if status.is_success() {+ tracing::debug!(%method, %path, host, %status, "preview mcp");+ } else {+ tracing::warn!(%method, %path, host, %status, "preview mcp rejected");+ }+ response+}++/// Build a stateless MCP server. `tools/list` is public; `SharePreview` still+/// authenticates the session credential.pub fn router(service: PreviewService, allowed_hosts: Vec<String>) -> Router {- let mut config = StreamableHttpServerConfig::default().with_allowed_hosts(allowed_hosts);+ let allowed_hosts = mcp_allowed_hosts(allowed_hosts);+ tracing::info!(hosts = ?allowed_hosts, "preview mcp host allowlist");+ let mut config =+ StreamableHttpServerConfig::default().with_allowed_hosts(allowed_hosts.clone());config.stateful_mode = false;config.json_response = true;let transport = StreamableHttpService::new(@@ -290,7 +410,12 @@ pub fn router(service: PreviewService, allowed_hosts: Vec<String>) -> Router {Arc::new(LocalSessionManager::default()),config,);- Router::new().nest_service("/mcp", transport)+ Router::new()+ .nest_service("/mcp", transport)+ .layer(middleware::from_fn_with_state(+ McpHttp { allowed_hosts },+ prepare_mcp,+ ))}#[cfg(test)]diff --git a/crates/agent_preview/src/inbound/toolset/test.rs b/crates/agent_preview/src/inbound/toolset/test.rsindex d48ff01b69..88c73f7e1c 100644--- a/crates/agent_preview/src/inbound/toolset/test.rs+++ b/crates/agent_preview/src/inbound/toolset/test.rs@@ -1,5 +1,6 @@use super::*;use crate::testing::{fixture_with, identity};+use tower::ServiceExt;/// Settings for a local stack that published a quick tunnel: every reachability/// path at once, which is also the only configuration that allows a proxy host.@@ -117,3 +118,90 @@ fn a_proxy_host_is_rejected_outside_a_local_stack() {settings.ssh_proxy_host = Some("not a hostname".into());assert!(settings.validate().is_err());}++#[test]+fn configured_control_hosts_are_added_to_the_loopback_allowlist() {+ assert_eq!(+ mcp_allowed_hosts(vec![+ "preview-gateway".into(),+ " localhost ".into(),+ String::new(),+ ]),+ vec!["localhost", "127.0.0.1", "::1", "preview-gateway"]+ );+}++#[test]+fn a_dropped_host_is_restored_only_from_an_allowed_forwarded_name() {+ let allowed = mcp_allowed_hosts(vec!["dev-gateway.macro.com".into()]);+ let mut headers = HeaderMap::new();+ headers.insert("x-forwarded-host", "dev-gateway.macro.com".parse().unwrap());+ restore_dropped_host(&mut headers, &"/preview/mcp".parse().unwrap(), &allowed);+ assert_eq!(headers[header::HOST], "dev-gateway.macro.com");++ let mut headers = HeaderMap::new();+ headers.insert("x-forwarded-host", "attacker.test".parse().unwrap());+ restore_dropped_host(&mut headers, &"/preview/mcp".parse().unwrap(), &allowed);+ assert!(headers.get(header::HOST).is_none());+}++#[tokio::test]+async fn live_discovery_lists_share_preview_without_a_session() {+ let (service, _, _) = crate::testing::fixture(22);+ let app = router(service, vec!["preview-gateway".into()]);+ let body = serde_json::json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/list",+ "params": {}+ });+ let response = app+ .oneshot(+ axum::http::Request::builder()+ .method("POST")+ .uri("/mcp")+ .header("host", "preview-gateway:8080")+ .header("content-type", "application/json")+ .header("accept", "application/json, text/event-stream")+ .body(axum::body::Body::from(body.to_string()))+ .unwrap(),+ )+ .await+ .unwrap();+ assert!(+ response.status().is_success(),+ "discovery failed: {}",+ response.status()+ );+ let bytes = axum::body::to_bytes(response.into_body(), 64 * 1024)+ .await+ .unwrap();+ let payload: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ assert_eq!(payload["result"]["tools"][0]["name"], "SharePreview");+}++#[tokio::test]+async fn a_disallowed_host_is_rejected_before_tools_are_listed() {+ let (service, _, _) = crate::testing::fixture(22);+ let app = router(service, vec!["preview-gateway".into()]);+ let body = serde_json::json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/list",+ "params": {}+ });+ let response = app+ .oneshot(+ axum::http::Request::builder()+ .method("POST")+ .uri("/mcp")+ .header("host", "attacker.test")+ .header("content-type", "application/json")+ .header("accept", "application/json, text/event-stream")+ .body(axum::body::Body::from(body.to_string()))+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(response.status(), axum::http::StatusCode::FORBIDDEN);+}diff --git a/services/preview_gateway/src/adapters.rs b/services/preview_gateway/src/adapters.rsindex 60f4bc51c7..1d0405e121 100644--- a/services/preview_gateway/src/adapters.rs+++ b/services/preview_gateway/src/adapters.rs@@ -37,6 +37,9 @@ impl<Repo: AgentSessionRepo, Access: EntityAccessService> Authoritylet session =agent_session::domain::credentials::authenticate_session(&self.sessions, &token.hash()).await+ .inspect_err(|error| {+ tracing::warn!(error = %error, "preview mcp session lookup failed");+ }).map_err(|_| PreviewError::Denied)?;Ok(AgentIdentity {session: session.id,@@ -44,6 +47,9 @@ impl<Repo: AgentSessionRepo, Access: EntityAccessService> Authority// non-user owner is refused rather than quietly given a quota.owner: session.owner_user()+ .inspect_err(|error| {+ tracing::warn!(error = %error, "preview mcp session has no user owner");+ }).map_err(|_| PreviewError::Denied)?.clone(),})diff --git a/services/preview_gateway/src/main.rs b/services/preview_gateway/src/main.rsindex 84883a837d..7d6fc84d5d 100644--- a/services/preview_gateway/src/main.rs+++ b/services/preview_gateway/src/main.rs@@ -96,14 +96,18 @@ async fn run() -> Result<(), rootcause::Report> {access,MacroAuthorizationState::new(Arc::new(auth)),));- let mcp = toolset::router(- service.clone(),- config- .preview_control_hosts- .split(',')- .map(|s| s.trim().to_owned())- .collect(),+ let allowed_hosts: Vec<String> = config+ .preview_control_hosts+ .split(',')+ .map(|s| s.trim().to_owned())+ .filter(|host| !host.is_empty())+ .collect();+ tracing::info!(+ hosts = ?allowed_hosts,+ port = config.port,+ "preview control listener ready");+ let mcp = toolset::router(service.clone(), allowed_hosts);let app = control.merge(mcp).route("/health", get(|| async { "ok" }))@@ -165,17 +169,24 @@ async fn admit_control(request: Request,next: Next,) -> Response {+ let method = request.method().clone();+ let path = request.uri().path().to_owned();let Ok(_permit) = slots.try_acquire_owned() else {+ tracing::warn!(%method, %path, "preview control overloaded");return StatusCode::TOO_MANY_REQUESTS.into_response();};let work = async {let (parts, body) = request.into_parts();let Ok(body) = axum::body::to_bytes(body, 64 * 1024).await else {+ tracing::warn!(%method, %path, "preview control request too large");return StatusCode::PAYLOAD_TOO_LARGE.into_response();};next.run(Request::from_parts(parts, Body::from(body))).await};tokio::time::timeout(Duration::from_secs(15), work).await- .unwrap_or_else(|_| StatusCode::REQUEST_TIMEOUT.into_response())+ .unwrap_or_else(|_| {+ tracing::warn!(%method, %path, "preview control timed out");+ StatusCode::REQUEST_TIMEOUT.into_response()+ })}