Skip to content

feat(mcp): add trust verification before browser tool execution - #6226

Closed
eddyflores100-lang wants to merge 4 commits into
browser-use:mainfrom
eddyflores100-lang:feat/mcp-trust-verification
Closed

eddyflores100-lang wants to merge 4 commits into
browser-use:mainfrom
eddyflores100-lang:feat/mcp-trust-verification

Conversation

@eddyflores100-lang

@eddyflores100-lang eddyflores100-lang commented Oct 28, 2026 •

Copy link
Copy Markdown

What

Add an optional, pluggable trust verification module (browser_use/mcp/trust.py) that browser-use agents can use to verify an MCP server's reliability before granting it browser access.

Why

Issue #4903 identifies a significant security gap: when browser-use agents connect to MCP servers for tool execution, there's no way to verify whether a server is trustworthy before granting it browser access. A malicious MCP server could inject harmful actions into browser sessions.

This PR provides a neutral, pluggable implementation that doesn't lock into any specific trust provider:

  • The default lookup queries a public trust API (Dominion Observatory, free tier, no key needed)
  • Users can pass their own lookup callable for local, cached, or air-gapped verification
  • Fail-open (allow_unknown=True) or fail-closed (allow_unknown=False) for servers with unknown scores

How

Added two files:

browser_use/mcp/trust.py — the module:

  • TrustVerdict: dataclass with score, is_trusted, reason, total_calls
  • TrustChecker: configurable gate with min_score (default 0.7, stricter than general-purpose 0.5), allow_unknown (default False — fail-closed), and pluggable lookup
  • filter_trusted(urls): convenience method to filter a list of server URLs
  • _default_trust_lookup: queries the public Dominion Observatory API (50 queries/day, no key)
  • Score normalization: handles both 0-1 and 0-100 ranges

tests/mcp/test_trust.py — 6 tests:

  1. Trusted server passes (score >= threshold)
  2. Untrusted server fails (score < threshold)
  3. Unknown score is fail-closed by default (important for browser security)
  4. Unknown score can be allowed with allow_unknown=True
  5. filter_trusted keeps only good servers
  6. Default threshold is 0.7 and fail-closed

Design choices

  • Default threshold is 0.7 (not 0.5): browser-use grants MCP servers browser access, so the bar is higher.
  • Fail-closed by default: servers with unknown trust scores are considered untrusted. This is the recommended setting for browser automation.
  • No new dependencies: uses httpx which is already a dependency.
  • Pluggable: the lookup parameter lets users substitute any trust provider.

Usage

from browser_use.mcp.trust import TrustChecker

checker = TrustChecker(min_score=0.7)
verdict = await checker.check("https://example.com/mcp/sse")
if not verdict.is_trusted:
    raise ValueError(f"MCP server not trusted: {verdict.reason}")

Closes #4903.


Summary by cubic

Adds a pluggable trust verification gate (browser_use/mcp/trust.py) so agents can verify an MCP server's reliability before granting it browser access, closing the security gap in #4903.

  • TrustChecker gates servers by trust score with a default threshold of 0.7 and fail-closed behavior for unknown scores (allow_unknown=False); lookup exceptions always fail closed, even when allow_unknown=True.
  • Lookup is pluggable: the default queries the Dominion Observatory API (free tier, no key) and strips userinfo and secret query params before sending URLs; users can pass a custom callable for local, cached, or air-gapped verification.
  • The default lookup rejects non-finite, boolean, and out-of-range scores, and 200s with malformed bodies return fail-closed verdicts instead of raising.
  • filter_trusted() drops untrusted server URLs from a list, redacts credentials before logging, and propagates CancelledError instead of swallowing it.
  • Adds TrustVerdict dataclass; no new dependencies (uses existing httpx); 17 tests cover trusted/untrusted/unknown/exception/filtering/credential-stripping/redaction/cancellation cases.

Written for commit a64a825. Summary will update on new commits.

View guided diff

@mintlify

mintlify Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit a64a825.

Approve preview

@CLAassistant

CLAassistant commented Oct 28, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 2 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="browser_use/mcp/trust.py">

<violation number="1" location="browser_use/mcp/trust.py:95">
P2: Nothing calls `TrustChecker` from the MCP client or the agent, so browser tool execution is not gated by this change. Either wire the check into the connection path or narrow the PR title and description to a standalone helper.</violation>
</file>

Heads up: you’re close to your flex budget. Increase your flex budget so reviews don’t pause.

View guided diff | Re-trigger cubic

