Initial commit

This commit is contained in:
moosecrap committed 2026-11-22 04:45:52 -08:00
commit 52ddc6ba9a
27 files changed
+2166

No files matched your search

+236
View File
@@ -0,0 +1,236 @@
from typing import Any, Callable, Dict
class Tool:
def __init__(self, name: str, description: str, schema: Dict[str, Any], handler: Callable):
self.name = name
self.description = description
self.schema = schema
self.handler = handler
def to_mcp_dict(self):
return {
"name": self.name,
"description": self.description,
"inputSchema": self.schema
}
from .page_summary import handle as get_page_summary_handler
from .element_details import handle as get_element_details_handler
from .click_element import handle as click_element_handler
from .type_text import handle as type_text_handler
from .press_key import handle as press_key_handler
from .scroll_page import handle as scroll_page_handler
from .execute_script import handle as execute_script_handler
from .take_screenshot import handle as take_screenshot_handler
from .read_page_text import handle as read_page_text_handler
from .list_tabs import handle as list_tabs_handler
from .switch_tab import handle as switch_tab_handler
from .navigate_to import handle as navigate_to_handler
from .open_new_tab import handle as open_new_tab_handler
from .get_current_url import handle as get_current_url_handler
from .get_page_cookies import handle as get_page_cookies_handler
TOOL_REGISTRY = [
Tool(
name="get_page_summary",
description="Returns a condensed 'Accessibility Tree' of the current page. Scans for interactive elements (buttons, links, inputs, etc.), assigns a temporary unique ID (data-mcp-id), and returns a simplified list with role and visible text/label.",
schema={
"type": "object",
"properties": {
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to scan"},
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the tab to scan"},
},
"required": [],
},
handler=get_page_summary_handler
),
Tool(
name="get_element_details",
description="Returns detailed attributes, value, bounding box, computed style, and surrounding HTML context for a specific element mcp-id.",
schema={
"type": "object",
"properties": {
"id": {"type": "integer", "description": "The mcp-id of the element to inspect"},
"tab_id": {"type": "integer", "description": "The Firefox Tab ID containing the element"},
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the element"},
},
"required": ["id"],
},
handler=get_element_details_handler
),
Tool(
name="click_element",
description="Performs a click action on the element with the specified mcp-id.",
schema={
"type": "object",
"properties": {
"id": {"type": "integer", "description": "The mcp-id of the element to click"},
"tab_id": {"type": "integer", "description": "The Firefox Tab ID containing the element"},
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the element"},
},
"required": ["id"],
},
handler=click_element_handler
),
Tool(
name="type_text",
description="Focuses the element with the specified mcp-id and types the provided text into it.",
schema={
"type": "object",
"properties": {
"id": {"type": "integer", "description": "The mcp-id of the element to type into"},
"text": {"type": "string", "description": "The text to type"},
"tab_id": {"type": "integer", "description": "The Firefox Tab ID containing the element"},
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the element"},
},
"required": ["id", "text"],
},
handler=type_text_handler
),
Tool(
name="press_key",
description="Simulates a keyboard press on the currently focused element (e.g., 'Enter', 'Escape', 'Tab', 'ArrowDown').",
schema={
"type": "object",
"properties": {
"key": {"type": "string", "description": "The key to press (e.g., 'Enter', 'Escape', 'Tab')"},
"tab_id": {"type": "integer", "description": "The Firefox Tab ID containing the element"},
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the element"},
},
"required": ["key"],
},
handler=press_key_handler
),
Tool(
name="scroll_page",
description="Scrolls the page by a specified direction and amount. Amount can be pixels or a percentage (1-100) of the viewport.",
schema={
"type": "object",
"properties": {
"direction": {"type": "string", "description": "Direction to scroll: 'up', 'down', 'left', 'right'", "enum": ["up", "down", "left", "right"]},
"amount": {"type": "integer", "description": "Pixels to scroll, or a percentage (1-100) of viewport size", "default": 500},
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to scroll"},
"window_id": {"type": "integer", "description": "The Firefox Window ID to scroll"},
},
"required": ["direction"],
},
handler=scroll_page_handler
),
Tool(
name="execute_script",
description="Executes arbitrary JavaScript in the context of the current page. (God Mode - use with caution).",
schema={
"type": "object",
"properties": {
"js_code": {"type": "string", "description": "JavaScript code to execute"},
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to execute in"},
"window_id": {"type": "integer", "description": "The Firefox Window ID to execute in"},
},
"required": ["js_code"],
},
handler=execute_script_handler
),
Tool(
name="take_screenshot",
description="Captures a screenshot of the current viewport in a window and returns it as a data URL (PNG). Can only capture the visible tab in a window.",
schema={
"type": "object",
"properties": {
"window_id": {"type": "integer", "description": "The Firefox Window ID to capture (uses the visible tab in that window)"},
},
"required": [],
},
handler=take_screenshot_handler
),
Tool(
name="read_page_text",
description="Returns a 'Reader Mode' version of the page, stripping scripts, styles, nav, headers, footers, and returning only the primary textual content.",
schema={
"type": "object",
"properties": {
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to read"},
"window_id": {"type": "integer", "description": "The Firefox Window ID to read"},
},
"required": [],
},
handler=read_page_text_handler
),
Tool(
name="list_tabs",
description="Lists all open Firefox tabs, including their titles, URLs, internal Tab IDs, and active status.",
schema={
"type": "object",
"properties": {},
"required": [],
},
handler=list_tabs_handler
),
Tool(
name="switch_tab",
description="Switches focus to the specified Tab ID or Window ID.",
schema={
"type": "object",
"properties": {
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to switch to"},
"window_id": {"type": "integer", "description": "The Firefox Window ID to switch to (switches to active tab in that window)"},
},
"required": [],
},
handler=switch_tab_handler
),
Tool(
name="navigate_to",
description="Navigates the specified tab to the specified URL.",
schema={
"type": "object",
"properties": {
"url": {"type": "string", "description": "The URL to navigate to"},
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to navigate"},
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the tab to navigate"},
},
"required": ["url"],
},
handler=navigate_to_handler
),
Tool(
name="open_new_tab",
description="Opens a new tab with the specified URL.",
schema={
"type": "object",
"properties": {
"url": {"type": "string", "description": "The URL to open in the new tab"},
"window_id": {"type": "integer", "description": "The Firefox Window ID to open the new tab in"},
},
"required": ["url"],
},
handler=open_new_tab_handler
),
Tool(
name="get_current_url",
description="Returns the current URL of the specified tab or the active tab.",
schema={
"type": "object",
"properties": {
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to get the URL from"},
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the tab to get the URL from"},
},
"required": [],
},
handler=get_current_url_handler
),
Tool(
name="get_page_cookies",
description="Retrieves cookies for the specified tab or current domain.",
schema={
"type": "object",
"properties": {
"tab_id": {"type": "integer", "description": "The Firefox Tab ID to get cookies from"},
"window_id": {"type": "integer", "description": "The Firefox Window ID containing the tab to get cookies from"},
},
"required": [],
},
handler=get_page_cookies_handler
),
]
+22
View File
@@ -0,0 +1,22 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Clicks the element with the specified mcp-id.
"""
eid = args.get("id")
if eid is None:
raise ToolError("Missing required argument: 'id'")
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {"id": int(eid)}
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
if args.get("tab_id") is not None:
params["tab_id"] = int(args["tab_id"])
await bridge.send_to_extension(request_id, "click_element", params)
return [{"type": "text", "text": f"Clicked element with mcp-id={eid}."}]
+39
View File
@@ -0,0 +1,39 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Returns detailed attributes and HTML for a specific element mcp-id.
"""
eid = args.get("id")
if eid is None:
raise ToolError("Missing required argument: 'id'")
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {"id": int(eid)}
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
if args.get("tab_id") is not None:
params["tab_id"] = int(args["tab_id"])
result = await bridge.send_to_extension(request_id, "get_element_details", params)
if not result:
raise ToolError(f"Element with mcp-id {eid} not found or has no details")
lines = [f"# Element Details (mcp-id={eid})\n"]
for key, value in result.items():
if key == "html":
lines.append(f"## HTML\n```html\n{value}\n```")
elif key == "bounding_box":
lines.append(f"## Bounding Box\n- x: {value.get('x', 'N/A')}\n- y: {value.get('y', 'N/A')}\n- width: {value.get('width', 'N/A')}\n- height: {value.get('height', 'N/A')}")
elif key == "attributes" and isinstance(value, dict):
lines.append("## Attributes")
for k, v in value.items():
lines.append(f"- {k}: {v}")
else:
lines.append(f"- **{key}**: {value}")
return [{"type": "text", "text": "\n".join(lines)}]
+24
View File
@@ -0,0 +1,24 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Executes arbitrary JavaScript in the current page.
"""
js_code = args.get("js_code")
if not js_code:
raise ToolError("Missing required argument: 'js_code'")
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {"js_code": str(js_code)}
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
if args.get("tab_id") is not None:
params["tab_id"] = int(args["tab_id"])
result = await bridge.send_to_extension(request_id, "execute_script", params)
output = result.get("result", "") if isinstance(result, dict) else str(result)
return [{"type": "text", "text": f"Script result:\n{output}"}]
+20
View File
@@ -0,0 +1,20 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Returns the current URL of the specified tab or the active tab.
"""
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {}
if args.get("tab_id") is not None:
params["tab_id"] = int(args["tab_id"])
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
result = await bridge.send_to_extension(request_id, "get_current_url", params)
url = result.get("url", "unknown") if isinstance(result, dict) else str(result)
return [{"type": "text", "text": f"Current URL: {url}"}]
+35
View File
@@ -0,0 +1,35 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Retrieves cookies for the specified tab or current domain.
"""
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {}
if args.get("tab_id") is not None:
params["tab_id"] = int(args["tab_id"])
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
result = await bridge.send_to_extension(request_id, "get_page_cookies", params)
cookies = result if isinstance(result, list) else []
lines = ["# Page Cookies\n"]
if not cookies:
lines.append("No cookies found for this domain.")
else:
for c in cookies:
name = c.get("name", "")
value = c.get("value", "")
domain = c.get("domain", "")
path = c.get("path", "")
secure = "Secure" if c.get("secure") else ""
http_only = "HttpOnly" if c.get("httpOnly") else ""
session = "Session" if c.get("session") else ""
flags = " | ".join([f for f in [secure, http_only, session] if f])
lines.append(f"- **{name}**: {value} (domain={domain}, path={path}) {flags}")
return [{"type": "text", "text": "\n".join(lines)}]
+27
View File
@@ -0,0 +1,27 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Lists all open Firefox tabs.
"""
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
result = await bridge.send_to_extension(request_id, "list_tabs", {})
tabs = result if isinstance(result, list) else []
lines = ["# Open Tabs\n"]
if not tabs:
lines.append("No tabs found.")
else:
for tab in tabs:
tid = tab.get("id", "?")
title = tab.get("title", "(no title)")
url = tab.get("url", "")
active = " (ACTIVE)" if tab.get("active") else ""
wid = tab.get("windowId", "?")
lines.append(f"- **Tab {tid}** (window {wid}): {title}{active}")
lines.append(f" URL: {url}")
return [{"type": "text", "text": "\n".join(lines)}]
+22
View File
@@ -0,0 +1,22 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Navigates the specified tab to the specified URL.
"""
url = args.get("url")
if not url:
raise ToolError("Missing required argument: 'url'")
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {"url": str(url)}
if args.get("tab_id") is not None:
params["tab_id"] = int(args["tab_id"])
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
await bridge.send_to_extension(request_id, "navigate_to", params)
return [{"type": "text", "text": f"Navigated to {url}."}]
+20
View File
@@ -0,0 +1,20 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Opens a new tab with the specified URL.
"""
url = args.get("url")
if not url:
raise ToolError("Missing required argument: 'url'")
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {"url": str(url)}
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
await bridge.send_to_extension(request_id, "open_new_tab", params)
return [{"type": "text", "text": f"Opened new tab with {url}."}]
+45
View File
@@ -0,0 +1,45 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Scans the specified tab for interactive elements, assigns mcp-ids,
and returns a simplified list.
"""
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {}
if args.get("tab_id") is not None:
params["tab_id"] = int(args["tab_id"])
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
result = await bridge.send_to_extension(request_id, "get_page_summary", params)
elements = result if isinstance(result, list) else []
lines = ["# Page Summary - Interactive Elements\n"]
lines.append("The following interactive elements have been indexed on the current page.")
lines.append("Use the `id` (mcp-id) with `click_element`, `type_text`, or `get_element_details`.\n")
if not elements:
lines.append("No interactive elements found on this page.")
else:
for el in elements:
eid = el.get("id", "?")
role = el.get("role", "unknown")
text = el.get("text", "") or el.get("label", "")
tag = el.get("tag", "")
href = el.get("href", "")
line = f"- **id={eid}** [{role}]"
if text:
line += f" - \"{text[:100]}\""
if tag:
line += f" (<{tag}>"
if href:
line += f" href={href}"
line += ")"
lines.append(line)
lines.append("\nTotal elements indexed: " + str(len(elements)))
return [{"type": "text", "text": "\n".join(lines)}]
+22
View File
@@ -0,0 +1,22 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Simulates a keyboard press.
"""
key = args.get("key")
if not key:
raise ToolError("Missing required argument: 'key'")
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {"key": str(key)}
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
if args.get("tab_id") is not None:
params["tab_id"] = int(args["tab_id"])
await bridge.send_to_extension(request_id, "press_key", params)
return [{"type": "text", "text": f"Pressed key '{key}'."}]
+23
View File
@@ -0,0 +1,23 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Returns a reader-mode version of the page text.
"""
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {}
if args.get("tab_id") is not None:
params["tab_id"] = int(args["tab_id"])
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
result = await bridge.send_to_extension(request_id, "read_page_text", params)
text = result if isinstance(result, str) else str(result)
if not text or text.strip() == "":
return [{"type": "text", "text": "No readable text found on this page."}]
return [{"type": "text", "text": f"# Page Text (Reader Mode)\n\n{text}"}]
+26
View File
@@ -0,0 +1,26 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Scrolls the page by direction and amount.
"""
direction = args.get("direction")
amount = args.get("amount", 500)
if not direction:
raise ToolError("Missing required argument: 'direction'")
if direction not in ("up", "down", "left", "right"):
raise ToolError(f"Invalid direction '{direction}'. Must be: up, down, left, right")
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {"direction": direction, "amount": int(amount)}
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
if args.get("tab_id") is not None:
params["tab_id"] = int(args["tab_id"])
await bridge.send_to_extension(request_id, "scroll_page", params)
return [{"type": "text", "text": f"Scrolled {direction} by {amount}."}]
+20
View File
@@ -0,0 +1,20 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Switches focus to the specified Tab ID. Gets the tab by its internal ID
(works across all windows), focuses that tab's window, and highlights it.
"""
tab_id = args.get("tab_id")
if tab_id is None:
raise ToolError("Missing required argument: 'tab_id'")
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
result = await bridge.send_to_extension(request_id, "switch_tab", {"tab_id": int(tab_id)})
if result and result.get("url"):
return [{"type": "text", "text": f"Switched to tab {tab_id} ({result['url']})."}]
return [{"type": "text", "text": f"Switched to tab {tab_id}."}]
+28
View File
@@ -0,0 +1,28 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Captures a screenshot of the current viewport.
Window ID is optional - captures the visible tab in that window.
"""
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {}
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
result = await bridge.send_to_extension(request_id, "take_screenshot", params)
screenshot_url = None
if isinstance(result, dict):
screenshot_url = result.get("screenshot")
if screenshot_url and screenshot_url.startswith("data:image/png;base64,"):
b64_data = screenshot_url.split(",", 1)[1]
return [
{"type": "text", "text": "Screenshot captured successfully."},
{"type": "image", "data": b64_data, "mimeType": "image/png"}
]
return [{"type": "text", "text": "Failed to capture screenshot."}]
+26
View File
@@ -0,0 +1,26 @@
import asyncio
from typing import Any, Dict
from tools.utils import ToolError
async def handle(args: Dict[str, Any], bridge: Any) -> list:
"""
Types text into the element with the specified mcp-id.
"""
eid = args.get("id")
text = args.get("text")
if eid is None:
raise ToolError("Missing required argument: 'id'")
if text is None:
raise ToolError("Missing required argument: 'text'")
request_id = f"req_{asyncio.get_event_loop().time()}_{id(args)}"
params: Dict[str, Any] = {"id": int(eid), "text": str(text)}
if args.get("window_id") is not None:
params["window_id"] = int(args["window_id"])
if args.get("tab_id") is not None:
params["tab_id"] = int(args["tab_id"])
await bridge.send_to_extension(request_id, "type_text", params)
return [{"type": "text", "text": f"Typed text into element mcp-id={eid}."}]
+41
View File
@@ -0,0 +1,41 @@
import time
import datetime
from pathlib import Path
from typing import List, Dict, Any, Optional
class ToolError(Exception):
"""Custom exception for tool-related errors to be caught by the MCP server."""
pass
def format_relative_time(timestamp: float) -> str:
"""Converts a timestamp to a human-readable relative format."""
now = time.time()
diff = now - timestamp
seconds = int(diff)
if seconds < 0:
return "In the future"
if seconds < 60:
return "Just now"
minutes = seconds // 60
if minutes < 60:
return f"{minutes}m ago"
hours = minutes // 60
if hours < 24:
return f"{hours}h ago"
days = hours // 24
if days == 1:
return "Yesterday"
if days < 30:
return f"{days}d ago"
months = days // 30
if months < 12:
return f"{months}mo ago"
dt = datetime.datetime.fromtimestamp(timestamp)
return dt.strftime('%Y-%m-%d')