style: 格式化 packages/@ant/ 下所有文件以通过 biome ci

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
claude-code-best
2026-05-01 21:55:51 +08:00
parent c32f26cf21
commit 9ea9859dce
92 changed files with 5903 additions and 5188 deletions

View File

@@ -1,546 +1,546 @@
export const BROWSER_TOOLS = [
{
name: "javascript_tool",
name: 'javascript_tool',
description:
"Execute JavaScript code in the context of the current page. The code runs in the page's context and can interact with the DOM, window object, and page variables. Returns the result of the last expression or any thrown errors. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
inputSchema: {
type: "object",
type: 'object',
properties: {
action: {
type: "string",
type: 'string',
description: "Must be set to 'javascript_exec'",
},
text: {
type: "string",
type: 'string',
description:
"The JavaScript code to execute. The code will be evaluated in the page context. The result of the last expression will be returned automatically. Do NOT use 'return' statements - just write the expression you want to evaluate (e.g., 'window.myData.value' not 'return window.myData.value'). You can access and modify the DOM, call page functions, and interact with page variables.",
},
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to execute the code in. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID.",
},
},
required: ["action", "text", "tabId"],
required: ['action', 'text', 'tabId'],
},
},
{
name: "read_page",
name: 'read_page',
description:
"Get an accessibility tree representation of elements on the page. By default returns all elements including non-visible ones. Output is limited to 50000 characters by default. If the output exceeds this limit, you will receive an error asking you to specify a smaller depth or focus on a specific element using ref_id. Optionally filter for only interactive elements. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
inputSchema: {
type: "object",
type: 'object',
properties: {
filter: {
type: "string",
enum: ["interactive", "all"],
type: 'string',
enum: ['interactive', 'all'],
description:
'Filter elements: "interactive" for buttons/links/inputs only, "all" for all elements including non-visible ones (default: all elements)',
},
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to read from. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID.",
},
depth: {
type: "number",
type: 'number',
description:
"Maximum depth of the tree to traverse (default: 15). Use a smaller depth if output is too large.",
'Maximum depth of the tree to traverse (default: 15). Use a smaller depth if output is too large.',
},
ref_id: {
type: "string",
type: 'string',
description:
"Reference ID of a parent element to read. Will return the specified element and all its children. Use this to focus on a specific part of the page when output is too large.",
'Reference ID of a parent element to read. Will return the specified element and all its children. Use this to focus on a specific part of the page when output is too large.',
},
max_chars: {
type: "number",
type: 'number',
description:
"Maximum characters for output (default: 50000). Set to a higher value if your client can handle large outputs.",
'Maximum characters for output (default: 50000). Set to a higher value if your client can handle large outputs.',
},
},
required: ["tabId"],
required: ['tabId'],
},
},
{
name: "find",
name: 'find',
description:
'Find elements on the page using natural language. Can search for elements by their purpose (e.g., "search bar", "login button") or by text content (e.g., "organic mango product"). Returns up to 20 matching elements with references that can be used with other tools. If more than 20 matches exist, you\'ll be notified to use a more specific query. If you don\'t have a valid tab ID, use tabs_context_mcp first to get available tabs.',
inputSchema: {
type: "object",
type: 'object',
properties: {
query: {
type: "string",
type: 'string',
description:
'Natural language description of what to find (e.g., "search bar", "add to cart button", "product title containing organic")',
},
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to search in. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID.",
},
},
required: ["query", "tabId"],
required: ['query', 'tabId'],
},
},
{
name: "form_input",
name: 'form_input',
description:
"Set values in form elements using element reference ID from the read_page tool. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
inputSchema: {
type: "object",
type: 'object',
properties: {
ref: {
type: "string",
type: 'string',
description:
'Element reference ID from the read_page tool (e.g., "ref_1", "ref_2")',
},
value: {
type: ["string", "boolean", "number"],
type: ['string', 'boolean', 'number'],
description:
"The value to set. For checkboxes use boolean, for selects use option value or text, for other inputs use appropriate string/number",
'The value to set. For checkboxes use boolean, for selects use option value or text, for other inputs use appropriate string/number',
},
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to set form value in. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID.",
},
},
required: ["ref", "value", "tabId"],
required: ['ref', 'value', 'tabId'],
},
},
{
name: "computer",
name: 'computer',
description: `Use a mouse and keyboard to interact with a web browser, and take screenshots. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.\n* Whenever you intend to click on an element like an icon, you should consult a screenshot to determine the coordinates of the element before moving the cursor.\n* If you tried clicking on a program or link but it failed to load, even after waiting, try adjusting your click location so that the tip of the cursor visually falls on the element that you want to click.\n* Make sure to click any buttons, links, icons, etc with the cursor tip in the center of the element. Don't click boxes on their edges unless asked.`,
inputSchema: {
type: "object",
type: 'object',
properties: {
action: {
type: "string",
type: 'string',
enum: [
"left_click",
"right_click",
"type",
"screenshot",
"wait",
"scroll",
"key",
"left_click_drag",
"double_click",
"triple_click",
"zoom",
"scroll_to",
"hover",
'left_click',
'right_click',
'type',
'screenshot',
'wait',
'scroll',
'key',
'left_click_drag',
'double_click',
'triple_click',
'zoom',
'scroll_to',
'hover',
],
description:
"The action to perform:\n* `left_click`: Click the left mouse button at the specified coordinates.\n* `right_click`: Click the right mouse button at the specified coordinates to open context menus.\n* `double_click`: Double-click the left mouse button at the specified coordinates.\n* `triple_click`: Triple-click the left mouse button at the specified coordinates.\n* `type`: Type a string of text.\n* `screenshot`: Take a screenshot of the screen.\n* `wait`: Wait for a specified number of seconds.\n* `scroll`: Scroll up, down, left, or right at the specified coordinates.\n* `key`: Press a specific keyboard key.\n* `left_click_drag`: Drag from start_coordinate to coordinate.\n* `zoom`: Take a screenshot of a specific region for closer inspection.\n* `scroll_to`: Scroll an element into view using its element reference ID from read_page or find tools.\n* `hover`: Move the mouse cursor to the specified coordinates or element without clicking. Useful for revealing tooltips, dropdown menus, or triggering hover states.",
'The action to perform:\n* `left_click`: Click the left mouse button at the specified coordinates.\n* `right_click`: Click the right mouse button at the specified coordinates to open context menus.\n* `double_click`: Double-click the left mouse button at the specified coordinates.\n* `triple_click`: Triple-click the left mouse button at the specified coordinates.\n* `type`: Type a string of text.\n* `screenshot`: Take a screenshot of the screen.\n* `wait`: Wait for a specified number of seconds.\n* `scroll`: Scroll up, down, left, or right at the specified coordinates.\n* `key`: Press a specific keyboard key.\n* `left_click_drag`: Drag from start_coordinate to coordinate.\n* `zoom`: Take a screenshot of a specific region for closer inspection.\n* `scroll_to`: Scroll an element into view using its element reference ID from read_page or find tools.\n* `hover`: Move the mouse cursor to the specified coordinates or element without clicking. Useful for revealing tooltips, dropdown menus, or triggering hover states.',
},
coordinate: {
type: "array",
items: { type: "number" },
type: 'array',
items: { type: 'number' },
minItems: 2,
maxItems: 2,
description:
"(x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates. Required for `left_click`, `right_click`, `double_click`, `triple_click`, and `scroll`. For `left_click_drag`, this is the end position.",
'(x, y): The x (pixels from the left edge) and y (pixels from the top edge) coordinates. Required for `left_click`, `right_click`, `double_click`, `triple_click`, and `scroll`. For `left_click_drag`, this is the end position.',
},
text: {
type: "string",
type: 'string',
description:
'The text to type (for `type` action) or the key(s) to press (for `key` action). For `key` action: Provide space-separated keys (e.g., "Backspace Backspace Delete"). Supports keyboard shortcuts using the platform\'s modifier key (use "cmd" on Mac, "ctrl" on Windows/Linux, e.g., "cmd+a" or "ctrl+a" for select all).',
},
duration: {
type: "number",
type: 'number',
minimum: 0,
maximum: 30,
description:
"The number of seconds to wait. Required for `wait`. Maximum 30 seconds.",
'The number of seconds to wait. Required for `wait`. Maximum 30 seconds.',
},
scroll_direction: {
type: "string",
enum: ["up", "down", "left", "right"],
description: "The direction to scroll. Required for `scroll`.",
type: 'string',
enum: ['up', 'down', 'left', 'right'],
description: 'The direction to scroll. Required for `scroll`.',
},
scroll_amount: {
type: "number",
type: 'number',
minimum: 1,
maximum: 10,
description:
"The number of scroll wheel ticks. Optional for `scroll`, defaults to 3.",
'The number of scroll wheel ticks. Optional for `scroll`, defaults to 3.',
},
start_coordinate: {
type: "array",
items: { type: "number" },
type: 'array',
items: { type: 'number' },
minItems: 2,
maxItems: 2,
description:
"(x, y): The starting coordinates for `left_click_drag`.",
'(x, y): The starting coordinates for `left_click_drag`.',
},
region: {
type: "array",
items: { type: "number" },
type: 'array',
items: { type: 'number' },
minItems: 4,
maxItems: 4,
description:
"(x0, y0, x1, y1): The rectangular region to capture for `zoom`. Coordinates define a rectangle from top-left (x0, y0) to bottom-right (x1, y1) in pixels from the viewport origin. Required for `zoom` action. Useful for inspecting small UI elements like icons, buttons, or text.",
'(x0, y0, x1, y1): The rectangular region to capture for `zoom`. Coordinates define a rectangle from top-left (x0, y0) to bottom-right (x1, y1) in pixels from the viewport origin. Required for `zoom` action. Useful for inspecting small UI elements like icons, buttons, or text.',
},
repeat: {
type: "number",
type: 'number',
minimum: 1,
maximum: 100,
description:
"Number of times to repeat the key sequence. Only applicable for `key` action. Must be a positive integer between 1 and 100. Default is 1. Useful for navigation tasks like pressing arrow keys multiple times.",
'Number of times to repeat the key sequence. Only applicable for `key` action. Must be a positive integer between 1 and 100. Default is 1. Useful for navigation tasks like pressing arrow keys multiple times.',
},
ref: {
type: "string",
type: 'string',
description:
'Element reference ID from read_page or find tools (e.g., "ref_1", "ref_2"). Required for `scroll_to` action. Can be used as alternative to `coordinate` for click actions.',
},
modifiers: {
type: "string",
type: 'string',
description:
'Modifier keys for click actions. Supports: "ctrl", "shift", "alt", "cmd" (or "meta"), "win" (or "windows"). Can be combined with "+" (e.g., "ctrl+shift", "cmd+alt"). Optional.',
},
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to execute the action on. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID.",
},
},
required: ["action", "tabId"],
required: ['action', 'tabId'],
},
},
{
name: "navigate",
name: 'navigate',
description:
"Navigate to a URL, or go forward/back in browser history. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
inputSchema: {
type: "object",
type: 'object',
properties: {
url: {
type: "string",
type: 'string',
description:
'The URL to navigate to. Can be provided with or without protocol (defaults to https://). Use "forward" to go forward in history or "back" to go back in history.',
},
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to navigate. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID.",
},
},
required: ["url", "tabId"],
required: ['url', 'tabId'],
},
},
{
name: "resize_window",
name: 'resize_window',
description:
"Resize the current browser window to specified dimensions. Useful for testing responsive designs or setting up specific screen sizes. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
inputSchema: {
type: "object",
type: 'object',
properties: {
width: {
type: "number",
description: "Target window width in pixels",
type: 'number',
description: 'Target window width in pixels',
},
height: {
type: "number",
description: "Target window height in pixels",
type: 'number',
description: 'Target window height in pixels',
},
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to get the window for. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID.",
},
},
required: ["width", "height", "tabId"],
required: ['width', 'height', 'tabId'],
},
},
{
name: "gif_creator",
name: 'gif_creator',
description:
"Manage GIF recording and export for browser automation sessions. Control when to start/stop recording browser actions (clicks, scrolls, navigation), then export as an animated GIF with visual overlays (click indicators, action labels, progress bar, watermark). All operations are scoped to the tab's group. When starting recording, take a screenshot immediately after to capture the initial state as the first frame. When stopping recording, take a screenshot immediately before to capture the final state as the last frame. For export, either provide 'coordinate' to drag/drop upload to a page element, or set 'download: true' to download the GIF.",
inputSchema: {
type: "object",
type: 'object',
properties: {
action: {
type: "string",
enum: ["start_recording", "stop_recording", "export", "clear"],
type: 'string',
enum: ['start_recording', 'stop_recording', 'export', 'clear'],
description:
"Action to perform: 'start_recording' (begin capturing), 'stop_recording' (stop capturing but keep frames), 'export' (generate and export GIF), 'clear' (discard frames)",
},
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to identify which tab group this operation applies to",
'Tab ID to identify which tab group this operation applies to',
},
download: {
type: "boolean",
type: 'boolean',
description:
"Always set this to true for the 'export' action only. This causes the gif to be downloaded in the browser.",
},
filename: {
type: "string",
type: 'string',
description:
"Optional filename for exported GIF (default: 'recording-[timestamp].gif'). For 'export' action only.",
},
options: {
type: "object",
type: 'object',
description:
"Optional GIF enhancement options for 'export' action. Properties: showClickIndicators (bool), showDragPaths (bool), showActionLabels (bool), showProgressBar (bool), showWatermark (bool), quality (number 1-30). All default to true except quality (default: 10).",
properties: {
showClickIndicators: {
type: "boolean",
type: 'boolean',
description:
"Show orange circles at click locations (default: true)",
'Show orange circles at click locations (default: true)',
},
showDragPaths: {
type: "boolean",
description: "Show red arrows for drag actions (default: true)",
type: 'boolean',
description: 'Show red arrows for drag actions (default: true)',
},
showActionLabels: {
type: "boolean",
type: 'boolean',
description:
"Show black labels describing actions (default: true)",
'Show black labels describing actions (default: true)',
},
showProgressBar: {
type: "boolean",
description: "Show orange progress bar at bottom (default: true)",
type: 'boolean',
description: 'Show orange progress bar at bottom (default: true)',
},
showWatermark: {
type: "boolean",
description: "Show Claude logo watermark (default: true)",
type: 'boolean',
description: 'Show Claude logo watermark (default: true)',
},
quality: {
type: "number",
type: 'number',
description:
"GIF compression quality, 1-30 (lower = better quality, slower encoding). Default: 10",
'GIF compression quality, 1-30 (lower = better quality, slower encoding). Default: 10',
},
},
},
},
required: ["action", "tabId"],
required: ['action', 'tabId'],
},
},
{
name: "upload_image",
name: 'upload_image',
description:
"Upload a previously captured screenshot or user-uploaded image to a file input or drag & drop target. Supports two approaches: (1) ref - for targeting specific elements, especially hidden file inputs, (2) coordinate - for drag & drop to visible locations like Google Docs. Provide either ref or coordinate, not both.",
'Upload a previously captured screenshot or user-uploaded image to a file input or drag & drop target. Supports two approaches: (1) ref - for targeting specific elements, especially hidden file inputs, (2) coordinate - for drag & drop to visible locations like Google Docs. Provide either ref or coordinate, not both.',
inputSchema: {
type: "object",
type: 'object',
properties: {
imageId: {
type: "string",
type: 'string',
description:
"ID of a previously captured screenshot (from the computer tool's screenshot action) or a user-uploaded image",
},
ref: {
type: "string",
type: 'string',
description:
'Element reference ID from read_page or find tools (e.g., "ref_1", "ref_2"). Use this for file inputs (especially hidden ones) or specific elements. Provide either ref or coordinate, not both.',
},
coordinate: {
type: "array",
type: 'array',
items: {
type: "number",
type: 'number',
},
description:
"Viewport coordinates [x, y] for drag & drop to a visible location. Use this for drag & drop targets like Google Docs. Provide either ref or coordinate, not both.",
'Viewport coordinates [x, y] for drag & drop to a visible location. Use this for drag & drop targets like Google Docs. Provide either ref or coordinate, not both.',
},
tabId: {
type: "number",
type: 'number',
description:
"Tab ID where the target element is located. This is where the image will be uploaded to.",
'Tab ID where the target element is located. This is where the image will be uploaded to.',
},
filename: {
type: "string",
type: 'string',
description:
'Optional filename for the uploaded file (default: "image.png")',
},
},
required: ["imageId", "tabId"],
required: ['imageId', 'tabId'],
},
},
{
name: "get_page_text",
name: 'get_page_text',
description:
"Extract raw text content from the page, prioritizing article content. Ideal for reading articles, blog posts, or other text-heavy pages. Returns plain text without HTML formatting. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
inputSchema: {
type: "object",
type: 'object',
properties: {
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to extract text from. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID.",
},
},
required: ["tabId"],
required: ['tabId'],
},
},
{
name: "tabs_context_mcp",
title: "Tabs Context",
name: 'tabs_context_mcp',
title: 'Tabs Context',
description:
"Get context information about the current MCP tab group. Returns all tab IDs inside the group if it exists. CRITICAL: You must get the context at least once before using other browser automation tools so you know what tabs exist. Each new conversation should create its own new tab (using tabs_create_mcp) rather than reusing existing tabs, unless the user explicitly asks to use an existing tab.",
'Get context information about the current MCP tab group. Returns all tab IDs inside the group if it exists. CRITICAL: You must get the context at least once before using other browser automation tools so you know what tabs exist. Each new conversation should create its own new tab (using tabs_create_mcp) rather than reusing existing tabs, unless the user explicitly asks to use an existing tab.',
inputSchema: {
type: "object",
type: 'object',
properties: {
createIfEmpty: {
type: "boolean",
type: 'boolean',
description:
"Creates a new MCP tab group if none exists, creates a new Window with a new tab group containing an empty tab (which can be used for this conversation). If a MCP tab group already exists, this parameter has no effect.",
'Creates a new MCP tab group if none exists, creates a new Window with a new tab group containing an empty tab (which can be used for this conversation). If a MCP tab group already exists, this parameter has no effect.',
},
},
required: [],
},
},
{
name: "tabs_create_mcp",
title: "Tabs Create",
name: 'tabs_create_mcp',
title: 'Tabs Create',
description:
"Creates a new empty tab in the MCP tab group. CRITICAL: You must get the context using tabs_context_mcp at least once before using other browser automation tools so you know what tabs exist.",
'Creates a new empty tab in the MCP tab group. CRITICAL: You must get the context using tabs_context_mcp at least once before using other browser automation tools so you know what tabs exist.',
inputSchema: {
type: "object",
type: 'object',
properties: {},
required: [],
},
},
{
name: "update_plan",
name: 'update_plan',
description:
"Present a plan to the user for approval before taking actions. The user will see the domains you intend to visit and your approach. Once approved, you can proceed with actions on the approved domains without additional permission prompts.",
'Present a plan to the user for approval before taking actions. The user will see the domains you intend to visit and your approach. Once approved, you can proceed with actions on the approved domains without additional permission prompts.',
inputSchema: {
type: "object" as const,
type: 'object' as const,
properties: {
domains: {
type: "array" as const,
items: { type: "string" as const },
type: 'array' as const,
items: { type: 'string' as const },
description:
"List of domains you will visit (e.g., ['github.com', 'stackoverflow.com']). These domains will be approved for the session when the user accepts the plan.",
},
approach: {
type: "array" as const,
items: { type: "string" as const },
type: 'array' as const,
items: { type: 'string' as const },
description:
"High-level description of what you will do. Focus on outcomes and key actions, not implementation details. Be concise - aim for 3-7 items.",
'High-level description of what you will do. Focus on outcomes and key actions, not implementation details. Be concise - aim for 3-7 items.',
},
},
required: ["domains", "approach"],
required: ['domains', 'approach'],
},
},
{
name: "read_console_messages",
name: 'read_console_messages',
description:
"Read browser console messages (console.log, console.error, console.warn, etc.) from a specific tab. Useful for debugging JavaScript errors, viewing application logs, or understanding what's happening in the browser console. Returns console messages from the current domain only. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs. IMPORTANT: Always provide a pattern to filter messages - without a pattern, you may get too many irrelevant messages.",
inputSchema: {
type: "object",
type: 'object',
properties: {
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to read console messages from. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID.",
},
onlyErrors: {
type: "boolean",
type: 'boolean',
description:
"If true, only return error and exception messages. Default is false (return all message types).",
'If true, only return error and exception messages. Default is false (return all message types).',
},
clear: {
type: "boolean",
type: 'boolean',
description:
"If true, clear the console messages after reading to avoid duplicates on subsequent calls. Default is false.",
'If true, clear the console messages after reading to avoid duplicates on subsequent calls. Default is false.',
},
pattern: {
type: "string",
type: 'string',
description:
"Regex pattern to filter console messages. Only messages matching this pattern will be returned (e.g., 'error|warning' to find errors and warnings, 'MyApp' to filter app-specific logs). You should always provide a pattern to avoid getting too many irrelevant messages.",
},
limit: {
type: "number",
type: 'number',
description:
"Maximum number of messages to return. Defaults to 100. Increase only if you need more results.",
'Maximum number of messages to return. Defaults to 100. Increase only if you need more results.',
},
},
required: ["tabId"],
required: ['tabId'],
},
},
{
name: "read_network_requests",
name: 'read_network_requests',
description:
"Read HTTP network requests (XHR, Fetch, documents, images, etc.) from a specific tab. Useful for debugging API calls, monitoring network activity, or understanding what requests a page is making. Returns all network requests made by the current page, including cross-origin requests. Requests are automatically cleared when the page navigates to a different domain. If you don't have a valid tab ID, use tabs_context_mcp first to get available tabs.",
inputSchema: {
type: "object",
type: 'object',
properties: {
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to read network requests from. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID.",
},
urlPattern: {
type: "string",
type: 'string',
description:
"Optional URL pattern to filter requests. Only requests whose URL contains this string will be returned (e.g., '/api/' to filter API calls, 'example.com' to filter by domain).",
},
clear: {
type: "boolean",
type: 'boolean',
description:
"If true, clear the network requests after reading to avoid duplicates on subsequent calls. Default is false.",
'If true, clear the network requests after reading to avoid duplicates on subsequent calls. Default is false.',
},
limit: {
type: "number",
type: 'number',
description:
"Maximum number of requests to return. Defaults to 100. Increase only if you need more results.",
'Maximum number of requests to return. Defaults to 100. Increase only if you need more results.',
},
},
required: ["tabId"],
required: ['tabId'],
},
},
{
name: "shortcuts_list",
name: 'shortcuts_list',
description:
"List all available shortcuts and workflows (shortcuts and workflows are interchangeable). Returns shortcuts with their commands, descriptions, and whether they are workflows. Use shortcuts_execute to run a shortcut or workflow.",
'List all available shortcuts and workflows (shortcuts and workflows are interchangeable). Returns shortcuts with their commands, descriptions, and whether they are workflows. Use shortcuts_execute to run a shortcut or workflow.',
inputSchema: {
type: "object",
type: 'object',
properties: {
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to list shortcuts from. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID.",
},
},
required: ["tabId"],
required: ['tabId'],
},
},
{
name: "shortcuts_execute",
name: 'shortcuts_execute',
description:
"Execute a shortcut or workflow by running it in a new sidepanel window using the current tab (shortcuts and workflows are interchangeable). Use shortcuts_list first to see available shortcuts. This starts the execution and returns immediately - it does not wait for completion.",
'Execute a shortcut or workflow by running it in a new sidepanel window using the current tab (shortcuts and workflows are interchangeable). Use shortcuts_list first to see available shortcuts. This starts the execution and returns immediately - it does not wait for completion.',
inputSchema: {
type: "object",
type: 'object',
properties: {
tabId: {
type: "number",
type: 'number',
description:
"Tab ID to execute the shortcut on. Must be a tab in the current group. Use tabs_context_mcp first if you don't have a valid tab ID.",
},
shortcutId: {
type: "string",
description: "The ID of the shortcut to execute",
type: 'string',
description: 'The ID of the shortcut to execute',
},
command: {
type: "string",
type: 'string',
description:
"The command name of the shortcut to execute (e.g., 'debug', 'summarize'). Do not include the leading slash.",
},
},
required: ["tabId"],
required: ['tabId'],
},
},
{
name: "switch_browser",
name: 'switch_browser',
description:
"Switch which Chrome browser is used for browser automation. Call this when the user wants to connect to a different Chrome browser. Broadcasts a connection request to all Chrome browsers with the extension installed — the user clicks 'Connect' in the desired browser.",
inputSchema: {
type: "object",
type: 'object',
properties: {},
required: [],
},
},
];
]