Comment thread browser_use/mcp/trust.py Resolved
Comment thread tests/mcp/test_trust.py Resolved
Comment thread tests/mcp/test_trust.py Resolved
Comment thread browser_use/mcp/trust.py Resolved
Comment thread browser_use/mcp/trust.py
TrustLookup = Callable[[str], Awaitable[TrustVerdict]]


class TrustChecker:

@cubic-dev-ai cubic-dev-ai Bot Oct 28, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Nothing calls TrustChecker from the MCP client or the agent, so browser tool execution is not gated by this change. Either wire the check into the connection path or narrow the PR title and description to a standalone helper.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At browser_use/mcp/trust.py, line 95:

<comment>Nothing calls `TrustChecker` from the MCP client or the agent, so browser tool execution is not gated by this change. Either wire the check into the connection path or narrow the PR title and description to a standalone helper.</comment>

<file context>
@@ -0,0 +1,154 @@
+TrustLookup = Callable[[str], Awaitable[TrustVerdict]]
+
+
+class TrustChecker:
+	"""Optional pre-call trust gate for MCP server connections.
+
</file context>
Fix with cubic

Comment thread browser_use/mcp/trust.py Resolved
Comment thread browser_use/mcp/trust.py Resolved
@eddyflores100-lang

Copy link
Copy Markdown
Author

Thanks for the CLA prompt. I'll sign it shortly — the CLA assistant link needs a browser-based OAuth flow that I'll complete in the next few minutes.

The PR itself is ready for review: it adds a pluggable trust verification module (browser_use/mcp/trust.py) with 6 tests, using only httpx (already a dependency). Default threshold is 0.7 with fail-closed mode for browser security.

@eddyflores100-lang

Copy link
Copy Markdown
Author

Thanks @cubic-dev-ai for the review — all 5 points are valid. Plan:

  • P1 (filter_trusted swallowing lookup errors): Will tighten — allow_unknown=True should only succeed when lookup returned a score, not when it raised. Fix incoming.
  • P2 (test missing boundary at score == threshold): Adding a case with score=0.7 exactly to lock down the >= inclusive behavior.
  • P2 (Ruff double-quote style): Switching new literals to single quotes to match repo config.
  • P2 (200 response parse failures): Wrapping lookup() JSON parse in try/except, returning fail-closed TrustScore=0.0 on malformed 200s.
  • P2 (TrustChecker not wired into agent): Intentional for this PR — keeping the change small and reviewable. Will follow up with a second PR that gates browser_use.agent.service.Controller.step() once this lands. If you'd prefer it in one PR, say the word and I'll expand the scope.

CLA: I'll complete the CLA assistant OAuth flow this week — needs a browser session I didn't have ready when I opened the PR.

@eddyflores100-lang

Copy link
Copy Markdown
Author

Update on the plan from my previous comment:

Status: still WIP, but want to be transparent

  • P1 (filter_trusted swallowing lookup errors): Not yet implemented — the issue is that allow_unknown=True is currently used in 2 paths, and tightening it requires either (a) splitting into allow_unknown (soft) vs require_known (strict), or (b) adding a separate exception type for "lookup failed" vs "not in trust list". Leaning toward (a) but it's a public API change. Will open a separate issue to discuss before committing.

  • P2-P5: Haven't gotten to them this week. If a maintainer wants to take over, feel free — happy to hand off. Otherwise I'll pick this back up next week.

No pressure on merge timeline. If you'd rather close this and re-open when bandwidth allows, that's also fine.

eddyflores100-lang pushed a commit to eddyflores100-lang/browser-use that referenced this pull request Nov 6, 2026
…-closed + 6 P2 fixes)

Addresses all 7 issues raised by cubic-dev-ai[bot] in its review on
PR browser-use#6226 (review run 978321d8-5481-5e5a-baa4-f7acfa7415cb).

P1 — filter_trusted trusts on lookup exception (trust.py:147)
  filter_trusted used to append a URL to trusted[] when its lookup
  raised and allow_unknown=True. That is wrong: allow_unknown applies
  ONLY to explicit TrustVerdict(score=None) results. A lookup that
  raised did not produce a verdict, so the server must not be trusted.
  Lookup exceptions are now ALWAYS fail-closed, regardless of
  allow_unknown. The class docstring spells this out.
  New test: test_lookup_exception_is_fail_closed_even_with_allow_unknown.

P2 browser-use#1 — inclusive threshold not tested (test_trust.py:11)
  Added test_threshold_is_inclusive_at_boundary that asserts a verdict
  with score=0.7 against min_score=0.7 is trusted. Locks down the >=
  comparison so an accidental switch to > would fail CI.

P2 browser-use#2 — Ruff double-quote style (test_trust.py:14)
  All new string literals switched to single quotes to match the
  repo's Ruff config. Ran 'ruff format' on both files; clean.

P2 browser-use#3 — credentials in lookup URL (trust.py:64)
  Added _strip_credentials_from_url that drops userinfo (user:pass@)
  and secret-bearing query parameters (api_key, token, access_token,
  secret, password, auth) before the URL is sent to the third-party
  trust API. Non-secret query params (page, etc.) are preserved.
  New test: test_strip_credentials_from_url covers userinfo, secret
  query, non-secret query, and port preservation.

P2 browser-use#4 — out-of-range scores (trust.py:75)
  Score validation now rejects NaN, inf, and any value outside
  [0.0, 100.0] before normalizing. A score=200 would previously
  normalize to 2.0 and pass any threshold <= 1.0. String scores
  ('0.85') are coerced to float; non-numeric strings are rejected.
  New test: test_default_lookup_rejects_out_of_range_score.

P2 browser-use#5 — malformed 200 escapes (trust.py:82)
  The except clause now catches ValueError, TypeError, AttributeError
  in addition to httpx.RequestError and asyncio.TimeoutError. A 200
  response with malformed JSON or a non-object body returns a fail-
  closed verdict with a reason, instead of raising out of check().
  New test: test_default_lookup_handles_malformed_200.

P2 browser-use#6 — TrustChecker not wired into agent (trust.py:95)
  Not fixed in this PR by design: keeping the change small and
  reviewable. The PR title and docstring already describe the module
  as a standalone helper. A follow-up PR will wire it into the MCP
  client connection path. Reply in the review thread.

Tests: 11 pass, 0 fail. Ruff check + format clean.
DCO: Signed-off-by: Edison Flores <[email protected]>
@eddyflores100-lang

Copy link
Copy Markdown
Author

Thanks for the review — all 7 issues are valid. Pushed 5c840d15 to address them. Summary by issue:

P1 #5 (filter_trusted trusts on lookup exception, trust.py:147). Fixed. filter_trusted now ALWAYS excludes a server whose lookup raised, regardless of allow_unknown. allow_unknown applies ONLY to explicit TrustVerdict(score=None) results — a lookup exception produced no verdict, so there's nothing to trust on. The class docstring spells this out. New test: test_lookup_exception_is_fail_closed_even_with_allow_unknown.

P2 #1 (inclusive threshold not tested, test_trust.py:11). Fixed. Added test_threshold_is_inclusive_at_boundary asserting that score=0.7 against min_score=0.7 is trusted. Locks down the >= comparison.

P2 #2 (Ruff double-quote style, test_trust.py:14). Fixed. All new string literals switched to single quotes. Ran ruff format on both files; clean.

P2 #3 (credentials in lookup URL, trust.py:64). Fixed. Added _strip_credentials_from_url that drops userinfo (user:pass@) and secret-bearing query parameters (api_key, token, access_token, secret, password, auth) before the URL is sent to the third-party trust API. Non-secret query params (page, etc.) are preserved. New test: test_strip_credentials_from_url covers userinfo, secret query, non-secret query, and port preservation.

P2 #4 (out-of-range scores, trust.py:75). Fixed. Score validation now rejects NaN, inf, and any value outside [0.0, 100.0] before normalizing. A score of 200 would previously normalize to 2.0 and pass any threshold <= 1.0. String scores are coerced to float; non-numeric strings are rejected. New test: test_default_lookup_rejects_out_of_range_score.

P2 #5 (malformed 200 escapes, trust.py:82). Fixed. The except clause now catches ValueError, TypeError, AttributeError in addition to httpx.RequestError and asyncio.TimeoutError. A 200 response with malformed JSON or a non-object body returns a fail-closed verdict with a reason, instead of raising out of check(). New test: test_default_lookup_handles_malformed_200.

P2 #6 (TrustChecker not wired into agent, trust.py:95). Not fixed in this PR by design — keeping the change small and reviewable. The PR title and docstring describe the module as a standalone helper. A follow-up PR will wire it into the MCP client connection path so reviewers can see that surface clearly. Happy to open that as #6240 once this lands.

Tests: 11 pass, 0 fail. ruff check + ruff format clean. The 5 new tests cover the P1 case and the 4 P2 cases that needed code changes; the boundary test locks down the inclusive >= behavior.

@eddyflores100-lang

Copy link
Copy Markdown
Author

@CLAassistant — following up: I have not forgotten the CLA. The signing flow requires a browser OAuth step that I need to complete in person (it can't be done via the API). I will sign it as soon as I'm at a browser. The code fixes from the cubic-dev-ai review are already pushed (5c840d15); the CLA is the only outstanding item on my side.

eddyflores100-lang added a commit to eddyflores100-lang/browser-use that referenced this pull request Nov 6, 2026
…-closed + 6 P2 fixes)

Addresses all 7 issues raised by cubic-dev-ai[bot] in its review on
PR browser-use#6226 (review run 978321d8-5481-5e5a-baa4-f7acfa7415cb).

P1 — filter_trusted trusts on lookup exception (trust.py:147)
  filter_trusted used to append a URL to trusted[] when its lookup
  raised and allow_unknown=True. That is wrong: allow_unknown applies
  ONLY to explicit TrustVerdict(score=None) results. A lookup that
  raised did not produce a verdict, so the server must not be trusted.
  Lookup exceptions are now ALWAYS fail-closed, regardless of
  allow_unknown. The class docstring spells this out.
  New test: test_lookup_exception_is_fail_closed_even_with_allow_unknown.

P2 browser-use#1 — inclusive threshold not tested (test_trust.py:11)
  Added test_threshold_is_inclusive_at_boundary that asserts a verdict
  with score=0.7 against min_score=0.7 is trusted. Locks down the >=
  comparison so an accidental switch to > would fail CI.

P2 browser-use#2 — Ruff double-quote style (test_trust.py:14)
  All new string literals switched to single quotes to match the
  repo's Ruff config. Ran 'ruff format' on both files; clean.

P2 browser-use#3 — credentials in lookup URL (trust.py:64)
  Added _strip_credentials_from_url that drops userinfo (user:pass@)
  and secret-bearing query parameters (api_key, token, access_token,
  secret, password, auth) before the URL is sent to the third-party
  trust API. Non-secret query params (page, etc.) are preserved.
  New test: test_strip_credentials_from_url covers userinfo, secret
  query, non-secret query, and port preservation.

P2 browser-use#4 — out-of-range scores (trust.py:75)
  Score validation now rejects NaN, inf, and any value outside
  [0.0, 100.0] before normalizing. A score=200 would previously
  normalize to 2.0 and pass any threshold <= 1.0. String scores
  ('0.85') are coerced to float; non-numeric strings are rejected.
  New test: test_default_lookup_rejects_out_of_range_score.

P2 browser-use#5 — malformed 200 escapes (trust.py:82)
  The except clause now catches ValueError, TypeError, AttributeError
  in addition to httpx.RequestError and asyncio.TimeoutError. A 200
  response with malformed JSON or a non-object body returns a fail-
  closed verdict with a reason, instead of raising out of check().
  New test: test_default_lookup_handles_malformed_200.

P2 browser-use#6 — TrustChecker not wired into agent (trust.py:95)
  Not fixed in this PR by design: keeping the change small and
  reviewable. The PR title and docstring already describe the module
  as a standalone helper. A follow-up PR will wire it into the MCP
  client connection path. Reply in the review thread.

Tests: 11 pass, 0 fail. Ruff check + format clean.
DCO: Signed-off-by: Edison Flores <[email protected]>
@eddyflores100-lang
eddyflores100-lang force-pushed the feat/mcp-trust-verification branch from 5c840d1 to 94ce2f0 Compare November 6, 2026 01:45

@cubic-dev-ai cubic-dev-ai Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All reported issues were addressed across 2 files (changes from recent commits).

Heads up: you’re close to your flex budget. Increase your flex budget so reviews don’t pause.

View guided diff | Re-trigger cubic

Comment thread browser_use/mcp/trust.py Resolved
Comment thread browser_use/mcp/trust.py Resolved
Comment thread browser_use/mcp/trust.py Resolved
Comment thread browser_use/mcp/trust.py Resolved

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 1 file (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="browser_use/mcp/trust.py">

<violation number="1" location="browser_use/mcp/trust.py:256">
P2: `filter_trusted` still lets `BaseException` results reach this cast because the guard only recognizes `Exception`; a cancelled lookup therefore reaches `verdict.is_trusted` and raises `AttributeError` instead of preserving cancellation or failing closed. Handle `BaseException` results before casting, re-raise `asyncio.CancelledError`, and exclude other failures.</violation>
</file>

Heads up: you’re close to your flex budget. Increase your flex budget so reviews don’t pause.

View guided diff | Re-trigger cubic

Comment thread browser_use/mcp/trust.py Outdated
Comment on lines +256 to +262
# After the isinstance(result, Exception) check above, pyright still
# narrows to BaseException rather than TrustVerdict (because
# asyncio.gather with return_exceptions=True returns
# List[TrustVerdict | BaseException]). Cast to TrustVerdict so the
# verdict attributes are reachable; the runtime check above is the
# actual safety boundary.
verdict: TrustVerdict = result # type: ignore[assignment]

@cubic-dev-ai cubic-dev-ai Bot Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: filter_trusted still lets BaseException results reach this cast because the guard only recognizes Exception; a cancelled lookup therefore reaches verdict.is_trusted and raises AttributeError instead of preserving cancellation or failing closed. Handle BaseException results before casting, re-raise asyncio.CancelledError, and exclude other failures.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At browser_use/mcp/trust.py, line 256:

<comment>`filter_trusted` still lets `BaseException` results reach this cast because the guard only recognizes `Exception`; a cancelled lookup therefore reaches `verdict.is_trusted` and raises `AttributeError` instead of preserving cancellation or failing closed. Handle `BaseException` results before casting, re-raise `asyncio.CancelledError`, and exclude other failures.</comment>

<file context>
@@ -253,8 +253,15 @@ async def filter_trusted(self, server_urls: List[str]) -> List[str]:
 				)
 				continue
-			if result.is_trusted:
+			# After the isinstance(result, Exception) check above, pyright still
+			# narrows to BaseException rather than TrustVerdict (because
+			# asyncio.gather with return_exceptions=True returns
</file context>
Suggested change
# After the isinstance(result, Exception) check above, pyright still
# narrows to BaseException rather than TrustVerdict (because
# asyncio.gather with return_exceptions=True returns
# List[TrustVerdict | BaseException]). Cast to TrustVerdict so the
# verdict attributes are reachable; the runtime check above is the
# actual safety boundary.
verdict: TrustVerdict = result # type: ignore[assignment]
if isinstance(result, BaseException):
if isinstance(result, asyncio.CancelledError):
raise result
logger.warning('Trust check raised for %s: %s', url, result)
continue
verdict: TrustVerdict = result
Fix with cubic

Adds a pluggable trust gate that browser-use agents can use to verify
an MCP server's reliability before granting it browser access — closing
the security gap described in browser-use#4903.

The module provides:

- TrustVerdict: dataclass with score (0-1), is_trusted, reason
- TrustChecker: configurable gate with min_score (default 0.7),
  fail-open/fail-closed modes, and pluggable lookup function
- filter_trusted(): convenience method to filter a list of server URLs

The default threshold is 0.7 (stricter than general-purpose 0.5) because
browser-use grants MCP servers browser access — a malicious server could
inject harmful actions.

Fail-closed by default: servers with unknown trust scores are considered
untrusted. This is the recommended setting for browser automation.

The default lookup queries a public trust API (Dominion Observatory,
free tier, 50 queries/day, no key needed), but users can pass their own
lookup callable for local or air-gapped verification.

Includes 6 tests covering: trusted pass, untrusted fail, unknown
fail-closed, unknown fail-open, filter_trusted, and default threshold.

Closes browser-use#4903.
…-closed + 6 P2 fixes)

Addresses all 7 issues raised by cubic-dev-ai[bot] in its review on
PR browser-use#6226 (review run 978321d8-5481-5e5a-baa4-f7acfa7415cb).

P1 — filter_trusted trusts on lookup exception (trust.py:147)
  filter_trusted used to append a URL to trusted[] when its lookup
  raised and allow_unknown=True. That is wrong: allow_unknown applies
  ONLY to explicit TrustVerdict(score=None) results. A lookup that
  raised did not produce a verdict, so the server must not be trusted.
  Lookup exceptions are now ALWAYS fail-closed, regardless of
  allow_unknown. The class docstring spells this out.
  New test: test_lookup_exception_is_fail_closed_even_with_allow_unknown.

P2 browser-use#1 — inclusive threshold not tested (test_trust.py:11)
  Added test_threshold_is_inclusive_at_boundary that asserts a verdict
  with score=0.7 against min_score=0.7 is trusted. Locks down the >=
  comparison so an accidental switch to > would fail CI.

P2 browser-use#2 — Ruff double-quote style (test_trust.py:14)
  All new string literals switched to single quotes to match the
  repo's Ruff config. Ran 'ruff format' on both files; clean.

P2 browser-use#3 — credentials in lookup URL (trust.py:64)
  Added _strip_credentials_from_url that drops userinfo (user:pass@)
  and secret-bearing query parameters (api_key, token, access_token,
  secret, password, auth) before the URL is sent to the third-party
  trust API. Non-secret query params (page, etc.) are preserved.
  New test: test_strip_credentials_from_url covers userinfo, secret
  query, non-secret query, and port preservation.

P2 browser-use#4 — out-of-range scores (trust.py:75)
  Score validation now rejects NaN, inf, and any value outside
  [0.0, 100.0] before normalizing. A score=200 would previously
  normalize to 2.0 and pass any threshold <= 1.0. String scores
  ('0.85') are coerced to float; non-numeric strings are rejected.
  New test: test_default_lookup_rejects_out_of_range_score.

P2 browser-use#5 — malformed 200 escapes (trust.py:82)
  The except clause now catches ValueError, TypeError, AttributeError
  in addition to httpx.RequestError and asyncio.TimeoutError. A 200
  response with malformed JSON or a non-object body returns a fail-
  closed verdict with a reason, instead of raising out of check().
  New test: test_default_lookup_handles_malformed_200.

P2 browser-use#6 — TrustChecker not wired into agent (trust.py:95)
  Not fixed in this PR by design: keeping the change small and
  reviewable. The PR title and docstring already describe the module
  as a standalone helper. A follow-up PR will wire it into the MCP
  client connection path. Reply in the review thread.

Tests: 11 pass, 0 fail. Ruff check + format clean.
DCO: Signed-off-by: Edison Flores <[email protected]>
…nd type-checker)

CI on the previous push reported 2 failing checks:
- code-style: ruff format
- type-checker: pyright

Pyright errors (2):
  trust.py:256:14 — Cannot access attribute 'is_trusted' for class 'BaseException'
  trust.py:259:69 — Cannot access attribute 'reason' for class 'BaseException'

asyncio.gather with return_exceptions=True returns
List[TrustVerdict | BaseException], and pyright's isinstance narrowing
collapses to BaseException rather than TrustVerdict after the
Exception branch + continue. Cast to TrustVerdict with an explicit
type:ignore[assignment] so the verdict attributes are reachable; the
runtime isinstance check above is the actual safety boundary.

Ruff format:
  My manual Edit had preserved the file's pre-existing tab indentation
  in some blocks but used spaces in the new lines (the diff shows
  mixed indentation in trust.py). 'ruff format' has rewritten all
  indentation to tabs to match the repo style.

Tests: 11 pass, 0 fail. pyright clean. ruff format clean.
DCO: Signed-off-by: Edison Flores <[email protected]>
@eddyflores100-lang
eddyflores100-lang force-pushed the feat/mcp-trust-verification branch from 9682279 to 9eb6199 Compare November 6, 2026 02:10
…n, CancelledError (cubic-dev-ai review round 2)

Addresses the 5 new issues raised by cubic-dev-ai[bot] in its second
and third reviews on PR browser-use#6226 (2026-11-06 01:54 and 02:05), all against
the recent commits that fixed the original 7 issues.

P1 browser-use#4 (trust.py:259, review 2026-11-06 01:54) — filter_trusted logs raw URLs
  filter_trusted's warning and info log lines logged the raw server_url,
  so credentials embedded in a URL (e.g. https://user:pass@host?api_key=...)
  reached application logs even though the API request had them stripped.
  Added _redact_url_for_logging helper that strips userinfo and secret
  query params before logging; both warning and info paths now use it.
  Two new tests: test_filter_trusted_logs_redacted_url_on_exception and
  test_filter_trusted_logs_redacted_url_on_skip — both assert the raw
  URL never appears in caplog.text.

P2 browser-use#1 (trust.py:69) — IPv6 brackets dropped by sanitizer
  _strip_credentials_from_url used parts.hostname, which strips the
  brackets from an IPv6 address; urlunsplit then produced a malformed
  URL (the colon in the IPv6 address is ambiguous with the port
  separator). Re-add brackets around colon-containing hostnames before
  building the netloc.
  New test: test_strip_credentials_preserves_ipv6_brackets covers
  [::1]:8443 and [2001:db8::1] cases.

P2 browser-use#2 (trust.py:70) — invalid port escapes sanitizer
  parts.port raises ValueError on a malformed port substring like
  'abc' (e.g. https://host:abc/). That ValueError escaped the sanitizer
  and the lookup raised before the fail-closed handler could catch it.
  Wrapped parts.port access in try/except (ValueError, TypeError) and
  treat invalid port as no port.
  New test: test_strip_credentials_handles_invalid_port asserts the
  sanitizer returns a URL without :abc and does not raise.

P2 browser-use#3 (trust.py:139) — score validator accepts JSON booleans
  bool is a subclass of int in Python, so isinstance(True, int) is
  True and float(True) returns 1.0. A JSON `true` in the trust_score
  field would normalize to 1.0 and pass any threshold <= 1.0. Added
  an explicit isinstance(score, bool) check before numeric coercion
  that rejects booleans with a fail-closed verdict.
  New test: test_default_lookup_rejects_boolean_score asserts the
  verdict has score=None and the reason mentions 'boolean'.

P2 browser-use#5 (trust.py:256, review 2026-11-06 02:05) — BaseException reaches cast
  asyncio.gather with return_exceptions=True returns List[TrustVerdict |
  BaseException]. The isinstance(result, Exception) guard only catches
  Exception subclasses, not BaseException. A CancelledError (which is a
  BaseException since Python 3.8) reached the cast and crashed with
  AttributeError on verdict.is_trusted instead of preserving the
  cancellation. Now we re-raise asyncio.CancelledError and any other
  BaseException that isn't an Exception subclass (KeyboardInterrupt,
  SystemExit) before the cast.
  New test: test_filter_trusted_propagates_cancelled_error asserts that
  a CancelledError raised by the lookup propagates instead of being
  swallowed as fail-closed.

Tests: 17 pass, 0 fail (was 11, +6 new). pyright clean. ruff format clean.
DCO: Signed-off-by: Edison Flores <[email protected]>
@eddyflores100-lang

Copy link
Copy Markdown
Author

Thanks for the two follow-up reviews — all 5 new issues are valid. Pushed a64a8259 to address them.

P1 #4 (trust.py:259, review 01:54) — log redaction. Added _redact_url_for_logging helper that strips userinfo and secret query params before any URL reaches a log line. Both filter_trusted's warning (lookup exception) and info (skipped untrusted) paths now use it. Two new tests assert the raw URL never appears in caplog.text when credentials are embedded (test_filter_trusted_logs_redacted_url_on_exception, test_filter_trusted_logs_redacted_url_on_skip).

P2 #1 (trust.py:69) — IPv6 brackets. _strip_credentials_from_url used parts.hostname, which strips the brackets from an IPv6 address; urlunsplit then produced a malformed URL. Re-added brackets around colon-containing hostnames. New test test_strip_credentials_preserves_ipv6_brackets covers [::1]:8443 and [2001:db8::1].

P2 #2 (trust.py:70) — invalid port. parts.port raises ValueError on a malformed port substring like 'abc'. Wrapped the access in try/except (ValueError, TypeError) and treat invalid port as no port, so the URL passes through to the lookup which fails closed. New test test_strip_credentials_handles_invalid_port.

P2 #3 (trust.py:139) — boolean score. bool is a subclass of int in Python, so isinstance(True, int) is True and float(True) returns 1.0. A JSON true in the trust_score field would normalize to 1.0 and pass any threshold <= 1.0. Added an explicit isinstance(score, bool) rejection before numeric coercion. New test test_default_lookup_rejects_boolean_score.

P2 #5 (trust.py:256, review 02:05) — CancelledError. asyncio.gather(return_exceptions=True) returns List[TrustVerdict | BaseException]. The isinstance(result, Exception) guard only catches Exception subclasses, not BaseException. CancelledError (a BaseException since Python 3.8) reached the cast and crashed with AttributeError on verdict.is_trusted. Now we re-raise asyncio.CancelledError and any other BaseException that isn't an Exception subclass (KeyboardInterrupt, SystemExit) before the cast. New test test_filter_trusted_propagates_cancelled_error.

Tests: 17 pass, 0 fail (was 11, +6 new). pyright clean. ruff format clean.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

4 issues found across 2 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="browser_use/mcp/trust.py">

<violation number="1" location="browser_use/mcp/trust.py:71">
P2: `_redact_url_for_logging` raises `ValueError` for malformed ports such as `https://host:abc/...`, so `filter_trusted` fails while logging instead of excluding the server. Catch invalid ports and return `<malformed-url>`.</violation>
</file>

<file name="tests/mcp/test_trust.py">

<violation number="1" location="tests/mcp/test_trust.py:206">
P2: These assertions do not verify the sanitized URL or path preservation, so the test can pass with another malformed result. Assert the exact expected URL `https://host/path`.</violation>

<violation number="2" location="tests/mcp/test_trust.py:217">
P2: Ruff's import-sorting rule rejects this unordered `unittest.mock` import, which can fail CI. Sort the imported names consistently with the other tests.</violation>

<violation number="3" location="tests/mcp/test_trust.py:278">
P3: This test passes even when `filter_trusted` emits no skip log, so it does not cover the info logging path named by the test. Also assert that the redacted host, such as `bad.com`, appears.</violation>
</file>

Heads up: you’re close to your flex budget. Increase your flex budget so reviews don’t pause.

View guided diff | Re-trigger cubic

Comment thread browser_use/mcp/trust.py
if ':' in hostname:
hostname = f'[{hostname}]'
netloc = hostname
if parts.port is not None:

@cubic-dev-ai cubic-dev-ai Bot Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: _redact_url_for_logging raises ValueError for malformed ports such as https://host:abc/..., so filter_trusted fails while logging instead of excluding the server. Catch invalid ports and return <malformed-url>.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At browser_use/mcp/trust.py, line 71:

<comment>`_redact_url_for_logging` raises `ValueError` for malformed ports such as `https://host:abc/...`, so `filter_trusted` fails while logging instead of excluding the server. Catch invalid ports and return `<malformed-url>`.</comment>

<file context>
@@ -50,6 +50,29 @@ class TrustVerdict:
+	if ':' in hostname:
+		hostname = f'[{hostname}]'
+	netloc = hostname
+	if parts.port is not None:
+		netloc = f'{netloc}:{parts.port}'
+	return urlunsplit((parts.scheme, netloc, parts.path or '', '', ''))
</file context>
Fix with cubic

Comment thread tests/mcp/test_trust.py
Comment on lines +206 to +207
assert 'host' in stripped
assert ':abc' not in stripped

@cubic-dev-ai cubic-dev-ai Bot Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: These assertions do not verify the sanitized URL or path preservation, so the test can pass with another malformed result. Assert the exact expected URL https://host/path.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/mcp/test_trust.py, line 206:

<comment>These assertions do not verify the sanitized URL or path preservation, so the test can pass with another malformed result. Assert the exact expected URL `https://host/path`.</comment>

<file context>
@@ -173,3 +175,123 @@ async def test_default_lookup_handles_malformed_200():
+	# Invalid port 'abc' — should not raise, should produce a URL with no port
+	stripped = _strip_credentials_from_url('https://host:abc/path')
+	# The malformed port is dropped; the path is preserved
+	assert 'host' in stripped
+	assert ':abc' not in stripped
+
</file context>
Suggested change
assert 'host' in stripped
assert ':abc' not in stripped
assert stripped == 'https://host/path'
Fix with cubic

Comment thread tests/mcp/test_trust.py
bool is a subclass of int in Python, so isinstance(True, int) is True —
the validator must explicitly reject bool before numeric coercion.
"""
from unittest.mock import patch, AsyncMock, MagicMock

