feat: add mock-network tool for intercepting and stubbing browser requests#32
Merged
cryptotavares merged 1 commit intoMay 29, 2026
Conversation
OGPoyraz
approved these changes
May 29, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Current State
The tool system provides 29 tools covering browser interaction, navigation, state management, knowledge, and advanced capabilities (CDP, batching). However, there is no built-in mechanism for intercepting and stubbing HTTP network requests during an active browser session. Agents and developers who need to mock API responses — for example, stubbing
accounts.api.cx.metamask.ioendpoints to return controlled balances or network lists — must either rely on external mock servers (viaMockServerCapability) or use raw CDP commands, both of which require significant setup and lack structured observability.Solution
This PR adds a new
mock_networktool (tool #30) that provides targeted Playwright-based network interception directly on the activeBrowserContext. It exposes four actions —add,clear,list, andrequests— through both the tool system (POST /tool/mock_network) and the CLI (mm mock-network <action>).Architecture
How It Works
The system is built around a
NetworkMockRouteManagerclass that manages Playwright route handlers for a givenBrowserContext. Manager instances are stored in a module-levelWeakMap<BrowserContext, NetworkMockRouteManager>, ensuring one manager per browser context with automatic garbage collection when the context is destroyed.Origin-Scoped Interception
Rather than installing a separate Playwright route handler per rule, the manager installs one handler per unique origin (e.g.,
https://accounts.api.cx.metamask.io/**). When a request arrives, the shared handler iterates rules in reverse order (newest first) to find a match by HTTP method and URL pattern. This avoids handler proliferation and ensures that replacing a rule with the sameidbut a different origin correctly unroutes the orphaned origin pattern.URL Matching
Rules support exact URLs and simple glob patterns:
https://api.example.com/v2/supportedNetworks*): matches any segment except/— e.g.,https://api.example.com/*.json**): matches everything including/— e.g.,https://api.example.com/v5/balances**Glob patterns are converted to
RegExpat match time viaglobToRegExp().Rule Lifecycle
id. Adding a rule with an existingidreplaces it. If the replaced rule's origin is no longer used by any remaining rule, the origin's Playwright route handler is removed (unroute).--limitfor the most recent N entries. The manager retains up to 500 records (configurable), evicting oldest entries on overflow.Response Construction
Each rule specifies a response with:
status(default: 200)jsonorbody(mutually exclusive — validated by Zod schema)headers(keys normalized to lowercase, merged over defaults)For JSON responses, default headers include
content-type: application/jsonandaccess-control-allow-origin: *. For text responses,content-type: text/plainis used instead.CLI Integration
The
mm mock-networksubcommand routes throughrouteMockNetworkCommand()insrc/cli/mm.ts. The CLI accepts three input shapes foraddand normalizes them before sending to the daemon:{id, method, url, response}{ rule: <object> }[{...}, {...}]{ routes: <array> }{ routes: [...] }{ routes: <array> }This normalization happens in
normalizeMockNetworkAddPayload().Validation
A Zod schema (
mockNetworkInputSchema) validates all inputs:.transform()http://orhttps://URL (validated by attemptingnew URL())jsonorbody(enforced via.refine())add, exactly one ofruleorroutesmust be providedTool Category
mock_networkis categorized as mutating, meaning tool responses include post-execution observations (state,a11y,testIds).Changes
New Files
src/tools/mock-network.ts— Tool implementation andNetworkMockRouteManagerclasssrc/tools/mock-network.test.ts— 476 lines of tests covering all actions, edge cases, URL matching, and request recordingModified Files
src/cli/mm.ts—routeMockNetworkCommand(),parseJsonArgument(),normalizeMockNetworkAddPayload(), help textsrc/cli/mm.test.ts— CLI routing tests for all mock-network subcommandssrc/tools/registry.ts— Registeredmock_networktool, updated category countssrc/tools/types/tool-inputs.ts— Type definitions for mock network inputssrc/tools/types/tool-outputs.ts— Type definitions for mock network resultssrc/validation/schemas.ts— Zod schemas for route rules and mock-network inputsrc/validation/schemas.test.ts— Schema validation testssrc/tools/index.ts— Re-exportREADME.md— Documentation for the new tool and CLI commandsSKILL.md— Agent-facing reference and error code updatesvitest.config.mts— Updated coverage thresholds