View File

@@ -1,10 +1,10 @@
export { BridgeClient, createBridgeClient } from "./bridgeClient.js";
export { BROWSER_TOOLS } from "./browserTools.js";
export { BridgeClient, createBridgeClient } from './bridgeClient.js'
export { BROWSER_TOOLS } from './browserTools.js'
export {
createChromeSocketClient,
createClaudeForChromeMcpServer,
} from "./mcpServer.js";
export { localPlatformLabel } from "./types.js";
} from './mcpServer.js'
export { localPlatformLabel } from './types.js'
export type {
BridgeConfig,
ChromeExtensionInfo,
@@ -12,4 +12,4 @@ export type {
Logger,
PermissionMode,
SocketClient,
} from "./types.js";
} from './types.js'

View File

@@ -1,16 +1,16 @@
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
import {
CallToolRequestSchema,
ListToolsRequestSchema,
} from "@modelcontextprotocol/sdk/types.js";
} from '@modelcontextprotocol/sdk/types.js'
import { createBridgeClient } from "./bridgeClient.js";
import { BROWSER_TOOLS } from "./browserTools.js";
import { createMcpSocketClient } from "./mcpSocketClient.js";
import { createMcpSocketPool } from "./mcpSocketPool.js";
import { handleToolCall } from "./toolCalls.js";
import type { ClaudeForChromeContext, SocketClient } from "./types.js";
import { createBridgeClient } from './bridgeClient.js'
import { BROWSER_TOOLS } from './browserTools.js'
import { createMcpSocketClient } from './mcpSocketClient.js'
import { createMcpSocketPool } from './mcpSocketPool.js'
import { handleToolCall } from './toolCalls.js'
import type { ClaudeForChromeContext, SocketClient } from './types.js'
/**
* Create the socket/bridge client for the Chrome extension MCP server.
@@ -24,23 +24,22 @@ export function createChromeSocketClient(
? createBridgeClient(context)
: context.getSocketPaths
? createMcpSocketPool(context)
: createMcpSocketClient(context);
: createMcpSocketClient(context)
}
export function createClaudeForChromeMcpServer(
context: ClaudeForChromeContext,
existingSocketClient?: SocketClient,
): Server {
const { serverName, logger } = context;
const { serverName, logger } = context
// Choose transport: bridge (WebSocket) > socket pool (multi-profile) > single socket.
const socketClient =
existingSocketClient ?? createChromeSocketClient(context);
const socketClient = existingSocketClient ?? createChromeSocketClient(context)
const server = new Server(
{
name: serverName,
version: "1.0.0",
version: '1.0.0',
},
{
capabilities: {
@@ -48,49 +47,49 @@ export function createClaudeForChromeMcpServer(
logging: {},
},
},
);
)
server.setRequestHandler(ListToolsRequestSchema, async () => {
if (context.isDisabled?.()) {
return { tools: [] };
return { tools: [] }
}
return {
tools: context.bridgeConfig
? BROWSER_TOOLS
: BROWSER_TOOLS.filter((t) => t.name !== "switch_browser"),
};
});
: BROWSER_TOOLS.filter(t => t.name !== 'switch_browser'),
}
})
server.setRequestHandler(
CallToolRequestSchema,
async (request): Promise<CallToolResult> => {
logger.info(`[${serverName}] Executing tool: ${request.params.name}`);
logger.info(`[${serverName}] Executing tool: ${request.params.name}`)
return handleToolCall(
context,
socketClient,
request.params.name,
request.params.arguments || {},
);
)
},
);
)
socketClient.setNotificationHandler((notification) => {
socketClient.setNotificationHandler(notification => {
logger.info(
`[${serverName}] Forwarding MCP notification: ${notification.method}`,
);
)
server
.notification({
method: notification.method,
params: notification.params,
})
.catch((error) => {
.catch(error => {
// Server may not be connected yet (e.g., during startup or after disconnect)
logger.info(
`[${serverName}] Failed to forward MCP notification: ${error.message}`,
);
});
});
)
})
})
return server;
return server
}

View File

@@ -1,13 +1,13 @@
import {
createMcpSocketClient,
SocketConnectionError,
} from "./mcpSocketClient.js";
import type { McpSocketClient } from "./mcpSocketClient.js";
} from './mcpSocketClient.js'
import type { McpSocketClient } from './mcpSocketClient.js'
import type {
ClaudeForChromeContext,
PermissionMode,
PermissionOverrides,
} from "./types.js";
} from './types.js'
/**
* Manages connections to multiple Chrome native host sockets (one per Chrome profile).
@@ -18,26 +18,29 @@ import type {
* built from tabs_context_mcp responses.
*/
export class McpSocketPool {
private clients: Map<string, McpSocketClient> = new Map();
private tabRoutes: Map<number, string> = new Map();
private context: ClaudeForChromeContext;
private clients: Map<string, McpSocketClient> = new Map()
private tabRoutes: Map<number, string> = new Map()
private context: ClaudeForChromeContext
private notificationHandler:
| ((notification: { method: string; params?: Record<string, unknown> }) => void)
| null = null;
| ((notification: {
method: string
params?: Record<string, unknown>
}) => void)
| null = null
constructor(context: ClaudeForChromeContext) {
this.context = context;
this.context = context
}
public setNotificationHandler(
handler: (notification: {
method: string;
params?: Record<string, unknown>;
method: string
params?: Record<string, unknown>
}) => void,
): void {
this.notificationHandler = handler;
this.notificationHandler = handler
for (const client of this.clients.values()) {
client.setNotificationHandler(handler);
client.setNotificationHandler(handler)
}
}
@@ -45,32 +48,30 @@ export class McpSocketPool {
* Discover available sockets and ensure at least one is connected.
*/
public async ensureConnected(): Promise<boolean> {
const { logger, serverName } = this.context;
const { logger, serverName } = this.context
this.refreshClients();
this.refreshClients()
// Try to connect any disconnected clients
const connectPromises: Promise<boolean>[] = [];
const connectPromises: Promise<boolean>[] = []
for (const client of this.clients.values()) {
if (!client.isConnected()) {
connectPromises.push(
client.ensureConnected().catch(() => false),
);
connectPromises.push(client.ensureConnected().catch(() => false))
}
}
if (connectPromises.length > 0) {
await Promise.all(connectPromises);
await Promise.all(connectPromises)
}
const connectedCount = this.getConnectedClients().length;
const connectedCount = this.getConnectedClients().length
if (connectedCount === 0) {
logger.info(`[${serverName}] No connected sockets in pool`);
return false;
logger.info(`[${serverName}] No connected sockets in pool`)
return false
}
logger.info(`[${serverName}] Socket pool: ${connectedCount} connected`);
return true;
logger.info(`[${serverName}] Socket pool: ${connectedCount} connected`)
return true
}
/**
@@ -82,57 +83,57 @@ export class McpSocketPool {
args: Record<string, unknown>,
_permissionOverrides?: PermissionOverrides,
): Promise<unknown> {
if (name === "tabs_context_mcp") {
return this.callTabsContext(args);
if (name === 'tabs_context_mcp') {
return this.callTabsContext(args)
}
// Route by tabId if present
const tabId = args.tabId as number | undefined;
const tabId = args.tabId as number | undefined
if (tabId !== undefined) {
const socketPath = this.tabRoutes.get(tabId);
const socketPath = this.tabRoutes.get(tabId)
if (socketPath) {
const client = this.clients.get(socketPath);
const client = this.clients.get(socketPath)
if (client?.isConnected()) {
return client.callTool(name, args);
return client.callTool(name, args)
}
}
// Tab route not found or client disconnected — fall through to any connected
}
// Fallback: use first connected client
const connected = this.getConnectedClients();
const connected = this.getConnectedClients()
if (connected.length === 0) {
throw new SocketConnectionError(
`[${this.context.serverName}] No connected sockets available`,
);
)
}
return connected[0]!.callTool(name, args);
return connected[0]!.callTool(name, args)
}
public async setPermissionMode(
mode: PermissionMode,
allowedDomains?: string[],
): Promise<void> {
const connected = this.getConnectedClients();
const connected = this.getConnectedClients()
await Promise.all(
connected.map((client) => client.setPermissionMode(mode, allowedDomains)),
);
connected.map(client => client.setPermissionMode(mode, allowedDomains)),
)
}
public isConnected(): boolean {
return this.getConnectedClients().length > 0;
return this.getConnectedClients().length > 0
}
public disconnect(): void {
for (const client of this.clients.values()) {
client.disconnect();
client.disconnect()
}
this.clients.clear();
this.tabRoutes.clear();
this.clients.clear()
this.tabRoutes.clear()
}
private getConnectedClients(): McpSocketClient[] {
return [...this.clients.values()].filter((c) => c.isConnected());
return [...this.clients.values()].filter(c => c.isConnected())
}
/**
@@ -142,173 +143,173 @@ export class McpSocketPool {
private async callTabsContext(
args: Record<string, unknown>,
): Promise<unknown> {
const { logger, serverName } = this.context;
const connected = this.getConnectedClients();
const { logger, serverName } = this.context
const connected = this.getConnectedClients()
if (connected.length === 0) {
throw new SocketConnectionError(
`[${serverName}] No connected sockets available`,
);
)
}
// If only one client, skip merging overhead
if (connected.length === 1) {
const result = await connected[0]!.callTool("tabs_context_mcp", args);
this.updateTabRoutes(result, this.getSocketPathForClient(connected[0]!));
return result;
const result = await connected[0]!.callTool('tabs_context_mcp', args)
this.updateTabRoutes(result, this.getSocketPathForClient(connected[0]!))
return result
}
// Query all connected clients in parallel
const results = await Promise.allSettled(
connected.map(async (client) => {
const result = await client.callTool("tabs_context_mcp", args);
const socketPath = this.getSocketPathForClient(client);
return { result, socketPath };
connected.map(async client => {
const result = await client.callTool('tabs_context_mcp', args)
const socketPath = this.getSocketPathForClient(client)
return { result, socketPath }
}),
);
)
// Merge tab results
const mergedTabs: unknown[] = [];
this.tabRoutes.clear();
const mergedTabs: unknown[] = []
this.tabRoutes.clear()
for (const settledResult of results) {
if (settledResult.status !== "fulfilled") {
if (settledResult.status !== 'fulfilled') {
logger.info(
`[${serverName}] tabs_context_mcp failed on one socket: ${settledResult.reason}`,
);
continue;
)
continue
}
const { result, socketPath } = settledResult.value;
this.updateTabRoutes(result, socketPath);
const { result, socketPath } = settledResult.value
this.updateTabRoutes(result, socketPath)
const tabs = this.extractTabs(result);
const tabs = this.extractTabs(result)
if (tabs) {
mergedTabs.push(...tabs);
mergedTabs.push(...tabs)
}
}
// Return merged result in the same format as the extension response
if (mergedTabs.length > 0) {
const tabListText = mergedTabs
.map((t) => {
const tab = t as { tabId: number; title: string; url: string };
return ` • tabId ${tab.tabId}: "${tab.title}" (${tab.url})`;
.map(t => {
const tab = t as { tabId: number; title: string; url: string }
return ` • tabId ${tab.tabId}: "${tab.title}" (${tab.url})`
})
.join("\n");
.join('\n')
return {
result: {
content: [
{
type: "text",
type: 'text',
text: JSON.stringify({ availableTabs: mergedTabs }),
},
{
type: "text",
type: 'text',
text: `\n\nTab Context:\n- Available tabs:\n${tabListText}`,
},
],
},
};
}
}
// Fallback: return first successful result as-is
for (const settledResult of results) {
if (settledResult.status === "fulfilled") {
return settledResult.value.result;
if (settledResult.status === 'fulfilled') {
return settledResult.value.result
}
}
throw new SocketConnectionError(
`[${serverName}] All sockets failed for tabs_context_mcp`,
);
)
}
/**
* Extract tab objects from a tool response to update routing table.
*/
private updateTabRoutes(result: unknown, socketPath: string): void {
const tabs = this.extractTabs(result);
if (!tabs) return;
const tabs = this.extractTabs(result)
if (!tabs) return
for (const tab of tabs) {
if (typeof tab === "object" && tab !== null && "tabId" in tab) {
const tabId = (tab as { tabId: number }).tabId;
this.tabRoutes.set(tabId, socketPath);
if (typeof tab === 'object' && tab !== null && 'tabId' in tab) {
const tabId = (tab as { tabId: number }).tabId
this.tabRoutes.set(tabId, socketPath)
}
}
}
private extractTabs(result: unknown): unknown[] | null {
if (!result || typeof result !== "object") return null;
if (!result || typeof result !== 'object') return null
// Response format: { result: { content: [{ type: "text", text: "{\"availableTabs\":[...],\"tabGroupId\":...}" }] } }
const asResponse = result as {
result?: { content?: Array<{ type: string; text?: string }> };
};
const content = asResponse.result?.content;
if (!content || !Array.isArray(content)) return null;
result?: { content?: Array<{ type: string; text?: string }> }
}
const content = asResponse.result?.content
if (!content || !Array.isArray(content)) return null
for (const item of content) {
if (item.type === "text" && item.text) {
if (item.type === 'text' && item.text) {
try {
const parsed = JSON.parse(item.text);
if (Array.isArray(parsed)) return parsed;
const parsed = JSON.parse(item.text)
if (Array.isArray(parsed)) return parsed
// Handle { availableTabs: [...] } format
if (parsed && Array.isArray(parsed.availableTabs)) {
return parsed.availableTabs;
return parsed.availableTabs
}
} catch {
// Not JSON, skip
}
}
}
return null;
return null
}
private getSocketPathForClient(client: McpSocketClient): string {
for (const [path, c] of this.clients.entries()) {
if (c === client) return path;
if (c === client) return path
}
return "";
return ''
}
/**
* Scan for available sockets and create/remove clients as needed.
*/
private refreshClients(): void {
const socketPaths = this.getAvailableSocketPaths();
const { logger, serverName } = this.context;
const socketPaths = this.getAvailableSocketPaths()
const { logger, serverName } = this.context
// Add new clients for newly discovered sockets
for (const path of socketPaths) {
if (!this.clients.has(path)) {
logger.info(`[${serverName}] Adding socket to pool: ${path}`);
logger.info(`[${serverName}] Adding socket to pool: ${path}`)
const clientContext: ClaudeForChromeContext = {
...this.context,
socketPath: path,
getSocketPath: undefined,
getSocketPaths: undefined,
};
const client = createMcpSocketClient(clientContext);
client.disableAutoReconnect = true;
if (this.notificationHandler) {
client.setNotificationHandler(this.notificationHandler);
}
this.clients.set(path, client);
const client = createMcpSocketClient(clientContext)
client.disableAutoReconnect = true
if (this.notificationHandler) {
client.setNotificationHandler(this.notificationHandler)
}
this.clients.set(path, client)
}
}
// Remove clients for sockets that no longer exist
for (const [path, client] of this.clients.entries()) {
if (!socketPaths.includes(path)) {
logger.info(`[${serverName}] Removing stale socket from pool: ${path}`);
client.disconnect();
this.clients.delete(path);
logger.info(`[${serverName}] Removing stale socket from pool: ${path}`)
client.disconnect()
this.clients.delete(path)
for (const [tabId, socketPath] of this.tabRoutes.entries()) {
if (socketPath === path) {
this.tabRoutes.delete(tabId);
this.tabRoutes.delete(tabId)
}
}
}
@@ -316,12 +317,12 @@ export class McpSocketPool {
}
private getAvailableSocketPaths(): string[] {
return this.context.getSocketPaths?.() ?? [];
return this.context.getSocketPaths?.() ?? []
}
}
export function createMcpSocketPool(
context: ClaudeForChromeContext,
): McpSocketPool {
return new McpSocketPool(context);
return new McpSocketPool(context)
}

View File

@@ -1,12 +1,12 @@
import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js'
import { SocketConnectionError } from "./mcpSocketClient.js";
import { SocketConnectionError } from './mcpSocketClient.js'
import type {
ClaudeForChromeContext,
PermissionMode,
PermissionOverrides,
SocketClient,
} from "./types.js";
} from './types.js'
export const handleToolCall = async (
context: ClaudeForChromeContext,
@@ -16,21 +16,21 @@ export const handleToolCall = async (
permissionOverrides?: PermissionOverrides,
): Promise<CallToolResult> => {
// Handle permission mode changes locally (not forwarded to extension)
if (name === "set_permission_mode") {
return handleSetPermissionMode(socketClient, args);
if (name === 'set_permission_mode') {
return handleSetPermissionMode(socketClient, args)
}
// Handle switch_browser outside the normal tool call flow (manages its own connection)
if (name === "switch_browser") {
return handleSwitchBrowser(context, socketClient);
if (name === 'switch_browser') {
return handleSwitchBrowser(context, socketClient)
}
try {
const isConnected = await socketClient.ensureConnected();
const isConnected = await socketClient.ensureConnected()
context.logger.silly(
`[${context.serverName}] Server is connected: ${isConnected}. Received tool call: ${name} with args: ${JSON.stringify(args)}.`,
);
)
if (isConnected) {
return await handleToolCallConnected(
@@ -39,28 +39,28 @@ export const handleToolCall = async (
name,
args,
permissionOverrides,
);
)
}
return handleToolCallDisconnected(context);
return handleToolCallDisconnected(context)
} catch (error) {
context.logger.info(`[${context.serverName}] Error calling tool:`, error);
context.logger.info(`[${context.serverName}] Error calling tool:`, error)
if (error instanceof SocketConnectionError) {
return handleToolCallDisconnected(context);
return handleToolCallDisconnected(context)
}
return {
content: [
{
type: "text",
type: 'text',
text: `Error calling tool, please try again. : ${error instanceof Error ? error.message : String(error)}`,
},
],
isError: true,
};
}
}
};
}
async function handleToolCallConnected(
context: ClaudeForChromeContext,
@@ -69,119 +69,119 @@ async function handleToolCallConnected(
args: Record<string, unknown>,
permissionOverrides?: PermissionOverrides,
): Promise<CallToolResult> {
const response = await socketClient.callTool(name, args, permissionOverrides);
const response = await socketClient.callTool(name, args, permissionOverrides)
context.logger.silly(
`[${context.serverName}] Received result from socket bridge: ${JSON.stringify(response)}`,
);
)
if (response === null || response === undefined) {
return {
content: [{ type: "text", text: "Tool execution completed" }],
};
content: [{ type: 'text', text: 'Tool execution completed' }],
}
}
// Response will have either result or error field
const { result, error } = response as {
result?: { content: unknown[] | string };
error?: { content: unknown[] | string };
};
result?: { content: unknown[] | string }
error?: { content: unknown[] | string }
}
// Determine which field has the content and whether it's an error
const contentData = error || result;
const isError = !!error;
const contentData = error || result
const isError = !!error
if (!contentData) {
return {
content: [{ type: "text", text: "Tool execution completed" }],
};
content: [{ type: 'text', text: 'Tool execution completed' }],
}
}
if (isError && isAuthenticationError(contentData.content)) {
context.onAuthenticationError();
context.onAuthenticationError()
}
const { content } = contentData;
const { content } = contentData
if (content && Array.isArray(content)) {
if (isError) {
return {
content: content.map((item: unknown) => {
if (typeof item === "object" && item !== null && "type" in item) {
return item;
if (typeof item === 'object' && item !== null && 'type' in item) {
return item
}
return { type: "text", text: String(item) };
return { type: 'text', text: String(item) }
}),
isError: true,
} as CallToolResult;
} as CallToolResult
}
const convertedContent = content.map((item: unknown) => {
if (
typeof item === "object" &&
typeof item === 'object' &&
item !== null &&
"type" in item &&
"source" in item
'type' in item &&
'source' in item
) {
const typedItem = item;
const typedItem = item
if (
typedItem.type === "image" &&
typeof typedItem.source === "object" &&
typedItem.type === 'image' &&
typeof typedItem.source === 'object' &&
typedItem.source !== null &&
"data" in typedItem.source
'data' in typedItem.source
) {
return {
type: "image",
type: 'image',
data: typedItem.source.data,
mimeType:
"media_type" in typedItem.source
? typedItem.source.media_type || "image/png"
: "image/png",
};
'media_type' in typedItem.source
? typedItem.source.media_type || 'image/png'
: 'image/png',
}
}
}
if (typeof item === "object" && item !== null && "type" in item) {
return item;
if (typeof item === 'object' && item !== null && 'type' in item) {
return item
}
return { type: "text", text: String(item) };
});
return { type: 'text', text: String(item) }
})
return {
content: convertedContent,
isError,
} as CallToolResult;
} as CallToolResult
}
// Handle string content
if (typeof content === "string") {
if (typeof content === 'string') {
return {
content: [{ type: "text", text: content }],
content: [{ type: 'text', text: content }],
isError,
} as CallToolResult;
} as CallToolResult
}
// Fallback for unexpected result format
context.logger.warn(
`[${context.serverName}] Unexpected result format from socket bridge`,
response,
);
)
return {
content: [{ type: "text", text: JSON.stringify(response) }],
content: [{ type: 'text', text: JSON.stringify(response) }],
isError,
};
}
}
function handleToolCallDisconnected(
context: ClaudeForChromeContext,
): CallToolResult {
const text = context.onToolCallDisconnected();
const text = context.onToolCallDisconnected()
return {
content: [{ type: "text", text }],
};
content: [{ type: 'text', text }],
}
}
/**
@@ -194,28 +194,28 @@ async function handleSetPermissionMode(
): Promise<CallToolResult> {
// Validate permission mode at runtime
const validModes = [
"ask",
"skip_all_permission_checks",
"follow_a_plan",
] as const;
const mode = args.mode as string | undefined;
'ask',
'skip_all_permission_checks',
'follow_a_plan',
] as const
const mode = args.mode as string | undefined
const permissionMode: PermissionMode =
mode && validModes.includes(mode as PermissionMode)
? (mode as PermissionMode)
: "ask";
: 'ask'
if (socketClient.setPermissionMode) {
await socketClient.setPermissionMode(
permissionMode,
args.allowed_domains as string[] | undefined,
);
)
}
return {
content: [
{ type: "text", text: `Permission mode set to: ${permissionMode}` },
{ type: 'text', text: `Permission mode set to: ${permissionMode}` },
],
};
}
}
/**
@@ -230,50 +230,50 @@ async function handleSwitchBrowser(
return {
content: [
{
type: "text",
text: "Browser switching is only available with bridge connections.",
type: 'text',
text: 'Browser switching is only available with bridge connections.',
},
],
isError: true,
};
}
}
const isConnected = await socketClient.ensureConnected();
const isConnected = await socketClient.ensureConnected()
if (!isConnected) {
return handleToolCallDisconnected(context);
return handleToolCallDisconnected(context)
}
const result = (await socketClient.switchBrowser?.()) ?? null;
const result = (await socketClient.switchBrowser?.()) ?? null
if (result === "no_other_browsers") {
if (result === 'no_other_browsers') {
return {
content: [
{
type: "text",
text: "No other browsers available to switch to. Open Chrome with the Claude extension in another browser to switch.",
type: 'text',
text: 'No other browsers available to switch to. Open Chrome with the Claude extension in another browser to switch.',
},
],
isError: true,
};
}
}
if (result) {
return {
content: [
{ type: "text", text: `Connected to browser "${result.name}".` },
{ type: 'text', text: `Connected to browser "${result.name}".` },
],
};
}
}
return {
content: [
{
type: "text",
text: "No browser responded within the timeout. Make sure Chrome is open with the Claude extension installed, then try again.",
type: 'text',
text: 'No browser responded within the timeout. Make sure Chrome is open with the Claude extension installed, then try again.',
},
],
isError: true,
};
}
}
/**
@@ -282,20 +282,20 @@ async function handleSwitchBrowser(
function isAuthenticationError(content: unknown[] | string): boolean {
const errorText = Array.isArray(content)
? content
.map((item) => {
if (typeof item === "string") return item;
.map(item => {
if (typeof item === 'string') return item
if (
typeof item === "object" &&
typeof item === 'object' &&
item !== null &&
"text" in item &&
typeof item.text === "string"
'text' in item &&
typeof item.text === 'string'
) {
return item.text;
return item.text
}
return "";
return ''
})
.join(" ")
: String(content);
.join(' ')
: String(content)
return errorText.toLowerCase().includes("re-authenticated");
return errorText.toLowerCase().includes('re-authenticated')
}

View File

@@ -1,64 +1,64 @@
export interface Logger {
info: (message: string, ...args: unknown[]) => void;
error: (message: string, ...args: unknown[]) => void;
warn: (message: string, ...args: unknown[]) => void;
debug: (message: string, ...args: unknown[]) => void;
silly: (message: string, ...args: unknown[]) => void;
info: (message: string, ...args: unknown[]) => void
error: (message: string, ...args: unknown[]) => void
warn: (message: string, ...args: unknown[]) => void
debug: (message: string, ...args: unknown[]) => void
silly: (message: string, ...args: unknown[]) => void
}
export type PermissionMode =
| "ask"
| "skip_all_permission_checks"
| "follow_a_plan";
| 'ask'
| 'skip_all_permission_checks'
| 'follow_a_plan'
export interface BridgeConfig {
/** Bridge WebSocket base URL (e.g., wss://bridge.claudeusercontent.com) */
url: string;
url: string
/** Returns the user's account UUID for the connection path */
getUserId: () => Promise<string | undefined>;
getUserId: () => Promise<string | undefined>
/** Returns a valid OAuth token for bridge authentication */
getOAuthToken: () => Promise<string | undefined>;
getOAuthToken: () => Promise<string | undefined>
/** Optional dev user ID for local development (bypasses OAuth) */
devUserId?: string;
devUserId?: string
}
/** Metadata about a connected Chrome extension instance. */
export interface ChromeExtensionInfo {
deviceId: string;
osPlatform?: string;
connectedAt: number;
name?: string;
deviceId: string
osPlatform?: string
connectedAt: number
name?: string
}
export interface ClaudeForChromeContext {
serverName: string;
logger: Logger;
socketPath: string;
serverName: string
logger: Logger
socketPath: string
// Optional dynamic resolver for socket path. When provided, called on each
// connection attempt to handle runtime conditions (e.g., TMPDIR mismatch).
getSocketPath?: () => string;
getSocketPath?: () => string
// Optional resolver returning all available socket paths (for multi-profile support).
// When provided, a socket pool connects to all sockets and routes by tab ID.
getSocketPaths?: () => string[];
clientTypeId: string; // "desktop" | "claude-code"
onToolCallDisconnected: () => string;
onAuthenticationError: () => void;
isDisabled?: () => boolean;
getSocketPaths?: () => string[]
clientTypeId: string // "desktop" | "claude-code"
onToolCallDisconnected: () => string
onAuthenticationError: () => void
isDisabled?: () => boolean
/** Bridge WebSocket configuration. When provided, uses bridge instead of socket. */
bridgeConfig?: BridgeConfig;
bridgeConfig?: BridgeConfig
/** If set, permission mode is sent to the extension immediately on bridge connection. */
initialPermissionMode?: PermissionMode;
initialPermissionMode?: PermissionMode
/** Optional callback to track telemetry events for bridge connections */
trackEvent?: <K extends string>(
eventName: K,
metadata: Record<string, unknown> | null,
) => void;
) => void
/** Called when user pairs with an extension via the browser pairing flow. */
onExtensionPaired?: (deviceId: string, name: string) => void;
onExtensionPaired?: (deviceId: string, name: string) => void
/** Returns the previously paired deviceId, if any. */
getPersistedDeviceId?: () => string | undefined;
getPersistedDeviceId?: () => string | undefined
/** Called when a remote extension is auto-selected (only option available). */
onRemoteExtensionWarning?: (ext: ChromeExtensionInfo) => void;
onRemoteExtensionWarning?: (ext: ChromeExtensionInfo) => void
}
/**
@@ -66,69 +66,69 @@ export interface ClaudeForChromeContext {
* via navigator.userAgentData.platform.
*/
export function localPlatformLabel(): string {
return process.platform === "darwin"
? "macOS"
: process.platform === "win32"
? "Windows"
: "Linux";
return process.platform === 'darwin'
? 'macOS'
: process.platform === 'win32'
? 'Windows'
: 'Linux'
}
/** Permission request forwarded from the extension to the desktop for user approval. */
export interface BridgePermissionRequest {
/** Links to the pending tool_call */
toolUseId: string;
toolUseId: string
/** Unique ID for this permission request */
requestId: string;
requestId: string
/** Tool type, e.g. "navigate", "click", "execute_javascript" */
toolType: string;
toolType: string
/** The URL/domain context */
url: string;
url: string
/** Additional action data (click coordinates, text, etc.) */
actionData?: Record<string, unknown>;
actionData?: Record<string, unknown>
}
/** Desktop response to a bridge permission request. */
export interface BridgePermissionResponse {
requestId: string;
allowed: boolean;
requestId: string
allowed: boolean
}
/** Per-call permission overrides, allowing each session to use its own permission state. */
export interface PermissionOverrides {
permissionMode: PermissionMode;
allowedDomains?: string[];
permissionMode: PermissionMode
allowedDomains?: string[]
/** Callback invoked when the extension requests user permission via the bridge. */
onPermissionRequest?: (request: BridgePermissionRequest) => Promise<boolean>;
onPermissionRequest?: (request: BridgePermissionRequest) => Promise<boolean>
}
/** Shared interface for McpSocketClient and McpSocketPool */
export interface SocketClient {
ensureConnected(): Promise<boolean>;
ensureConnected(): Promise<boolean>
callTool(
name: string,
args: Record<string, unknown>,
permissionOverrides?: PermissionOverrides,
): Promise<unknown>;
isConnected(): boolean;
disconnect(): void;
): Promise<unknown>
isConnected(): boolean
disconnect(): void
setNotificationHandler(
handler: (notification: {
method: string;
params?: Record<string, unknown>;
method: string
params?: Record<string, unknown>
}) => void,
): void;
): void
/** Set permission mode for the current session. Only effective on BridgeClient. */
setPermissionMode?(
mode: PermissionMode,
allowedDomains?: string[],
): Promise<void>;
): Promise<void>
/** Switch to a different browser. Only available on BridgeClient. */
switchBrowser?(): Promise<
| {
deviceId: string;
name: string;
deviceId: string
name: string
}
| "no_other_browsers"
| 'no_other_browsers'
| null
>;
>
}