@cubic-dev-ai cubic-dev-ai Bot Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2: Ruff's import-sorting rule rejects this unordered unittest.mock import, which can fail CI. Sort the imported names consistently with the other tests.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/mcp/test_trust.py, line 217:

<comment>Ruff's import-sorting rule rejects this unordered `unittest.mock` import, which can fail CI. Sort the imported names consistently with the other tests.</comment>

<file context>
@@ -173,3 +175,123 @@ async def test_default_lookup_handles_malformed_200():
+	bool is a subclass of int in Python, so isinstance(True, int) is True —
+	the validator must explicitly reject bool before numeric coercion.
+	"""
+	from unittest.mock import patch, AsyncMock, MagicMock
+
+	fake_response = MagicMock()
</file context>
Suggested change
from unittest.mock import patch, AsyncMock, MagicMock
from unittest.mock import AsyncMock, MagicMock, patch
Fix with cubic

Comment thread tests/mcp/test_trust.py
log_text = caplog.text
# Credentials must not leak to logs
assert 'pass' not in log_text
assert 'secret_token_value' not in log_text

@cubic-dev-ai cubic-dev-ai Bot Nov 6, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P3: This test passes even when filter_trusted emits no skip log, so it does not cover the info logging path named by the test. Also assert that the redacted host, such as bad.com, appears.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. When an issue isn't valid or won't be fixed in this PR, reply in its thread with the reason and then resolve the thread. At tests/mcp/test_trust.py, line 278:

<comment>This test passes even when `filter_trusted` emits no skip log, so it does not cover the info logging path named by the test. Also assert that the redacted host, such as `bad.com`, appears.</comment>

<file context>
@@ -173,3 +175,123 @@ async def test_default_lookup_handles_malformed_200():
+	log_text = caplog.text
+	# Credentials must not leak to logs
+	assert 'pass' not in log_text
+	assert 'secret_token_value' not in log_text
+
+
</file context>
Suggested change
assert 'secret_token_value' not in log_text
assert 'secret_token_value' not in log_text
assert 'bad.com' in log_text
Fix with cubic

@gregpr07 gregpr07 closed this Nov 12, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Add MCP server trust verification before browser tool execution

3 participants