- hub: FastAPI backend (MCP server, ADB LAN controller, bridge, storage) - hub/web: Vue 3 admin console (device manager, screen mirror, chat workbench) - android: Kotlin shell app with WebView stage, OTA, telemetry, keep-alive - protocol: architecture, MCP schema, and WebSocket protocol specs
277 lines
13 KiB
Python
277 lines
13 KiB
Python
from __future__ import annotations
|
|
|
|
import contextvars
|
|
import json
|
|
import uuid
|
|
from typing import Any
|
|
|
|
from mcp.server.mcpserver import MCPServer
|
|
|
|
from app.adb_lan.controller import LanAdbController
|
|
from app.bridge.manager import DeviceBridgeManager
|
|
from app.storage.db import PulseWallDB, now_ms
|
|
|
|
# Populated by ASGI middleware on /mcp to verify whether the caller is on private LAN.
|
|
mcp_request_is_lan: contextvars.ContextVar[bool] = contextvars.ContextVar("mcp_request_is_lan", default=False)
|
|
|
|
|
|
UI_FRAMEWORK_GUIDE = {
|
|
"local_assets_base": "https://appassets.androidplatform.net/assets/pulsewall/",
|
|
"preloaded_globals": [
|
|
"Vue (Vue 3 runtime)",
|
|
"dayjs (Day.js datetime ~2KB)",
|
|
"PwIcons (ultra-light offline SVG icons: PwIcons.svg('cpu', 20) or <span data-pw-icon='cpu'></span>)",
|
|
"pulsewall-tokens.css + tailwind-lite.min.css (zero-runtime Tailwind utility classes & dark-glass tokens)",
|
|
"window.PulseWall JSBridge: loadLib(nameOrArray), sendAction(id, label, customText), getDeviceProfile(), getTelemetry(), getDataContext()",
|
|
],
|
|
"lazy_local_libraries": {
|
|
"usage": "Call `await window.PulseWall.loadLib(['plyr', 'hls'])` (or `<script src='./libs/...'>`). All files load offline from APK in <5ms — NEVER use external CDN URLs when a local library exists!",
|
|
"libs": {
|
|
"plyr": {"global": "Plyr", "files": "./libs/plyr.min.js + ./libs/plyr.css", "use_for": "Lightweight zero-dep media player UI (preferred)"},
|
|
"hls": {"global": "Hls", "files": "./libs/hls.light.min.js", "use_for": "HLS (.m3u8) live/VOD streaming engine (light build)"},
|
|
"echarts": {"global": "echarts", "files": "./libs/echarts.custom.min.js", "heavy": True, "use_for": "Tree-shaken ECharts (Line/Bar/Pie/Gauge/Radar/Scatter + CanvasRenderer). Load ONLY when rich charts are needed."},
|
|
"konva": {"global": "Konva", "files": "./libs/konva.min.js", "use_for": "2D interactive canvas & object manipulation"},
|
|
"three": {"global": "THREE", "files": "./libs/three.min.js", "heavy": True, "use_for": "3D WebGL scenes. Heavy — avoid on low-end TV boxes unless explicitly requested."},
|
|
"rough": {"global": "rough", "files": "./libs/rough.min.js", "use_for": "Hand-drawn sketchy Canvas/SVG visuals (<9KB)"},
|
|
"lodash": {"global": "_", "files": "./libs/lodash-lite.min.js", "use_for": "Tree-shaken lodash-es (debounce, throttle, cloneDeep, merge, groupBy, sortBy, orderBy, uniq, chunk, clamp, pick, omit, get, set, sumBy, meanBy, keyBy, round, range)"},
|
|
"zustand": {"global": "Zustand", "files": "./libs/zustand.min.js", "use_for": "Minimal shared state store (`Zustand.createStore`, ~1KB)"},
|
|
"anime": {"global": "anime", "files": "./libs/anime.min.js", "use_for": "Lightweight JS animation (~6KB, use only when CSS transitions aren't enough)"},
|
|
},
|
|
},
|
|
"compatibility_rules": [
|
|
"Always respect device viewport_css_w / viewport_css_h, device_type (tv/phone/tablet), and safe_area_top_dp / safe_area_bottom_dp.",
|
|
"Prefer lightweight core libs (Vue + tailwind-lite + dayjs + PwIcons + rough/konva); only lazy-load heavy libs (echarts, three) when genuinely needed.",
|
|
"Avoid fixed pixel widths exceeding viewport_css_w; prefer flexbox/grid and relative units.",
|
|
"Target Android 11 WebView compatibility (Chrome 83+ / ES2020): avoid bleeding-edge CSS like :has() or container queries unless guarded.",
|
|
"Never overwrite native alert layer; render page content inside the canvas container only.",
|
|
],
|
|
}
|
|
|
|
|
|
def build_mcp_server(
|
|
db: PulseWallDB,
|
|
bridge: DeviceBridgeManager,
|
|
adb_controller: LanAdbController,
|
|
) -> MCPServer:
|
|
mcp = MCPServer(
|
|
name="PulseWall Hub",
|
|
instructions=(
|
|
"PulseWall controls connected Android information-wall devices. "
|
|
"Always inspect get_device_status(device_id) before calling render_page so styles match the exact "
|
|
"phone/tablet viewport and Android 11 WebView version. For important alerts requiring user action, "
|
|
"provide 2-4 high-probability preset buttons before optional free-text input."
|
|
),
|
|
version="0.1.0",
|
|
)
|
|
|
|
# ---- Resources ----
|
|
@mcp.resource("pulsewall://devices")
|
|
def res_devices() -> str:
|
|
return json.dumps(db.list_devices(), ensure_ascii=False, indent=2)
|
|
|
|
@mcp.resource("pulsewall://device/{device_id}/profile")
|
|
def res_device_profile(device_id: str) -> str:
|
|
dev = db.get_device(device_id)
|
|
if not dev:
|
|
return json.dumps({"error": f"Device '{device_id}' not found"}, ensure_ascii=False)
|
|
return json.dumps(
|
|
{
|
|
"device": dev,
|
|
"ui_framework_guide": UI_FRAMEWORK_GUIDE,
|
|
},
|
|
ensure_ascii=False,
|
|
indent=2,
|
|
)
|
|
|
|
@mcp.resource("pulsewall://device/{device_id}/layout")
|
|
def res_device_layout(device_id: str) -> str:
|
|
snaps = db.list_snapshots(device_id=device_id, limit=5)
|
|
return json.dumps({"device_id": device_id, "recent_snapshots": snaps}, ensure_ascii=False, indent=2)
|
|
|
|
@mcp.resource("pulsewall://events/pending")
|
|
def res_pending_events() -> str:
|
|
return json.dumps(db.list_pending_events(limit=30), ensure_ascii=False, indent=2)
|
|
|
|
# ---- Tools ----
|
|
@mcp.tool()
|
|
def list_devices() -> dict[str, Any]:
|
|
"""List all registered Android devices with online state, capabilities, and display summary."""
|
|
devices = db.list_devices()
|
|
return {"count": len(devices), "devices": devices}
|
|
|
|
@mcp.tool()
|
|
def get_device_status(device_id: str) -> dict[str, Any]:
|
|
"""Get real-time hardware telemetry, DisplayProfile (viewport/DPI/safe-area/webview_version), and UI style hints for a device."""
|
|
dev = db.get_device(device_id)
|
|
if not dev:
|
|
return {"ok": False, "error": f"Device '{device_id}' not found."}
|
|
return {
|
|
"ok": True,
|
|
"device": dev,
|
|
"ui_framework_guide": UI_FRAMEWORK_GUIDE,
|
|
}
|
|
|
|
@mcp.tool()
|
|
async def push_feed_item(
|
|
device_id: str,
|
|
title: str,
|
|
body: str,
|
|
level: str = "info",
|
|
source: str = "ai",
|
|
sound: str = "ding",
|
|
html_snippet: str | None = None,
|
|
tags: list[str] | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Push a passive live-feed item to the device (no user confirmation required)."""
|
|
item_id = f"feed_{uuid.uuid4().hex[:10]}"
|
|
payload = {
|
|
"item_id": item_id,
|
|
"title": title,
|
|
"body": body,
|
|
"level": level,
|
|
"source": source,
|
|
"sound": sound,
|
|
"html_snippet": html_snippet,
|
|
"tags": tags or [],
|
|
"ts": now_ms(),
|
|
}
|
|
sent = await bridge.send_frame(device_id, "feed.push", payload)
|
|
db.add_audit("feed", device_id, f"[{level}] {title}", payload)
|
|
return {"ok": sent, "item_id": item_id, "delivered": sent}
|
|
|
|
@mcp.tool()
|
|
async def trigger_alert(
|
|
device_id: str,
|
|
title: str,
|
|
message: str,
|
|
level: str = "warning",
|
|
presentation: str = "modal",
|
|
sound: str = "warning",
|
|
vibrate: bool = True,
|
|
wake_screen: bool = False,
|
|
tts_text: str | None = None,
|
|
details_code: str | None = None,
|
|
custom_html: str | None = None,
|
|
interaction: dict[str, Any] | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Trigger a native alert overlay (toast | modal | fullscreen_alarm) with optional Preset-First interactive buttons."""
|
|
alert_id = f"alert_{uuid.uuid4().hex[:10]}"
|
|
if interaction and "interaction_id" not in interaction:
|
|
interaction = {**interaction, "interaction_id": f"int_{uuid.uuid4().hex[:10]}"}
|
|
payload = {
|
|
"alert_id": alert_id,
|
|
"title": title,
|
|
"message": message,
|
|
"level": level,
|
|
"presentation": presentation,
|
|
"sound": sound,
|
|
"vibrate": vibrate,
|
|
"wake_screen": wake_screen or (presentation == "fullscreen_alarm"),
|
|
"tts_text": tts_text,
|
|
"details_code": details_code,
|
|
"custom_html": custom_html,
|
|
"interaction": interaction,
|
|
}
|
|
sent = await bridge.send_frame(device_id, "alert.trigger", payload)
|
|
db.add_audit("alert", device_id, f"[{level}/{presentation}] {title}", payload)
|
|
return {
|
|
"ok": sent,
|
|
"alert_id": alert_id,
|
|
"interaction_id": (interaction or {}).get("interaction_id"),
|
|
"delivered": sent,
|
|
}
|
|
|
|
@mcp.tool()
|
|
async def dismiss_alert(device_id: str, alert_id: str | None = None) -> dict[str, Any]:
|
|
"""Dismiss an active alert (or all alerts if alert_id is omitted) on the device."""
|
|
sent = await bridge.send_frame(device_id, "alert.dismiss", {"alert_id": alert_id})
|
|
return {"ok": sent, "alert_id": alert_id}
|
|
|
|
@mcp.tool()
|
|
async def render_page(
|
|
device_id: str,
|
|
html: str,
|
|
mode: str = "full",
|
|
title: str = "",
|
|
data_context: dict[str, Any] | None = None,
|
|
wait_validation_sec: int = 15,
|
|
) -> dict[str, Any]:
|
|
"""Render dynamic HTML/Vue layout on device with pre-render sandbox validation and end-side Repair AI self-healing."""
|
|
return await bridge.send_render_and_wait(
|
|
device_id=device_id,
|
|
html=html,
|
|
mode=mode,
|
|
title=title,
|
|
data_context=data_context,
|
|
wait_validation_sec=wait_validation_sec,
|
|
)
|
|
|
|
@mcp.tool()
|
|
async def rollback_page(device_id: str, snapshot_id: str | None = None) -> dict[str, Any]:
|
|
"""Roll back the device WebView to a previous healthy snapshot, or pass snapshot_id='home' to restore built-in Home screen."""
|
|
if snapshot_id == "home":
|
|
sent = await bridge.send_frame(device_id, "render.home", {})
|
|
db.add_audit("rollback", device_id, "Restored built-in Home screen")
|
|
return {"ok": sent, "snapshot_id": "home"}
|
|
snap = db.get_snapshot(snapshot_id) if snapshot_id else db.get_previous_healthy_snapshot(device_id)
|
|
if not snap:
|
|
return {"ok": False, "error": "No healthy snapshot available for rollback."}
|
|
sent = await bridge.send_frame(
|
|
device_id,
|
|
"render.rollback",
|
|
{"snapshot_id": snap["snapshot_id"], "html": snap["html"], "title": snap.get("title", "")},
|
|
)
|
|
db.add_audit("rollback", device_id, f"Rolled back to {snap['snapshot_id']}")
|
|
return {"ok": sent, "snapshot_id": snap["snapshot_id"]}
|
|
|
|
@mcp.tool()
|
|
async def reply_clarification(
|
|
device_id: str,
|
|
task_id: str,
|
|
answers: dict[str, Any],
|
|
updated_data: dict[str, Any] | None = None,
|
|
updated_html: str | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Reply to a data clarification question raised by the device's end-side Repair AI."""
|
|
payload = {
|
|
"task_id": task_id,
|
|
"answers": answers,
|
|
"updated_data": updated_data or {},
|
|
"updated_html": updated_html,
|
|
}
|
|
sent = await bridge.send_frame(device_id, "clarification.answer", payload)
|
|
db.add_audit("clarification_answer", device_id, f"Upstream answered clarification for {task_id}", payload)
|
|
return {"ok": sent, "task_id": task_id}
|
|
|
|
@mcp.tool()
|
|
def get_pending_events(device_id: str | None = None, limit: int = 20) -> dict[str, Any]:
|
|
"""Poll pending reverse events (user interaction replies & end-side AI data clarification questions)."""
|
|
events = db.list_pending_events(device_id=device_id, limit=limit)
|
|
return {"count": len(events), "events": events}
|
|
|
|
@mcp.tool()
|
|
def ack_events(event_ids: list[str]) -> dict[str, Any]:
|
|
"""Acknowledge reverse events after processing them."""
|
|
acked = db.ack_events(event_ids)
|
|
return {"ok": True, "acked_count": acked}
|
|
|
|
@mcp.tool()
|
|
async def lan_adb_action(
|
|
device_id: str,
|
|
action: str,
|
|
params: dict[str, Any] | None = None,
|
|
) -> dict[str, Any]:
|
|
"""Execute a LAN-ONLY developer debug / ADB action on an authorized device (tap, swipe, text, keyevent, screencap, launch_app, screen_wake, screen_sleep, status, dumpsys_summary)."""
|
|
if not mcp_request_is_lan.get():
|
|
return {
|
|
"ok": False,
|
|
"error": "Forbidden: lan_adb_action is strictly restricted to private LAN MCP callers.",
|
|
}
|
|
try:
|
|
return await adb_controller.execute_action(device_id, action, params)
|
|
except Exception as exc:
|
|
detail = getattr(exc, "detail", str(exc))
|
|
return {"ok": False, "error": detail}
|
|
|
|
return mcp
|