Initial commit
This commit is contained in:
commit
52ddc6ba9a
27 files changed
+2166
No files matched your search
@@ -0,0 +1,176 @@
|
||||
# Created by https://www.toptal.com/developers/gitignore/api/python
|
||||
# Edit at https://www.toptal.com/developers/gitignore?templates=python
|
||||
|
||||
### Python ###
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/#use-with-ide
|
||||
.pdm.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
### Python Patch ###
|
||||
# Poetry local configuration file - https://python-poetry.org/docs/configuration/#local-configuration
|
||||
poetry.toml
|
||||
|
||||
# ruff
|
||||
.ruff_cache/
|
||||
|
||||
# LSP config files
|
||||
pyrightconfig.json
|
||||
|
||||
# End of https://www.toptal.com/developers/gitignore/api/python
|
||||
@@ -0,0 +1,20 @@
|
||||
import logging
|
||||
from pathlib import Path
|
||||
from contextvars import ContextVar
|
||||
|
||||
# --- Project Root ---
|
||||
ROOT_DIR = Path(__file__).parent.resolve()
|
||||
|
||||
# --- Server & Logs ---
|
||||
HOST = "127.0.0.1"
|
||||
PORT = 8008
|
||||
request_host = ContextVar("request_host", default=f"{HOST}:{PORT}")
|
||||
LOG_LEVEL = "INFO"
|
||||
LOG_FILE = str(ROOT_DIR / "debug.log")
|
||||
|
||||
# --- WebSocket (Extension) ---
|
||||
WS_PATH = "/ws"
|
||||
WS_TIMEOUT = 30 # seconds to wait for extension response
|
||||
|
||||
# --- Extension ---
|
||||
EXTENSION_DIR = ROOT_DIR.parent / "extension"
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import signal
|
||||
import sys
|
||||
import json
|
||||
|
||||
import uvicorn
|
||||
from starlette.applications import Starlette
|
||||
from starlette.routing import Route, WebSocketRoute
|
||||
from starlette.responses import Response, StreamingResponse
|
||||
from starlette.middleware.cors import CORSMiddleware
|
||||
from starlette.websockets import WebSocket, WebSocketDisconnect
|
||||
|
||||
from mcp_logic import MCPBridge
|
||||
from tools import TOOL_REGISTRY
|
||||
import config
|
||||
|
||||
|
||||
# --- Configuration & Logging ---
|
||||
logging.basicConfig(
|
||||
level=getattr(logging, config.LOG_LEVEL),
|
||||
filename=config.LOG_FILE,
|
||||
filemode="a",
|
||||
format="%(asctime)s - %(levelname)s - %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("FirefoxMCP")
|
||||
|
||||
bridge = MCPBridge()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# SSE Transport (for MCP clients / LLMs)
|
||||
# ------------------------------------------------------------------
|
||||
async def sse_endpoint(request):
|
||||
"""SSE endpoint: MCP clients connect here to receive responses."""
|
||||
sid = bridge.create_session()
|
||||
logger.debug(f"SSE session started: {sid}")
|
||||
|
||||
async def event_generator():
|
||||
try:
|
||||
# Tell the client where to POST messages
|
||||
yield f"event: endpoint\ndata: /messages?session_id={sid}\n\n"
|
||||
queue = bridge.sessions[sid]
|
||||
while bridge.running:
|
||||
try:
|
||||
msg = await asyncio.wait_for(queue.get(), timeout=0.5)
|
||||
yield f"event: message\ndata: {msg}\n\n"
|
||||
queue.task_done()
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
except asyncio.CancelledError:
|
||||
logger.debug(f"SSE session cancelled: {sid}")
|
||||
finally:
|
||||
bridge.sessions.pop(sid, None)
|
||||
logger.debug(f"SSE session closed: {sid}")
|
||||
|
||||
return StreamingResponse(event_generator(), media_type="text/event-stream")
|
||||
|
||||
|
||||
async def messages_endpoint(request):
|
||||
"""HTTP POST endpoint: MCP clients send tool calls here."""
|
||||
sid = request.query_params.get("session_id")
|
||||
if not sid or sid not in bridge.sessions:
|
||||
return Response("Session not found", status_code=404)
|
||||
|
||||
# Capture host header for any URL generation
|
||||
host_header = request.headers.get("host", f"{config.HOST}:{config.PORT}")
|
||||
config.request_host.set(host_header)
|
||||
|
||||
try:
|
||||
body = await request.json()
|
||||
except Exception as e:
|
||||
return Response(f"Invalid JSON: {e}", status_code=400)
|
||||
|
||||
method = body.get("method")
|
||||
params = body.get("params", {})
|
||||
req_id = body.get("id")
|
||||
|
||||
logger.debug(f"MCP Request: {method} (ID: {req_id})")
|
||||
|
||||
result = await bridge.handle_request(method, params, req_id, TOOL_REGISTRY)
|
||||
|
||||
if isinstance(result, Response):
|
||||
return result
|
||||
|
||||
# Send the result back via SSE
|
||||
await bridge.send_to_session(
|
||||
sid,
|
||||
{"jsonrpc": "2.0", "id": req_id, "result": result},
|
||||
)
|
||||
return Response(status_code=202)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# WebSocket Transport (for the Firefox Extension)
|
||||
# ------------------------------------------------------------------
|
||||
async def extension_websocket(websocket: WebSocket):
|
||||
"""WebSocket endpoint: the Firefox extension connects here."""
|
||||
await websocket.accept()
|
||||
bridge.set_extension_websocket(websocket)
|
||||
logger.info("Firefox extension connected via WebSocket")
|
||||
|
||||
try:
|
||||
while True:
|
||||
data = await websocket.receive_text()
|
||||
try:
|
||||
msg = json.loads(data)
|
||||
except json.JSONDecodeError:
|
||||
logger.error(f"Invalid JSON from extension: {data}")
|
||||
continue
|
||||
|
||||
msg_type = msg.get("type")
|
||||
request_id = msg.get("request_id")
|
||||
|
||||
if msg_type == "response":
|
||||
result = msg.get("result")
|
||||
error = msg.get("error")
|
||||
bridge.handle_extension_response(request_id, result=result, error=error)
|
||||
logger.debug(f"Extension response for {request_id}: {'error' if error else 'ok'}")
|
||||
elif msg_type == "register":
|
||||
logger.debug(f"Extension registered: {msg}")
|
||||
else:
|
||||
logger.warning(f"Unknown message type from extension: {msg_type}")
|
||||
|
||||
except WebSocketDisconnect:
|
||||
logger.info("Firefox extension disconnected")
|
||||
except Exception as e:
|
||||
logger.error(f"WebSocket error: {e}")
|
||||
finally:
|
||||
bridge.remove_extension_websocket()
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Starlette App
|
||||
# ------------------------------------------------------------------
|
||||
app = Starlette(
|
||||
routes=[
|
||||
Route("/sse", endpoint=sse_endpoint),
|
||||
Route("/messages", endpoint=messages_endpoint, methods=["POST"]),
|
||||
WebSocketRoute(config.WS_PATH, endpoint=extension_websocket),
|
||||
]
|
||||
)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Entry point
|
||||
# ------------------------------------------------------------------
|
||||
if __name__ == "__main__":
|
||||
uvicorn_config = uvicorn.Config(
|
||||
app=app,
|
||||
host=config.HOST,
|
||||
port=config.PORT,
|
||||
log_level="info",
|
||||
timeout_graceful_shutdown=2,
|
||||
)
|
||||
|
||||
server = uvicorn.Server(uvicorn_config)
|
||||
|
||||
def signal_handler(sig, frame):
|
||||
logger.info("Shutdown signal received")
|
||||
bridge.running = False
|
||||
server.should_exit = True
|
||||
|
||||
signal.signal(signal.SIGINT, signal_handler)
|
||||
signal.signal(signal.SIGTERM, signal_handler)
|
||||
|
||||
try:
|
||||
asyncio.run(server.serve())
|
||||
except KeyboardInterrupt:
|
||||
pass
|
||||
finally:
|
||||
logger.info("Server process exiting.")
|
||||
sys.exit(0)
|
||||
@@ -0,0 +1,162 @@
|
||||
import asyncio
|
||||
import uuid
|
||||
import json
|
||||
from typing import Any, Dict, Union, List, Optional
|
||||
from starlette.responses import Response
|
||||
from starlette.websockets import WebSocket
|
||||
|
||||
from tools.utils import ToolError
|
||||
|
||||
|
||||
class MCPBridge:
|
||||
"""
|
||||
The Bridge between MCP clients (LLMs) and the Firefox Extension.
|
||||
|
||||
Manages:
|
||||
- SSE sessions for MCP clients
|
||||
- WebSocket connection from the Firefox extension
|
||||
- Correlation of MCP tool calls with extension responses
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# SSE sessions: session_id -> asyncio.Queue
|
||||
self.sessions: Dict[str, asyncio.Queue] = {}
|
||||
self.running = True
|
||||
|
||||
# WebSocket connection from the Firefox extension
|
||||
self.extension_ws: Optional[WebSocket] = None
|
||||
|
||||
# Pending requests: request_id -> asyncio.Future
|
||||
self.pending_requests: Dict[str, asyncio.Future] = {}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# SSE session management
|
||||
# ------------------------------------------------------------------
|
||||
def create_session(self) -> str:
|
||||
sid = str(uuid.uuid4())
|
||||
self.sessions[sid] = asyncio.Queue()
|
||||
return sid
|
||||
|
||||
async def send_to_session(self, sid: str, message: Dict[str, Any]):
|
||||
if sid in self.sessions:
|
||||
await self.sessions[sid].put(json.dumps(message))
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Extension WebSocket management
|
||||
# ------------------------------------------------------------------
|
||||
def set_extension_websocket(self, ws: WebSocket):
|
||||
self.extension_ws = ws
|
||||
|
||||
def remove_extension_websocket(self):
|
||||
self.extension_ws = None
|
||||
# Cancel all pending requests since the extension is gone
|
||||
for fut in self.pending_requests.values():
|
||||
if not fut.done():
|
||||
fut.set_exception(Exception("Firefox extension disconnected"))
|
||||
self.pending_requests.clear()
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Send a request to the extension and wait for its response
|
||||
# ------------------------------------------------------------------
|
||||
async def send_to_extension(
|
||||
self,
|
||||
request_id: str,
|
||||
action: str,
|
||||
params: Dict[str, Any],
|
||||
timeout: float = 30.0,
|
||||
) -> Any:
|
||||
if not self.extension_ws:
|
||||
raise ToolError(
|
||||
"Firefox extension is not connected. "
|
||||
"Load the extension in Firefox (about:debugging) and ensure it connects to ws://127.0.0.1:8008/ws"
|
||||
)
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
future: asyncio.Future = loop.create_future()
|
||||
self.pending_requests[request_id] = future
|
||||
|
||||
message = json.dumps({
|
||||
"type": "request",
|
||||
"request_id": request_id,
|
||||
"action": action,
|
||||
"params": params,
|
||||
})
|
||||
|
||||
try:
|
||||
await self.extension_ws.send_text(message)
|
||||
result = await asyncio.wait_for(future, timeout=timeout)
|
||||
return result
|
||||
except asyncio.TimeoutError:
|
||||
raise ToolError(f"Extension did not respond to '{action}' within {timeout:.0f} seconds")
|
||||
finally:
|
||||
self.pending_requests.pop(request_id, None)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Called by the WebSocket handler when the extension responds
|
||||
# ------------------------------------------------------------------
|
||||
def handle_extension_response(self, request_id: str, result: Any = None, error: Optional[str] = None):
|
||||
future = self.pending_requests.get(request_id)
|
||||
if future and not future.done():
|
||||
if error:
|
||||
future.set_exception(Exception(error))
|
||||
else:
|
||||
future.set_result(result)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# MCP protocol request handling
|
||||
# ------------------------------------------------------------------
|
||||
async def handle_request(
|
||||
self,
|
||||
method: str,
|
||||
params: Dict[str, Any],
|
||||
req_id: Any,
|
||||
tool_registry: List[Any],
|
||||
) -> Union[Dict[str, Any], Response]:
|
||||
if method == "initialize":
|
||||
return {
|
||||
"protocolVersion": "2024-11-05",
|
||||
"capabilities": {"tools": {}},
|
||||
"serverInfo": {"name": "FirefoxMCP", "version": "0.1.0"},
|
||||
}
|
||||
|
||||
if method == "tools/list":
|
||||
return {"tools": [t.to_mcp_dict() for t in tool_registry]}
|
||||
|
||||
if method == "tools/call":
|
||||
name = params.get("name")
|
||||
args = params.get("arguments", {})
|
||||
|
||||
tool = next((t for t in tool_registry if t.name == name), None)
|
||||
if not tool:
|
||||
return Response(
|
||||
content=json.dumps(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"error": {"code": -32601, "message": f"Tool {name} not found"},
|
||||
}
|
||||
),
|
||||
media_type="application/json",
|
||||
)
|
||||
|
||||
try:
|
||||
# Pass the bridge instance as the second argument so tools can
|
||||
# send commands to the Firefox extension.
|
||||
content = await tool.handler(args, self)
|
||||
except ToolError as e:
|
||||
content = [{"type": "text", "text": str(e)}]
|
||||
except Exception as e:
|
||||
content = [{"type": "text", "text": f"Unexpected internal error: {str(e)}"}]
|
||||
|
||||
return {"content": content}
|
||||
|
||||
return Response(
|
||||
content=json.dumps(
|
||||
{
|
||||
"jsonrpc": "2.0",
|
||||
"id": req_id,
|
||||
"error": {"code": -32601, "message": f"Method {method} not found"},
|
||||
}
|
||||
),
|
||||
media_type="application/json",
|
||||
)
|
||||
@@ -0,0 +1,3 @@
|
||||
uvicorn[standard]
|
||||
starlette
|
||||
websockets
|
||||
@@ -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
|
||||
),
|
||||
]
|
||||
@@ -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}."}]
|
||||
@@ -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)}]
|
||||
@@ -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}"}]
|
||||
@@ -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}"}]
|
||||
@@ -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)}]
|
||||
@@ -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)}]
|
||||
@@ -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}."}]
|
||||
@@ -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}."}]
|
||||
@@ -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)}]
|
||||
@@ -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}'."}]
|
||||
@@ -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}"}]
|
||||
@@ -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}."}]
|
||||
@@ -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}."}]
|
||||
@@ -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."}]
|
||||
@@ -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}."}]
|
||||
@@ -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')
|
||||
Reference in new issue
Block a user