From 42e253e6c9c538b29675b83ad65e4871208f8460 Mon Sep 17 00:00:00 2001 From: tomi Date: Wed, 18 Nov 2026 00:06:50 +0100 Subject: [PATCH 1/3] fix(mcp): fail closed on unsupported Playwright isolated contexts --- docs/ARCHITECTURE.md | 26 ++++ src/bridge.rs | 192 +++++++++++++++++++++++- src/upstream_control.rs | 314 +++++++++++++++++++++++++++++++++++++++- 3 files changed, 522 insertions(+), 10 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index d78e42ef..3d91af0c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1125,6 +1125,32 @@ The catalogue is a startup snapshot. Dynamic `tools/list_changed` notifications are not used to mutate the downstream fixed surface; restart the process to rematerialize an upstream catalogue. +**Playwright browser-context capability boundary.** A `browser_tabs` call with +`action: "new"` and a non-default `isolatedContext` requires a real browser-level +connection. An upstream launched with `--extension` (or +`PLAYWRIGHT_MCP_EXTENSION=true`) only attaches to existing tabs, so Codexify +rejects the isolated request **before upstream dispatch**, whether invoked +through direct, gateway or catalog exposure. An ordinary new/default-context +tab is unaffected. Browser-level Playwright may create isolated contexts; a CDP +endpoint may or may not have browser-level permission. If CDP reports the exact +`Target.createBrowserContext` `-32000 Not allowed` error, Codexify explains +the missing capability and does not retry or substitute the extension. + +A connected extension is **not** a fallback for an unavailable browser-level +backend. These are separate upstreams with distinct session identities; routing +one tab-creation call to another upstream would not route subsequent navigation, +selection or cleanup there. Backend and tab ownership must remain stable for +the entire workflow. Playwright's index-based global tab selection is not +per-agent ownership enforcement; callers sharing one backend must still prevent +cross-agent tab interference until stable target identity is integrated upstream. + +MCP initialization is a startup snapshot as well: a `playwright` server that +misses `startupTimeoutSec` is omitted from the downstream catalogue, even if +`playwright-extension` succeeds. Investigate its startup diagnostics and set +a bounded per-upstream `startupTimeoutSec` appropriate for the machine before +restarting Codexify during a safe maintenance window. Never restart an active +browser or resubmit an external action just to repair a missing MCP tool. + ### 7.3 Direct compatibility mode (`"mode": "direct"`) Each selected upstream tool becomes a `BridgedTool` named `__` diff --git a/src/bridge.rs b/src/bridge.rs index 68bdcef4..3cb158c1 100644 --- a/src/bridge.rs +++ b/src/bridge.rs @@ -274,6 +274,12 @@ pub(crate) async fn forward_tool_call( context: UpstreamCallContext<'_>, ) -> ToolResult { let UpstreamCallContext { resources, control } = context; + // This preflight is shared by direct, gateway and catalog MCP exposure. + // Never send an isolation request to a browser extension as a fallback. + if let Err(error) = control.check_browser_context_request(tool, ¶ms) { + return ToolResult::error(format!("Upstream MCP server '{server}': {error}")); + } + let isolated_requested = control.isolated_tab_requested(tool, ¶ms); let timeout = tool_timeout.unwrap_or(Duration::from_secs(60)); let deadline = tokio::time::Instant::now() + timeout; let token = cancellation.cloned().unwrap_or_default(); @@ -307,10 +313,34 @@ pub(crate) async fn forward_tool_call( }); match result { - Ok(result) => map_call_result(result, peer, server, tool_timeout, resources), - Err(error) => ToolResult::error(format!( - "Upstream MCP server '{server}' failed to run '{tool}': {error}" - )), + Ok(result) => { + if isolated_requested && result.is_error == Some(true) { + let message = result + .content + .iter() + .filter_map(|block| match block { + ContentBlock::Text(text) => Some(text.text.as_str()), + _ => None, + }) + .collect::>() + .join("\n"); + if let Some(error) = control.browser_context_refusal(isolated_requested, &message) { + return ToolResult::error(format!( + "Upstream MCP server '{server}' failed to run '{tool}': {error}" + )); + } + } + map_call_result(result, peer, server, tool_timeout, resources) + } + Err(error) => { + let detail = error.to_string(); + let detail = control + .browser_context_refusal(isolated_requested, &detail) + .unwrap_or(detail); + ToolResult::error(format!( + "Upstream MCP server '{server}' failed to run '{tool}': {detail}" + )) + } } } @@ -542,9 +572,10 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { match connect_one(server_name, spec, config).await { Ok((service, upstream_tools, tool_timeout)) => { let peer = service.peer().clone(); - let control = Arc::new(crate::upstream_control::UpstreamControl::new( - spec.request_limits.clone(), - )); + let control = Arc::new( + crate::upstream_control::UpstreamControl::new(spec.request_limits.clone()) + .for_server(server_name, spec), + ); upstreams.insert(server_name.clone(), control.clone()); monitors.push(monitor_upstream(peer.clone(), control.clone())); let count = upstream_tools.len(); @@ -604,6 +635,18 @@ pub async fn connect_upstreams(config: &AppConfig) -> Bridge { "Call the `{original_name}` tool on the `{server_name}` MCP server." ) }); + // Warn before a model chooses extension-backed tabs + // for a workflow requiring genuine browser contexts. + let description = if original_name == "browser_tabs" + && control.browser_context_capability() + == Some("existing-tabs-only") + { + format!( + "{description} This Playwright extension backend supports existing tabs only; isolatedContext requires a browser-level Playwright backend. No automatic cross-backend fallback is performed." + ) + } else { + description + }; tools.push(Box::new(BridgedTool { name: leaked, original_name, @@ -1322,6 +1365,12 @@ mod tests { if request.name.as_ref() == "slow" { tokio::time::sleep(Duration::from_secs(1)).await; } + if request.name.as_ref() == "browser_tabs" && text == "cdp_refused" { + return Ok(CallToolResult::error(vec![ContentBlock::text( + r#"Protocol error (Target.createBrowserContext): {"code":-32000,"message":"Not allowed"}"#, + )]) + .into()); + } Ok(CallToolResult::success(vec![ContentBlock::text(text)]).into()) } } @@ -1352,6 +1401,135 @@ mod tests { (format!("http://{address}/mcp"), task) } + #[tokio::test] + async fn playwright_capability_is_enforced_at_real_mcp_forwarding_boundary() { + // The test server echoes a marker for any browser_tabs request. If an + // extension-only isolated request reaches it, the test will fail. + let (url, server_task) = spawn_http_upstream().await; + let mut spec = McpServerSpec { + url: Some(url), + transport: Some("http".into()), + ..Default::default() + }; + spec.http_headers + .insert("authorization".into(), "Bearer remote-token".into()); + spec.http_headers + .insert("x-static".into(), "static-value".into()); + spec.http_headers.insert("x-env".into(), "env-value".into()); + let config = crate::config::default_config(std::env::temp_dir()); + let (service, _, _) = connect_one_with_env("playwright-test", &spec, &config, &|_| None) + .await + .unwrap(); + let resources = BridgedResourceStore::new(config.artifact_egress.clone()); + + let extension_spec = McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into(), "--extension".into()], + ..Default::default() + }; + let full_spec = McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into()], + ..Default::default() + }; + let cdp_spec = McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into(), "--cdp-endpoint=chrome".into()], + ..Default::default() + }; + let extension_control = crate::upstream_control::UpstreamControl::default() + .for_server("playwright-extension", &extension_spec); + let full_control = crate::upstream_control::UpstreamControl::default() + .for_server("playwright", &full_spec); + let cdp_control = + crate::upstream_control::UpstreamControl::default().for_server("playwright", &cdp_spec); + let tab_request = |name: &str, context: &str| { + CallToolRequestParams::new("browser_tabs").with_arguments( + json!({ + "action": "new", + "isolatedContext": context, + "url": "https://example.invalid/local-fixture", + "text": name, + }) + .as_object() + .unwrap() + .clone(), + ) + }; + + let blocked = forward_tool_call( + service.peer(), + tab_request("never-dispatch", "lane06_grants_funding"), + "playwright-extension", + "browser_tabs", + None, + None, + UpstreamCallContext { + resources: &resources, + control: &extension_control, + }, + ) + .await; + assert!(blocked.is_error); + assert!(blocked.joined_text().contains("No request was dispatched")); + assert!(!blocked.joined_text().contains("never-dispatch")); + + let capable = forward_tool_call( + service.peer(), + tab_request("capable-backend-called", "lane06_grants_funding"), + "playwright", + "browser_tabs", + None, + None, + UpstreamCallContext { + resources: &resources, + control: &full_control, + }, + ) + .await; + assert!(!capable.is_error); + assert_eq!(capable.joined_text(), "capable-backend-called"); + + let refused = forward_tool_call( + service.peer(), + tab_request("cdp_refused", "lane07_funded_events"), + "playwright", + "browser_tabs", + None, + None, + UpstreamCallContext { + resources: &resources, + control: &cdp_control, + }, + ) + .await; + assert!(refused.is_error); + assert!(refused.joined_text().contains("CDP -32000 Not allowed")); + assert!( + refused + .joined_text() + .contains("No isolated context was confirmed") + ); + + // No isolation requested: ordinary existing-tab operation still works. + let nonisolated = forward_tool_call( + service.peer(), + tab_request("ordinary-tab", "default"), + "playwright-extension", + "browser_tabs", + None, + None, + UpstreamCallContext { + resources: &resources, + control: &extension_control, + }, + ) + .await; + assert!(!nonisolated.is_error); + assert_eq!(nonisolated.joined_text(), "ordinary-tab"); + server_task.abort(); + } + #[derive(Clone)] struct ResourceTestMcp; diff --git a/src/upstream_control.rs b/src/upstream_control.rs index f1bf211a..5466c097 100644 --- a/src/upstream_control.rs +++ b/src/upstream_control.rs @@ -1,5 +1,6 @@ //! Per-connection admission and failure containment; never retries tool calls. -use crate::types::McpRequestLimits; +use crate::types::{McpRequestLimits, McpServerSpec}; +use rmcp::model::CallToolRequestParams; use serde_json::{Value, json}; use std::sync::Mutex; use std::time::Duration; @@ -7,6 +8,58 @@ use tokio::sync::{Semaphore, SemaphorePermit}; use tokio::time::Instant; use tokio_util::sync::CancellationToken; +// Capability is tied to a configured upstream, never inferred from a tab name. +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)] +enum PlaywrightBackendMode { + #[default] + Other, + Browser, + Cdp, + Extension, +} + +impl PlaywrightBackendMode { + fn from_spec(name: &str, spec: &McpServerSpec) -> Self { + let playwright = name.to_ascii_lowercase().contains("playwright") + || spec + .args + .iter() + .any(|arg| arg.to_ascii_lowercase().contains("playwright")) + || spec + .command + .as_deref() + .is_some_and(|command| command.to_ascii_lowercase().contains("playwright")); + if !playwright { + return Self::Other; + } + let extension_env = spec + .env + .get("PLAYWRIGHT_MCP_EXTENSION") + .is_some_and(|value| { + matches!(value.to_ascii_lowercase().as_str(), "1" | "true" | "yes") + }); + if spec + .args + .iter() + .any(|arg| arg == "--extension" || arg == "--extension=true") + || extension_env + || name.eq_ignore_ascii_case("playwright-extension") + || name.eq_ignore_ascii_case("playwright_extension") + { + Self::Extension + } else if spec + .args + .iter() + .any(|arg| arg == "--cdp-endpoint" || arg.starts_with("--cdp-endpoint=")) + || spec.env.contains_key("PLAYWRIGHT_MCP_CDP_ENDPOINT") + { + Self::Cdp + } else { + Self::Browser + } + } +} + #[derive(Default)] struct State { failures: u32, @@ -17,6 +70,7 @@ struct State { pub(crate) struct UpstreamControl { limits: McpRequestLimits, + playwright_mode: PlaywrightBackendMode, active: Semaphore, pending: Semaphore, state: Mutex, @@ -55,10 +109,79 @@ impl UpstreamControl { active: Semaphore::new(limits.max_concurrent_requests), pending: Semaphore::new(limits.max_concurrent_requests + limits.max_pending_requests), limits, + playwright_mode: PlaywrightBackendMode::Other, state: Mutex::new(State::default()), unavailable: tokio::sync::watch::channel(false).0, } } + /// Keep capability stable for this upstream connection and all exposure modes. + pub(crate) fn for_server(mut self, name: &str, spec: &McpServerSpec) -> Self { + self.playwright_mode = PlaywrightBackendMode::from_spec(name, spec); + self + } + + /// Advertise only what the connection mode can establish, not what a + /// similar tool on another upstream may be able to do. + pub(crate) fn browser_context_capability(&self) -> Option<&'static str> { + match self.playwright_mode { + PlaywrightBackendMode::Other => None, + PlaywrightBackendMode::Browser => Some("browser-level"), + PlaywrightBackendMode::Cdp => Some("cdp-permission-dependent"), + PlaywrightBackendMode::Extension => Some("existing-tabs-only"), + } + } + + pub(crate) fn isolated_tab_requested( + &self, + tool: &str, + params: &CallToolRequestParams, + ) -> bool { + self.playwright_mode != PlaywrightBackendMode::Other + && tool == "browser_tabs" + && params.arguments.as_ref().is_some_and(|args| { + args.get("action").and_then(Value::as_str) == Some("new") + && args + .get("isolatedContext") + .and_then(Value::as_str) + .is_some_and(|name| !name.is_empty() && name != "default") + }) + } + + /// An extension is attached to existing tabs; it cannot provide real + /// BrowserContexts. No attempt or fallback is safe for an isolation request. + pub(crate) fn check_browser_context_request( + &self, + tool: &str, + params: &CallToolRequestParams, + ) -> Result<(), String> { + if self.isolated_tab_requested(tool, params) + && self.playwright_mode == PlaywrightBackendMode::Extension + { + return Err( + "Playwright extension/existing-tab mode cannot create a genuinely isolated browser context (Target.createBrowserContext requires browser-level access). No request was dispatched. Use a connected browser-level Playwright MCP backend for browser_tabs(new, isolatedContext), then keep subsequent tab operations on that backend. If it is unavailable, repair its startup; do not fall back to shared extension tabs." + .into(), + ); + } + Ok(()) + } + + /// Some CDP endpoints are page-scoped; translate the exact refusal but + /// do not assume a context was created or automatically retry any tool. + pub(crate) fn browser_context_refusal( + &self, + isolated_requested: bool, + message: &str, + ) -> Option { + (isolated_requested + && message.contains("Target.createBrowserContext") + && message.contains("-32000") + && message.contains("Not allowed")) + .then(|| { + "CDP -32000 Not allowed: this Playwright/CDP session lacks browser-level Target.createBrowserContext permission. No isolated context was confirmed. Do not reuse an extension tab or assume creation succeeded; connect a browser-level Playwright backend, verify session identity and existing resources before retrying." + .into() + }) + } + pub(crate) async fn wait_unavailable(&self) { let mut receiver = self.unavailable.subscribe(); loop { @@ -128,10 +251,14 @@ impl UpstreamControl { .saturating_sub(self.active.available_permits()); let admitted = (self.limits.max_concurrent_requests + self.limits.max_pending_requests) .saturating_sub(self.pending.available_permits()); - json!({"state": if state.probe_active {"probing"} else if state.open_until.is_some() {"unresponsive"} else if state.failures > 0 {"degraded"} else {"connected"}, + let mut snapshot = json!({"state": if state.probe_active {"probing"} else if state.open_until.is_some() {"unresponsive"} else if state.failures > 0 {"degraded"} else {"connected"}, "activeRequests":active,"queuedRequests":admitted.saturating_sub(active),"consecutiveFailures":state.failures, "retryAfterMs":state.open_until.map(|until| until.saturating_duration_since(Instant::now()).as_millis() as u64).unwrap_or(0), - "lastOutcome":state.last_outcome}) + "lastOutcome":state.last_outcome}); + if let Some(capability) = self.browser_context_capability() { + snapshot["browserContextCapability"] = json!(capability); + } + snapshot } } @@ -181,6 +308,187 @@ impl Drop for Admission<'_> { } } +#[cfg(test)] +mod browser_context_tests { + use super::*; + use serde_json::json; + + #[test] + fn exposed_capability_matches_configured_backend() { + let full = UpstreamControl::default().for_server( + "playwright", + &McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into()], + ..Default::default() + }, + ); + let extension = UpstreamControl::default().for_server( + "playwright-extension", + &McpServerSpec { + command: Some("node".into()), + args: vec!["@playwright/mcp".into(), "--extension".into()], + ..Default::default() + }, + ); + assert_eq!(full.snapshot()["browserContextCapability"], "browser-level"); + assert_eq!( + extension.snapshot()["browserContextCapability"], + "existing-tabs-only" + ); + assert!( + UpstreamControl::default() + .snapshot() + .get("browserContextCapability") + .is_none() + ); + } + + fn spec(args: &[&str]) -> McpServerSpec { + McpServerSpec { + command: Some("node".into()), + args: args.iter().map(|arg| (*arg).to_string()).collect(), + ..Default::default() + } + } + + fn request(action: &str, context: Option<&str>) -> CallToolRequestParams { + let mut arguments = json!({ "action": action, "url": "https://example.invalid/form" }); + if let Some(context) = context { + arguments["isolatedContext"] = json!(context); + } + CallToolRequestParams::new("browser_tabs") + .with_arguments(arguments.as_object().unwrap().clone()) + } + + #[test] + fn extension_mode_fails_before_isolated_creation() { + let control = UpstreamControl::default().for_server( + "playwright-extension", + &spec(&["playwright/mcp.js", "--extension"]), + ); + let request = request("new", Some("lane06_grants_funding")); + assert!(control.isolated_tab_requested("browser_tabs", &request)); + let error = control + .check_browser_context_request("browser_tabs", &request) + .unwrap_err(); + assert!(error.contains("No request was dispatched")); + assert!(error.contains("cannot create a genuinely isolated")); + } + + #[test] + fn extension_env_and_renamed_server_also_fail_closed() { + let mut settings = spec(&["playwright/mcp.js"]); + settings + .env + .insert("PLAYWRIGHT_MCP_EXTENSION".into(), "true".into()); + let control = UpstreamControl::default().for_server("my_browser", &settings); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", Some("lane01"))) + .is_err() + ); + settings + .env + .insert("PLAYWRIGHT_MCP_EXTENSION".into(), "false".into()); + let control = UpstreamControl::default().for_server("my_browser", &settings); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", Some("lane01"))) + .is_ok() + ); + } + + #[test] + fn normal_extension_tab_operations_remain_compatible() { + let control = UpstreamControl::default().for_server( + "playwright-extension", + &spec(&["playwright/mcp.js", "--extension"]), + ); + for request in [ + request("list", Some("lane06")), + request("new", None), + request("new", Some("default")), + request("select", Some("lane06")), + ] { + assert!( + control + .check_browser_context_request("browser_tabs", &request) + .is_ok() + ); + } + assert!( + control + .check_browser_context_request("browser_navigate", &request("new", Some("lane06"))) + .is_ok() + ); + } + + #[test] + fn browser_and_cdp_backend_allow_capable_context_attempts() { + for settings in [ + spec(&["playwright/mcp.js"]), + spec(&["playwright/mcp.js", "--cdp-endpoint=http://127.0.0.1:9222"]), + ] { + let control = UpstreamControl::default().for_server("playwright", &settings); + assert!( + control + .check_browser_context_request( + "browser_tabs", + &request("new", Some("lane06_grants_funding")) + ) + .is_ok() + ); + } + } + + #[test] + fn cdp_minus_32000_is_precise_but_unrelated_errors_stay_untouched() { + let control = UpstreamControl::default().for_server( + "playwright", + &spec(&["playwright/mcp.js", "--cdp-endpoint=chrome"]), + ); + let error = r#"Protocol error (Target.createBrowserContext): {"code":-32000,"message":"Not allowed"}"#; + assert!( + control + .browser_context_refusal(true, error) + .unwrap() + .contains("No isolated context was confirmed") + ); + assert!(control.browser_context_refusal(false, error).is_none()); + assert!( + control + .browser_context_refusal( + true, + "Protocol error -32000: Not allowed for Page.navigate" + ) + .is_none() + ); + } + + #[test] + fn unrelated_mcp_backend_and_disconnect_cannot_silently_switch_modes() { + let ordinary = UpstreamControl::default() + .for_server("other-mcp", &spec(&["unrelated-server.js", "--extension"])); + assert!( + ordinary + .check_browser_context_request("browser_tabs", &request("new", Some("lane06"))) + .is_ok() + ); + let extension = UpstreamControl::default().for_server( + "playwright_extension", + &spec(&["playwright/mcp.js", "--extension"]), + ); + extension.health_result(false); + extension.health_result(true); + assert!( + extension + .check_browser_context_request("browser_tabs", &request("new", Some("lane06"))) + .is_err() + ); + } +} + #[cfg(test)] mod tests { use super::*; From e16ac4af1274c4b3fe63c6afc793a7f8473ae2fe Mon Sep 17 00:00:00 2001 From: tomi Date: Wed, 18 Nov 2026 00:57:24 +0100 Subject: [PATCH 2/3] fix(mcp): detect Playwright extension mode in JSON config --- docs/ARCHITECTURE.md | 11 ++- src/upstream_control.rs | 183 ++++++++++++++++++++++++++++++++++++---- 2 files changed, 175 insertions(+), 19 deletions(-) diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 3d91af0c..a535a97e 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1127,10 +1127,13 @@ rematerialize an upstream catalogue. **Playwright browser-context capability boundary.** A `browser_tabs` call with `action: "new"` and a non-default `isolatedContext` requires a real browser-level -connection. An upstream launched with `--extension` (or -`PLAYWRIGHT_MCP_EXTENSION=true`) only attaches to existing tabs, so Codexify -rejects the isolated request **before upstream dispatch**, whether invoked -through direct, gateway or catalog exposure. An ordinary new/default-context +connection. An upstream launched with `--extension`, `PLAYWRIGHT_MCP_EXTENSION=true`, +or `extension: true` in its Playwright JSON config only attaches to existing tabs, +so Codexify rejects the isolated request **before upstream dispatch**, whether +invoked through direct, gateway or catalog exposure. If an explicitly supplied +Playwright JSON configuration cannot be read or parsed, isolated-context +creation also fails closed instead of assuming the backend has browser-level +permissions. An ordinary new/default-context tab is unaffected. Browser-level Playwright may create isolated contexts; a CDP endpoint may or may not have browser-level permission. If CDP reports the exact `Target.createBrowserContext` `-32000 Not allowed` error, Codexify explains diff --git a/src/upstream_control.rs b/src/upstream_control.rs index 5466c097..816abc78 100644 --- a/src/upstream_control.rs +++ b/src/upstream_control.rs @@ -16,9 +16,42 @@ enum PlaywrightBackendMode { Browser, Cdp, Extension, + Unverified, } impl PlaywrightBackendMode { + // Playwright accepts --config and PLAYWRIGHT_MCP_CONFIG as well as + // command-line flags. A hidden extension configuration must not be + // mistaken for a browser-level backend. + fn config_document(spec: &McpServerSpec) -> Option> { + let path = spec + .args + .iter() + .enumerate() + .filter_map(|(index, arg)| { + if arg == "--config" { + Some(spec.args.get(index + 1).map_or("", String::as_str)) + } else { + arg.strip_prefix("--config=") + } + }) + .last() + .map(str::to_owned) + .or_else(|| spec.env.get("PLAYWRIGHT_MCP_CONFIG").cloned()) + .or_else(|| std::env::var("PLAYWRIGHT_MCP_CONFIG").ok())?; + + let mut path = std::path::PathBuf::from(path); + if path.is_relative() { + if let Some(cwd) = spec.cwd.as_ref() { + path = std::path::Path::new(cwd).join(path); + } + } + let parsed = std::fs::read_to_string(path) + .ok() + .and_then(|source| serde_json::from_str::(&source).ok()); + Some(parsed) + } + fn from_spec(name: &str, spec: &McpServerSpec) -> Self { let playwright = name.to_ascii_lowercase().contains("playwright") || spec @@ -32,31 +65,52 @@ impl PlaywrightBackendMode { if !playwright { return Self::Other; } - let extension_env = spec + + let configured = Self::config_document(spec); + let read_config = configured.as_ref().and_then(Option::as_ref); + + let cli_extension = spec.args.iter().rev().find_map(|arg| match arg.as_str() { + "--extension" | "--extension=true" => Some(true), + "--extension=false" => Some(false), + _ => None, + }); + let env_extension = spec .env .get("PLAYWRIGHT_MCP_EXTENSION") - .is_some_and(|value| { - matches!(value.to_ascii_lowercase().as_str(), "1" | "true" | "yes") + .cloned() + .or_else(|| std::env::var("PLAYWRIGHT_MCP_EXTENSION").ok()) + .and_then(|value| match value.to_ascii_lowercase().as_str() { + "1" | "true" | "yes" => Some(true), + "0" | "false" | "no" => Some(false), + _ => None, }); - if spec - .args - .iter() - .any(|arg| arg == "--extension" || arg == "--extension=true") - || extension_env + let config_extension = read_config + .and_then(|value| value.get("extension")) + .and_then(Value::as_bool); + if cli_extension.or(env_extension).or(config_extension) == Some(true) || name.eq_ignore_ascii_case("playwright-extension") || name.eq_ignore_ascii_case("playwright_extension") { - Self::Extension - } else if spec + return Self::Extension; + } + + // Failure to read an explicitly configured backend leaves its + // permissions unknown. Do not dispatch real isolation requests. + if configured.as_ref().is_some_and(Option::is_none) { + return Self::Unverified; + } + + let cdp = spec .args .iter() .any(|arg| arg == "--cdp-endpoint" || arg.starts_with("--cdp-endpoint=")) || spec.env.contains_key("PLAYWRIGHT_MCP_CDP_ENDPOINT") - { - Self::Cdp - } else { - Self::Browser - } + || std::env::var_os("PLAYWRIGHT_MCP_CDP_ENDPOINT").is_some() + || read_config + .and_then(|value| value.pointer("/browser/cdpEndpoint")) + .and_then(Value::as_str) + .is_some_and(|url| !url.is_empty()); + if cdp { Self::Cdp } else { Self::Browser } } } @@ -128,6 +182,7 @@ impl UpstreamControl { PlaywrightBackendMode::Browser => Some("browser-level"), PlaywrightBackendMode::Cdp => Some("cdp-permission-dependent"), PlaywrightBackendMode::Extension => Some("existing-tabs-only"), + PlaywrightBackendMode::Unverified => Some("unverified-config"), } } @@ -154,6 +209,13 @@ impl UpstreamControl { tool: &str, params: &CallToolRequestParams, ) -> Result<(), String> { + if self.isolated_tab_requested(tool, params) + && self.playwright_mode == PlaywrightBackendMode::Unverified + { + return Err( + "Playwright config file is missing, invalid or unreadable, so browser-context capabilities cannot be verified. No request was dispatched. Restore the configured MCP file before creating an isolated browser context.".into() + ); + } if self.isolated_tab_requested(tool, params) && self.playwright_mode == PlaywrightBackendMode::Extension { @@ -424,6 +486,97 @@ mod browser_context_tests { ); } + #[test] + fn playwright_json_extension_mode_cannot_bypass_guard() { + let temp = tempfile::tempdir().unwrap(); + let file = temp.path().join("playwright.json"); + std::fs::write(&file, r#"{"extension":true}"#).unwrap(); + let config_name = file.to_str().unwrap(); + let settings = spec(&["@playwright/mcp", "--config", config_name]); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.browser_context_capability(), + Some("existing-tabs-only") + ); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", Some("lane06"))) + .unwrap_err() + .contains("No request was dispatched") + ); + + std::fs::write( + &file, + r#"{"extension":false,"browser":{"cdpEndpoint":"chrome"}}"#, + ) + .unwrap(); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.browser_context_capability(), + Some("cdp-permission-dependent") + ); + + std::fs::write(&file, r#"{"extension":true}"#).unwrap(); + let mut overriding = settings.clone(); + overriding + .env + .insert("PLAYWRIGHT_MCP_EXTENSION".into(), "false".into()); + let control = UpstreamControl::default().for_server("playwright", &overriding); + assert_eq!(control.browser_context_capability(), Some("browser-level")); + } + + #[test] + fn missing_or_invalid_json_config_fails_closed_without_blocking_default_tab() { + let temp = tempfile::tempdir().unwrap(); + let file = temp.path().join("config.json"); + let mut settings = spec(&["@playwright/mcp", "--config"]); + settings.args.push(file.to_string_lossy().into_owned()); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.snapshot()["browserContextCapability"], + "unverified-config" + ); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", Some("lane06"))) + .unwrap_err() + .contains("No request was dispatched") + ); + assert!( + control + .check_browser_context_request("browser_tabs", &request("new", None)) + .is_ok() + ); + + std::fs::write(&file, "not json").unwrap(); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.snapshot()["browserContextCapability"], + "unverified-config" + ); + + std::fs::write(&file, r#"{"extension":true}"#).unwrap(); + settings.args.push("--extension=false".into()); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.snapshot()["browserContextCapability"], + "browser-level" + ); + } + + #[test] + fn playwright_config_relative_to_upstream_cwd_is_resolved() { + let temp = tempfile::tempdir().unwrap(); + std::fs::write(temp.path().join("playwright.json"), r#"{"extension":true}"#).unwrap(); + let mut settings = spec(&["@playwright/mcp", "--config=playwright.json"]); + settings.cwd = Some(temp.path().to_string_lossy().into_owned()); + let control = UpstreamControl::default().for_server("playwright", &settings); + assert_eq!( + control.snapshot()["browserContextCapability"], + "existing-tabs-only" + ); + } + #[test] fn browser_and_cdp_backend_allow_capable_context_attempts() { for settings in [ From 4b3d3ee3938eb63b06739378c14fe60fda2826bb Mon Sep 17 00:00:00 2001 From: tomi Date: Wed, 18 Nov 2026 01:09:38 +0100 Subject: [PATCH 3/3] fix(mcp): satisfy strict Clippy lint for config parser --- src/upstream_control.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/upstream_control.rs b/src/upstream_control.rs index 816abc78..f95f350d 100644 --- a/src/upstream_control.rs +++ b/src/upstream_control.rs @@ -35,16 +35,16 @@ impl PlaywrightBackendMode { arg.strip_prefix("--config=") } }) - .last() + .next_back() .map(str::to_owned) .or_else(|| spec.env.get("PLAYWRIGHT_MCP_CONFIG").cloned()) .or_else(|| std::env::var("PLAYWRIGHT_MCP_CONFIG").ok())?; let mut path = std::path::PathBuf::from(path); - if path.is_relative() { - if let Some(cwd) = spec.cwd.as_ref() { - path = std::path::Path::new(cwd).join(path); - } + if path.is_relative() + && let Some(cwd) = spec.cwd.as_ref() + { + path = std::path::Path::new(cwd).join(path); } let parsed = std::fs::read_to_string(path) .ok()