dom-api-tracer-mcp
v2.6.0
Published
MCP Server for DOM Element Selector & API Tracer Chrome Extension — AI-agent bridge with CLI support
Maintainers
Readme
DOM API Tracer - MCP Server
Model Context Protocol (MCP) server for the DOM Element Selector & API Tracer Chrome extension. Provides programmatic access to extension features via MCP tools for AI assistants and automation workflows.
Version: 2.6.0 Protocol: MCP 1.0 License: MIT
Overview
This MCP server acts as a bridge between AI assistants and the DOM Element Selector extension. It exposes 7 powerful, consolidated tools that enable:
- DOM element selection and analysis
- Network request tracing (REST, WebSocket, GraphQL)
- Data source detection (API, SSR, Initial State)
- Code generation for web scraping
- JavaScript execution in page context
The server is protocol-agnostic and works with any MCP-compatible client (Claude Desktop, custom MCP clients, automation tools, etc.).
Features
- 7 Smart Tools: Context-aware API for web analysis & RPA
- CLI Support: Professional command-line interface (
npx dom-api-tracer-mcp) - Modular Architecture: Clean separation of concerns
- HTTP Bridge: REST-like endpoint for extension communication (port 3101)
- Heartbeat System: 15s interval connection monitoring with stale detection
- Singleton Gateway: Prevents port conflicts between multiple agent instances
- Graceful Shutdown: Clean process termination on SIGINT/SIGTERM
- State Management: Intelligent caching and validation
- Workflow Validation: Built-in validators prevent common usage errors
- Rate Limiting: Protects against overload
- Auto-Config: One command to configure Claude/Cursor/Windsurf (
--init) - Auto-Discovery: Extension automatically connects when loaded
Installation
Prerequisites
- Node.js 18 or higher
- DOM Element Selector Chrome extension installed
Setup
Option A: NPM (Recommended)
# Install globally
npm install -g dom-api-tracer-mcp
# Or run directly with npx
npx dom-api-tracer-mcpOption B: From Source
# Navigate to mcp-server directory
cd mcp-server
# Install dependencies
npm install
# Start the server
npm startThe server will start on port 3101 and wait for MCP client connections.
CLI Options
dom-api-tracer-mcp # Start with default port (3101)
dom-api-tracer-mcp --port 3200 # Start on custom port
dom-api-tracer-mcp --init # Auto-configure AI agent config files
dom-api-tracer-mcp --debug # Enable verbose logging
dom-api-tracer-mcp --version # Show version
dom-api-tracer-mcp --help # Show helpEnvironment Variables
MCP_PORTorPORT: HTTP bridge port (default: 3101)MCP_DEBUG: Enable debug logging (1to enable)
# Custom port example
export MCP_PORT=3200
npm startUsage
Starting the Server
IMPORTANT: Do NOT start the server manually with npm start.
The MCP server is designed to be started automatically by AI assistants (Claude Code, Cursor, Antigravity, etc.) when they launch. Starting it manually will cause port conflicts.
The server will auto-start when your AI assistant launches, and you'll see output similar to:
[MCP Server] DOM API Tracer MCP server started successfully
[MCP Server] Version: 2.6.0
[MCP Server] Available tools: 7
[MCP Server] Modular architecture enabled ✅
[MCP Bridge] ✅ HTTP server started on port 3101 (PRIMARY)Connection Requirement: For the extension to connect to the MCP server, you must select an element in the browser first. Open any webpage, click the extension icon, click "Select Element", and click any element on the page.
Connecting MCP Clients
The server uses stdio transport for MCP communication. Configure your MCP client to auto-start the server.
Example Configurations
Claude Code / Claude Desktop:
Edit ~/.config/claude/mcp.json (macOS/Linux) or %APPDATA%\Claude\mcp.json (Windows):
{
"mcpServers": {
"dom-api-tracer": {
"command": "npx",
"args": ["-y", "dom-api-tracer-mcp"]
}
}
}Cursor / Other MCP Clients:
Configure your client's MCP settings to execute:
npx -y dom-api-tracer-mcpThe server will auto-start when your AI assistant launches. Do not run it separately.
Health Check
curl http://localhost:3101/health
# Response: {"status":"ok","extension":"connected"}For AI Assistants: Critical Workflow Guidelines
IMPORTANT: AI assistants using this MCP server must follow strict workflow patterns to ensure reliable operation. Failure to follow these guidelines will result in validation errors and failed operations.
The server implements validation layers and state management to prevent common errors. Follow these guidelines carefully for successful integration.
Prerequisite Validation System
The MCP server implements three validation layers:
- StateValidator: Ensures data freshness and prevents stale reads
- RateLimiter: Prevents overload and excessive requests
- WorkflowHelper: Validates tool dependencies and order
When you receive a validation error, read the error message carefully. It will include:
- What went wrong
- Which prerequisite is missing
- "REQUIRED STEPS" to fix the issue
Tool Workflow Positions
Each tool has a workflow position marker:
- First Step: Can be called without prerequisites
- Second Step: Requires First Step tools to be called first
- Advanced: Requires specific prerequisites
- Utility: Can be called anytime
Critical Rules for AI Assistants
1. Follow Prerequisites
Tools like get_network_trace require get_selected_element to be called first. Always check tool descriptions for prerequisites.
Example Error:
❌ Error: Cannot get network trace without selected element
REQUIRED STEPS:
1. Call get_selected_element first
2. Then call get_network_traceCorrect Workflow:
1. get_selected_element ← First Step
2. get_network_trace ← Second Step (requires step 1)2. Synchronous Operations
The JavaScript execution tool (execute_js) is BLOCKING. It will wait up to 10 seconds for the browser to execute the code and return the result directly. You do not need to wait and call another tool to get results.
Correct Pattern:
1. execute_js(code: "document.title")
→ Returns: "My Page Title"3. Trust "SUGGESTED NEXT STEPS"
Many tool outputs include suggestions:
SUGGESTED NEXT STEPS:
- Call get_network_trace to find matching API calls
- Use execute_js if no API matches found (to extract from page state)Follow these suggestions. They are generated based on the current state and guide you to the correct next action.
4. Data Freshness
Selected element data expires after 10 minutes. If you get a "stale data" error, call get_selected_element again to refresh.
Common Workflows
Web Scraping (API-Based)
1. get_selected_element (Automatic Data Source Analysis included)
↓
2. get_network_trace (Deep Inspection & GraphQL included)Web Scraping (SSR/Initial State)
1. get_selected_element (Includes Automatic Data Source Analysis)
↓ (if SSR detected)
2. execute_js(code="document.querySelector('...').textContent")
↓
3. Returns result directly (BLOCKING)WebSocket Analysis
1. get_selected_element
↓
2. get_websocket_traceGraphQL Analysis
1. get_selected_element
↓
2. get_network_trace (Deep Inspection & GraphQL included)Additional Best Practices
- Always check tool descriptions for prerequisites before calling
- Read error messages carefully - they include step-by-step fix instructions
- Use
debug_mcp_statewhen troubleshooting workflow issues - Respect rate limits - excessive requests will be throttled
- Keep selected element data fresh (re-select if older than 10 minutes)
- For RPA (
execute_action): Always useexecute_jsfirst to validate your selector, then pass the validatedxpathorcsstoexecute_action. Avoid relying ontextselectors.
Available Tools (6)
Core Tools
get_selected_element
Retrieve information about the DOM element selected in the extension.
Workflow Position: First Step Prerequisites: None
Returns:
- CSS selector
- XPath
- Tag name
- Attributes
- Selection timestamp
Example:
{
"selector": "#product-price",
"xpath": "//*[@id='product-price']",
"tagName": "span",
"attributes": {"class": "price", "data-price": "29.99"}
}get_network_trace
Find network requests matching the selected element's data.
Workflow Position: Second Step
Prerequisites: get_selected_element
Parameters:
minConfidence(number, optional): Filter by confidence score (0.0-1.0, default: 0.5)limit(number, optional): Max results (default: 10)
Returns: Array of matching requests with Deep Inspection Data (Headers, Body, GraphQL) for top matches.
Analysis Tools
get_websocket_trace
Find WebSocket messages matching the selected element.
Workflow Position: Second Step (Alternative to get_network_trace)
Prerequisites: get_selected_element
Parameters:
minConfidence(number, optional): Filter threshold (default: 0.5)limit(number, optional): Max results (default: 10)direction(string, optional):all,sent,received(default:all)
Returns: Matching WebSocket messages with confidence scores
JavaScript Execution
execute_js
Execute custom JavaScript code in the active tab's page context.
Workflow Position: Advanced Prerequisites: None (but extension must be connected)
Parameters:
code(string, required): JavaScript code to execute (max 10KB)timeout(number, optional): Timeout in ms (default: 5000, max: 30000)
Security:
- Blocks
eval()andFunction() - Blocks
setInterval(memory leak risk) - Size limit: 10KB
- Execution timeout enforced
Robotic Process Automation (RPA)
execute_action
Perform safe, autonomous interactions with the active Chrome tab (click, type text).
Workflow Position: Third Step
Prerequisites: Valid xpath or css selector obtained from get_selected_element or execute_js.
Parameters:
actionType(string): 'click' or 'type'selectorInfo(object): Target element locator. PREFERxpathorcss. Avoidtext.text(string): Output text (only if actionType = 'type')url(string): Current URL (for safety validation)
⚠️ Selector Best Practices:
- PREFER
xpathorcssselectors. They are precise and reliable. - AVOID
textselectors on complex pages — nested elements (e.g.,<button><span>Text</span></button>) cause false negatives. - VALIDATE your selector before use: call
execute_jsfirst to confirm the element is found and interactable.
Recommended Workflow:
1. execute_js → find the right xpath/css selector
2. execute_action → use the validated selectorExample:
{
"actionType": "click",
"selectorInfo": { "xpath": "//button[@role='tab' and contains(., 'Players')]" },
"url": "https://example.com/team"
}Security:
- Uses a strict SafetyGuard that blocks passwords and sensitive sites.
- Restricted from crypto pipelines and banking environments.
Utilities
debug_mcp_state
Show MCP server internal state for debugging.
Workflow Position: Debug Prerequisites: None
Returns: Server state, selected element, network trace status, etc.
Architecture
Modular Structure (v2.1 Refactor)
The server was refactored from a single 900+ line file to a modular architecture:
mcp-server/src/
├── index.js # Entry point (90 lines)
├── tools/ # Smart Tool implementations (5 files)
│ ├── get-selected-element.js
│ ├── get-network-trace.js
│ ├── get-websocket-trace.js
│ ├── execute-js.js
│ ├── debug-mcp-state.js
│ └── index.js # Tool registry
├── bridge/ # HTTP server for extension communication
│ ├── http-server.js
│ ├── routes.js
│ └── middleware.js
├── state/ # State management
│ ├── extension-state.js
│ └── cache.js
└── utils/ # Shared utilitiesBenefits
- Single Responsibility: Each tool in its own file (200-300 lines)
- Testable: Easy to unit test individual tools
- Extensible: Add new tools by creating a new file in
tools/ - Readable: 90-line entry point vs. 900+ line monolith
HTTP Bridge
The server runs an Express HTTP server on port 3101 for extension communication:
POST /update- Extension sends selected element dataGET /health- Health check endpoint
The extension polls this endpoint or pushes updates when elements are selected.
Configuration
Port Configuration
Default port: 3101
Change via environment variable:
export MCP_PORT=3200
npm startOr modify src/index.js line 25:
const HTTP_PORT = parseInt(process.env.MCP_PORT || process.env.PORT || '3101', 10);Extension Configuration
The extension must know the MCP server port. It's configured to use port 3101 by default (hardcoded in modules/mcp-integration.js).
Development
Adding a New Tool
Create a new file in
src/tools/:// src/tools/my-new-tool.js export const myNewToolTool = { name: 'my_new_tool', description: 'Description of what this tool does', inputSchema: { type: 'object', properties: { param1: { type: 'string', description: 'Parameter description' } }, required: ['param1'] }, handler: async (args, extensionData, httpPort) => { // Implementation return { content: [ { type: 'text', text: 'Result' } ] }; } };Register in
src/tools/index.js:import { myNewToolTool } from './my-new-tool.js'; export const allTools = [ // ... existing tools myNewToolTool ];Restart server
Modifying Existing Tools
Edit the corresponding file in src/tools/. Each tool exports an object with:
name: Tool identifierdescription: User-facing descriptioninputSchema: JSON Schema for parametershandler: Async function that implements the tool
Tool Registry Pattern
Tools are automatically discovered via src/tools/index.js. The getToolsList() function returns tool metadata, and getToolHandler() retrieves handlers by name.
Troubleshooting
Extension Not Connected
Symptom: debug_mcp_state returns "extension": "disconnected"
Solutions:
- Ensure Chrome extension is loaded:
chrome://extensions/ - Refresh the webpage where the extension is active
- Check browser console for extension errors
- Verify MCP server is running:
curl http://localhost:3101/health
Port Already in Use
Symptom: Error: listen EADDRINUSE: address already in use :::3101
Solutions:
- Check if another instance is running:
lsof -i :3101 # macOS/Linux netstat -ano | findstr :3101 # Windows - Kill the process or use a different port:
export MCP_PORT=3200 npm start
Validation Errors
Symptom: Tools return prerequisite errors
Solutions:
- Read the error message carefully - it includes "REQUIRED STEPS"
- Follow the workflow order (First Step → Second Step → etc.)
- For execute_js, respect the tool timeout (it will block and wait automatically)
- Use
debug_mcp_stateto inspect server state
Stale Data Errors
Symptom: "Selected element data is stale (>10 minutes old)"
Solutions:
- Call
get_selected_elementagain to refresh data - Select a new element in the extension
API Reference
Tool Response Format
All tools return:
{
"content": [
{
"type": "text",
"text": "Tool output"
}
],
"isError": false
}On error:
{
"content": [
{
"type": "text",
"text": "❌ Error: Description\nREQUIRED STEPS:\n1. Fix this\n2. Then that"
}
],
"isError": true
}Input Schema
Each tool defines a JSON Schema for parameters. Refer to tool descriptions above or inspect src/tools/*.js files for complete schemas.
Error Handling
The server uses validation layers that return structured errors:
- Clear error messages
- Required steps to fix
- Workflow position context
Always read error messages - they guide you to the correct workflow.
Performance
- Tool Execution: <100ms for most tools
- Network Trace: <500ms for typical traces (10-50 requests)
- JavaScript Execution: 100ms-5000ms (depends on code complexity and timeout)
- State Freshness: 10 minute cache for selected element data
Security
- Code Validation: JavaScript executor blocks dangerous patterns (
eval,Function()) - Timeout Enforcement: All JS execution has hard timeout (max 30s)
- Size Limits: Code size limited to 10KB, result size to 100KB
- XSS Prevention: Output sanitization in result parser
- Rate Limiting: Prevents request flooding
License
This software is proprietary. All rights reserved.
Unauthorized copying, distribution, or modification is prohibited.
Usage Rights
- Personal Use: You may use this MCP server in your personal projects
- Commercial Use: You may use this MCP server in your commercial projects and applications
- Redistribution: Redistribution, resale, or transfer of this software is strictly prohibited
- Modification: You may modify the software for your own internal use only
- Source Code: Provided for transparency and security review; does not grant redistribution rights
Each user must obtain their own license. Sharing or redistributing this software is not permitted.
For licensing inquiries: [email protected]
Support
- Documentation: See main README
- MCP Protocol: Model Context Protocol Specification
- Contact: [email protected]
For development guidelines and contribution information, see the main README.md.
