diff --git a/AGENTS.md b/AGENTS.md index 886084a..d92e9b9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -9,6 +9,7 @@ This project is a high-performance web-based Keybinding Management Suite designe 3. **Intelligent Conflict Detection**: Distinguishes between harmless overlaps in mutually exclusive flight/ground modes and fatal collisions using temporal state machine analysis (`multiTap`, `activationMode`, Master Modes SCM/NAV). 4. **Hardware Listening**: HTML5 Gamepad API listener to detect physical button/axis presses in real time and jump straight to the relevant binding in the UI. 5. **Native Go Extraction Daemon (`sc-daemon`)**: Direct Zip64 central directory streamer and CryEngine cipher decryptor to extract default bindings and localization strings directly from Star Citizen's 90GB+ `Data.p4k` archive without high RAM consumption. +6. **WebMCP Browser AI Agent Integration (`useWebMCP.ts`)**: Exposes 9 structured, JSON-Schema-typed tools on `document.modelContext` / `navigator.modelContext` so browser-embedded AI agents can audit conflicts, search the 50-map catalog, find unused stick buttons, re-index `jsX_` devices, and modify bindings client-side without fragile DOM scraping. Detailed specifications, mathematical formulas, and cipher routines are documented in [docs/ARCHITECTURE_BLUEPRINT.md](docs/ARCHITECTURE_BLUEPRINT.md). @@ -47,7 +48,7 @@ sc-mapping/ │ └── src/ │ ├── components/ # DeviceRack.tsx, ReferralCodeCard.tsx, MonetizationSlot.tsx, etc. │ ├── data/ # referralCodes.ts (community supporter referral pool) -│ ├── hooks/ # useGamepadListener.ts (HTML5 Gamepad API hook) +│ ├── hooks/ # useGamepadListener.ts (HTML5 Gamepad API), useWebMCP.ts (W3C WebMCP tools) │ └── App.tsx # Main workspace UI ├── e2e/ # Playwright End-to-End browser UX test suite │ └── app-workflow.spec.ts # Complete user journey tests (presets, matrix, modals, XML export) diff --git a/README.md b/README.md index eb8e87f..f906079 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ Configuring complex HOTAS, HOSAS, pedals, and button boxes in Star Citizen's nat - **Intelligent 4-Tier Conflict Diagnostics**: Differentiates harmless overlaps in mutually exclusive flight/ground modes from lethal collisions. Analyzes temporal mechanics (`multiTap`, `press`, `hold`, Master Modes SCM/NAV) and warns you before accidental inputs trigger fatal actions like Self-Destruct, Eject, or Jettison Cargo. - **Live Hardware Listening Mode**: Powered by the HTML5 Gamepad API. Press any physical button or deflect any analog stick or pedal on your desk, and the UI immediately detects the input and filters to the corresponding binding. - **Lossless CryEngine XML Round-Tripping**: Never discards device `` blocks (axis inversions, sensitivity curves, product GUIDs) and preserves concurrent secondary `` inputs alongside primary `` overrides. +- **WebMCP Browser AI Agent Ready (`document.modelContext`)**: Exposes 9 structured client-side tools (`get_profile_summary`, `audit_conflicts`, `search_bindings_and_catalog`, `find_unused_joystick_inputs`, `set_action_binding`, `auto_fix_obsolete_conflicts`, `remap_joystick_instances`, `configure_joystick_options`, and `workspace_control`) so W3C WebMCP-compatible browser AI assistants can audit, search, and configure flight profiles deterministically in memory. --- diff --git a/apps/web/src/App.tsx b/apps/web/src/App.tsx index 33c92a8..b518f67 100644 --- a/apps/web/src/App.tsx +++ b/apps/web/src/App.tsx @@ -29,6 +29,7 @@ import { } from './components/MonetizationSlot'; import { ReferralCodeCard } from './components/ReferralCodeCard'; import { useGamepadListener } from './hooks/useGamepadListener'; +import { useWebMCP } from './hooks/useWebMCP'; import { Upload, Download, @@ -391,6 +392,52 @@ export const App: React.FC = () => { } }; + // WebMCP Browser AI Agent Integration (document.modelContext / navigator.modelContext) + const { + registeredTools: webMcpTools, + isNativeSupport: isWebMcpNative, + lastToolCall: lastWebMcpCall, + executeRegisteredTool: executeWebMcpTool + } = useWebMCP({ + doc, + activePreset, + gameVersion, + gameBranch, + gameBuildDate, + suiteVersion, + hardwareMapping, + conflictReport, + deviceScope, + activeTab, + searchQuery, + onSetActiveTab: setActiveTab, + onSetSearchQuery: setSearchQuery, + onSetDeviceScope: setDeviceScope, + onSetHardwareMapping: setHardwareMapping, + onApplyDeviceOptions: handleApplyDeviceOptions, + onSaveActionInputs: handleSaveActionInputs, + onAutoFixConflict: handleAutoFix, + onLoadSamplePreset: handleLoadSamplePreset + }); + + const [selectedWebMcpTool, setSelectedWebMcpTool] = useState('get_profile_summary'); + const [webMcpTestOutput, setWebMcpTestOutput] = useState(null); + + const handleRunWebMcpDiagnostic = async (toolName: string) => { + try { + const sampleInputs: Record> = { + get_profile_summary: {}, + audit_conflicts: { deviceScope: 'js', severity: 'all', limit: 10 }, + search_bindings_and_catalog: { query: 'eject', limit: 5 }, + find_unused_joystick_inputs: { deviceInstance: 1, maxButtons: 16 } + }; + const result = await executeWebMcpTool(toolName, sampleInputs[toolName] || {}); + setWebMcpTestOutput(JSON.stringify(result, null, 2)); + } catch (err: any) { + setWebMcpTestOutput(JSON.stringify({ error: err.message }, null, 2)); + } + }; + return (
{/* Pilot Safety & XML Backup Advisory Banner */} @@ -440,6 +487,17 @@ export const App: React.FC = () => { • Build: {gameBuildDate} + • +
@@ -886,6 +944,59 @@ git commit -am "chore(catalog): update actions & tokens for Star Citizen 4.x"`} "Preview Bundled LIVE Data" tests the static catalog committed to git. "Local Dev Sync" is strictly an optional diagnostic when testing the Go daemon before writing files.

+ + {/* WebMCP Browser AI Agent Bridge Diagnostic Panel */} +
+
+ + + WebMCP AI Agent Bridge (document.modelContext) + + + {webMcpTools.length} Tools Ready ({isWebMcpNative ? 'Native W3C' : 'Polyfill Active'}) + +
+

+ Exposes structured client-side tools so browser-embedded AI agents can audit conflicts, search the 50-map catalog, re-index jsX_ sticks, and edit bindings without DOM scraping. +

+
+ + +
+ {lastWebMcpCall && ( +
+ Last Invocation: {lastWebMcpCall.toolName} ({lastWebMcpCall.status}) +
+ )} + {webMcpTestOutput && ( +
+                    {webMcpTestOutput}
+                  
+ )} +
diff --git a/apps/web/src/hooks/useWebMCP.test.tsx b/apps/web/src/hooks/useWebMCP.test.tsx new file mode 100644 index 0000000..ec12a78 --- /dev/null +++ b/apps/web/src/hooks/useWebMCP.test.tsx @@ -0,0 +1,417 @@ +import React from 'react'; +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen, fireEvent, waitFor, renderHook, act } from '@testing-library/react'; +import { ActionMapsParser } from '@sc-mapping/parser'; +import { ConflictResolver } from '@sc-mapping/resolver'; +import type { ActionMapsDocument, BindingInput, ConflictDetails, JoystickDeviceOption } from '@sc-mapping/shared-types'; +import { useWebMCP, ensureModelContextHost, type UseWebMCPOptions } from './useWebMCP'; +import { App } from '../App'; + +const TEST_XML = ` + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +`; + +function createMockOptions(docOverride?: ActionMapsDocument | null): { + options: UseWebMCPOptions; + spies: { + onSetActiveTab: ReturnType; + onSetSearchQuery: ReturnType; + onSetDeviceScope: ReturnType; + onSetHardwareMapping: ReturnType; + onApplyDeviceOptions: ReturnType; + onSaveActionInputs: ReturnType; + onAutoFixConflict: ReturnType; + onLoadSamplePreset: ReturnType; + }; +} { + const doc = docOverride === undefined ? ActionMapsParser.parseXML(TEST_XML) : docOverride; + const conflictReport = doc ? ConflictResolver.auditDocument(doc, { deviceFilter: 'js' }) : null; + const hardwareMapping = new Map([ + [1, 1], + [2, 2] + ]); + + const spies = { + onSetActiveTab: vi.fn(), + onSetSearchQuery: vi.fn(), + onSetDeviceScope: vi.fn(), + onSetHardwareMapping: vi.fn(), + onApplyDeviceOptions: vi.fn(), + onSaveActionInputs: vi.fn(), + onAutoFixConflict: vi.fn(), + onLoadSamplePreset: vi.fn().mockResolvedValue(undefined) + }; + + return { + options: { + doc, + activePreset: 'Test Preset', + gameVersion: '4.10.200.58746', + gameBranch: 'sc-alpha-4.10.3', + gameBuildDate: '2026-11-12', + suiteVersion: '1.0.0', + hardwareMapping, + conflictReport, + deviceScope: 'js', + activeTab: 'matrix', + searchQuery: '', + ...spies + }, + spies + }; +} + +describe('WebMCP Browser AI Agent Integration (useWebMCP)', () => { + beforeEach(() => { + delete (document as any).modelContext; + delete (navigator as any).modelContext; + }); + + it('initializes document.modelContext and navigator.modelContext polyfill container and validates tool registration', async () => { + const host = ensureModelContextHost(); + expect(document.modelContext).toBeDefined(); + expect(navigator.modelContext).toBeDefined(); + expect(host.__isPolyfill).toBe(true); + + // Calling ensureModelContextHost a second time returns the existing host + const hostAgain = ensureModelContextHost(); + expect(hostAgain).toBe(host); + + // Invalid tool throws + await expect(host.registerTool({ name: '', description: 'bad', inputSchema: { type: 'object', properties: {} }, execute: null as any })).rejects.toThrow( + /Invalid WebMCP tool definition/i + ); + + // Executing unknown tool throws + await expect(host.executeTool('non_existent_tool')).rejects.toThrow(/WebMCP tool not found/i); + + // provideContext replaces registered tools + await host.provideContext!({ + tools: [ + { + name: 'ping_tool', + description: 'Ping test', + inputSchema: { type: 'object', properties: {} }, + execute: () => ({ pong: true }) + } + ] + }); + expect(host.getTools().map(t => t.name)).toEqual(['ping_tool']); + expect(await host.executeTool('ping_tool')).toEqual({ pong: true }); + }); + + it('registers all 9 Star Citizen keybinding tools and executes get_profile_summary', async () => { + const { options } = createMockOptions(); + const { result, unmount } = renderHook(() => useWebMCP(options)); + + expect(result.current.registeredTools).toHaveLength(9); + const toolNames = result.current.registeredTools.map(t => t.name); + expect(toolNames).toEqual([ + 'get_profile_summary', + 'audit_conflicts', + 'search_bindings_and_catalog', + 'find_unused_joystick_inputs', + 'set_action_binding', + 'auto_fix_obsolete_conflicts', + 'remap_joystick_instances', + 'configure_joystick_options', + 'workspace_control' + ]); + + let summary: any; + await act(async () => { + summary = await result.current.executeRegisteredTool('get_profile_summary'); + }); + + expect(summary.profileLoaded).toBe(true); + expect(summary.profileName).toBe('webmcp_test_profile'); + expect(summary.targetGame.branch).toBe('sc-alpha-4.10.3'); + expect(summary.joystickDevices).toHaveLength(2); + expect(summary.joystickDevices[0].productName).toBe('VKBsim Gladiator EVO R'); + expect(summary.conflictSummary.totalConflicts).toBeGreaterThan(0); + expect(result.current.lastToolCall?.toolName).toBe('get_profile_summary'); + expect(result.current.lastToolCall?.status).toBe('ok'); + + unmount(); + expect(document.modelContext?.getTools()).toHaveLength(0); + }); + + it('executes audit_conflicts with severity and scope filters and handles null document', async () => { + const { options } = createMockOptions(); + const { result } = renderHook(() => useWebMCP(options)); + + let allAudit: any; + await act(async () => { + allAudit = await result.current.executeRegisteredTool('audit_conflicts', { + deviceScope: 'js', + severity: 'all', + limit: 10 + }); + }); + expect(allAudit.counts.total).toBeGreaterThan(0); + expect(allAudit.conflicts.length).toBeGreaterThan(0); + + let fatalOnly: any; + await act(async () => { + fatalOnly = await result.current.executeRegisteredTool('audit_conflicts', { + deviceScope: 'js', + severity: 'Fatal', + limit: 5 + }); + }); + for (const c of fatalOnly.conflicts) { + expect(c.severity).toBe('Fatal'); + } + + // Null doc case + const { options: nullOpts } = createMockOptions(null); + const { result: nullResult } = renderHook(() => useWebMCP(nullOpts)); + let emptyAudit: any; + await act(async () => { + emptyAudit = await nullResult.current.executeRegisteredTool('audit_conflicts', {}); + }); + expect(emptyAudit.error).toMatch(/No keybinding profile/i); + }); + + it('searches catalog and custom bindings via search_bindings_and_catalog', async () => { + const { options } = createMockOptions(); + const { result } = renderHook(() => useWebMCP(options)); + + // Search for bound action by query + let ejectSearch: any; + await act(async () => { + ejectSearch = await result.current.executeRegisteredTool('search_bindings_and_catalog', { + query: 'v_eject', + bindingState: 'bound', + limit: 10 + }); + }); + expect(ejectSearch.totalReturned).toBeGreaterThanOrEqual(1); + expect(ejectSearch.results[0].actionName).toBe('v_eject'); + expect(ejectSearch.results[0].isBound).toBe(true); + + // Search for custom action not in canonical catalog + let customSearch: any; + await act(async () => { + customSearch = await result.current.executeRegisteredTool('search_bindings_and_catalog', { + query: 'v_custom_noncatalog_action', + mapName: 'spaceship_movement', + bindingState: 'bound' + }); + }); + expect(customSearch.results.some((r: any) => r.actionName === 'v_custom_noncatalog_action')).toBe(true); + + // Search unbound actions with SCM filter + let unboundScm: any; + await act(async () => { + unboundScm = await result.current.executeRegisteredTool('search_bindings_and_catalog', { + masterFlightMode: 'SCM', + bindingState: 'unbound', + limit: 5 + }); + }); + expect(unboundScm.results.length).toBeLessThanOrEqual(5); + for (const item of unboundScm.results) { + expect(item.isBound).toBe(false); + expect(item.masterFlightMode).toBe('SCM'); + } + }); + + it('identifies unused and used buttons on a joystick via find_unused_joystick_inputs', async () => { + const { options } = createMockOptions(); + const { result } = renderHook(() => useWebMCP(options)); + + let stickReport: any; + await act(async () => { + stickReport = await result.current.executeRegisteredTool('find_unused_joystick_inputs', { + deviceInstance: 1, + maxButtons: 8, + mapName: 'spaceship_movement' + }); + }); + + expect(stickReport.devicePrefix).toBe('js1'); + expect(stickReport.usedButtons.some((u: any) => u.input === 'js1_button4')).toBe(true); + expect(stickReport.usedButtons.some((u: any) => u.input === 'js1_button5')).toBe(true); + expect(stickReport.unusedButtons).toContain('js1_button1'); + expect(stickReport.unusedButtons).toContain('js1_button2'); + }); + + it('updates bindings, enforces unbind invariant, and checks conflicts via set_action_binding', async () => { + const { options, spies } = createMockOptions(); + const { result } = renderHook(() => useWebMCP(options)); + + // 1. Bind action to a colliding input (js1_button4 is used by v_boost and v_space_brake) + let bindRes: any; + await act(async () => { + bindRes = await result.current.executeRegisteredTool('set_action_binding', { + mapName: 'spaceship_movement', + actionName: 'v_yaw', + inputs: [ + { input: 'js1_button4', activationMode: 'press' }, + { input: 'lalt+js2_button9', activationMode: 'hold', multiTap: 2 } + ] + }); + }); + + expect(spies.onSaveActionInputs).toHaveBeenCalledTimes(1); + expect(bindRes.status).toBe('updated'); + expect(bindRes.unbindEmittedOnExport).toBe(false); + expect(bindRes.inputs).toHaveLength(2); + expect(bindRes.inputs[0].bindType).toBe('rebind'); + expect(bindRes.inputs[1].bindType).toBe('addbind'); + expect(bindRes.inputs[1].modifiers).toEqual(['lalt']); + expect(bindRes.conflictsWithNewBinding.length).toBeGreaterThan(0); + + // 2. Clear action inputs (Unbind invariant -> empty array triggers explicit on export) + let clearRes: any; + await act(async () => { + clearRes = await result.current.executeRegisteredTool('set_action_binding', { + mapName: 'spaceship_movement', + actionName: 'v_yaw', + inputs: [] + }); + }); + expect(clearRes.unbindEmittedOnExport).toBe(true); + expect(clearRes.inputs).toEqual([]); + + // 3. Missing required parameters throws error and records error status + await act(async () => { + await expect( + result.current.executeRegisteredTool('set_action_binding', { + mapName: '', + actionName: '', + inputs: [] + }) + ).rejects.toThrow(/Both mapName and actionName are required/i); + }); + }); + + it('auto-fixes obsolete conflicts, remaps joysticks, configures device options, and controls workspace', async () => { + const { options, spies } = createMockOptions(); + const { result } = renderHook(() => useWebMCP(options)); + + // 1. Auto-fix obsolete conflicts (v_ifcs_toggle_cruise_control colliding with v_master_mode_cycle) + let fixRes: any; + await act(async () => { + fixRes = await result.current.executeRegisteredTool('auto_fix_obsolete_conflicts', {}); + }); + expect(fixRes.fixedCount).toBeGreaterThanOrEqual(1); + expect(spies.onAutoFixConflict).toHaveBeenCalled(); + + // 2. Remap joystick instances (js1 -> js2, js2 -> js1) + let remapRes: any; + await act(async () => { + remapRes = await result.current.executeRegisteredTool('remap_joystick_instances', { + mapping: { js1: 2, '2': 1 } + }); + }); + expect(remapRes.status).toBe('remapped'); + expect(remapRes.hardwareMapping).toEqual({ js1: 'js2', js2: 'js1' }); + expect(spies.onSetHardwareMapping).toHaveBeenCalled(); + + // Reset joystick instances + let resetRes: any; + await act(async () => { + resetRes = await result.current.executeRegisteredTool('remap_joystick_instances', { + reset: true + }); + }); + expect(resetRes.status).toBe('reset'); + expect(resetRes.hardwareMapping).toEqual({ js1: 'js1', js2: 'js2' }); + + // 3. Configure joystick options (inversions, deadzones, sensitivities) + let optRes: any; + await act(async () => { + optRes = await result.current.executeRegisteredTool('configure_joystick_options', { + instance: 2, + productName: 'VKBsim Gladiator EVO L OTA', + inversions: { flight_move_strafe_longitudinal: true }, + deadzones: { x: 0.04, y: 0.04 }, + sensitivities: { x: 1.15 } + }); + }); + expect(optRes.status).toBe('configured'); + expect(optRes.device.productName).toBe('VKBsim Gladiator EVO L OTA'); + expect(spies.onApplyDeviceOptions).toHaveBeenCalledWith( + expect.objectContaining({ + instance: 2, + inversions: { flight_move_strafe_longitudinal: true } + }) + ); + + // 4. Workspace control: switch tab, filter search, load preset, and export XML + let wsRes: any; + await act(async () => { + wsRes = await result.current.executeRegisteredTool('workspace_control', { + activeTab: 'conflicts', + searchQuery: 'v_pitch', + deviceScope: 'all', + loadPreset: 'vkb_omni', + exportXml: true + }); + }); + expect(spies.onLoadSamplePreset).toHaveBeenCalledWith( + 'vkb_evo_hosas_omni.xml', + 'Dual VKB (Right + Omni Left)' + ); + expect(spies.onSetActiveTab).toHaveBeenCalledWith('conflicts'); + expect(spies.onSetSearchQuery).toHaveBeenCalledWith('v_pitch'); + expect(spies.onSetDeviceScope).toHaveBeenCalledWith('all'); + expect(wsRes.exportedXml).toContain(' { + render(); + + const headerBadge = screen.getByTestId('webmcp-header-badge'); + expect(headerBadge).toBeTruthy(); + expect(headerBadge.textContent).toContain('WebMCP: 9 AI Tools'); + + fireEvent.click(headerBadge); + + const bridgePanel = await screen.findByTestId('webmcp-bridge-panel'); + expect(bridgePanel).toBeTruthy(); + expect(bridgePanel.textContent).toContain('9 Tools Ready'); + + const runBtn = screen.getByRole('button', { name: /Run Tool/i }); + fireEvent.click(runBtn); + + await waitFor(() => { + const output = screen.getByTestId('webmcp-test-output'); + expect(output.textContent).toContain('"profileName": "dual_vkb_evo_scm"'); + }); + }); +}); diff --git a/apps/web/src/hooks/useWebMCP.ts b/apps/web/src/hooks/useWebMCP.ts new file mode 100644 index 0000000..aa84d0c --- /dev/null +++ b/apps/web/src/hooks/useWebMCP.ts @@ -0,0 +1,1100 @@ +import { useEffect, useRef, useState, useCallback } from 'react'; +import { + ActionMapsParser, + ActionMapsExporter, + CatalogManager +} from '@sc-mapping/parser'; +import { + ConflictResolver, + ConflictSeverity +} from '@sc-mapping/resolver'; +import type { + ActionMapsDocument, + ActionBinding, + BindingInput, + ConflictDetails, + ConflictReport, + JoystickDeviceOption, + ActivationMode, + BindType +} from '@sc-mapping/shared-types'; + +export interface WebMCPJsonSchema { + type: 'object'; + properties: Record; + }>; + required?: string[]; + additionalProperties?: boolean; +} + +export interface WebMCPToolDefinition { + name: string; + title?: string; + description: string; + inputSchema: WebMCPJsonSchema; + readOnlyHint?: boolean; + execute: (input: TInput) => Promise | TOutput; +} + +export interface ModelContextContainer { + registerTool: (tool: WebMCPToolDefinition, options?: Record) => Promise | void; + unregisterTool?: (name: string) => Promise | void; + getTools: () => WebMCPToolDefinition[]; + executeTool: (name: string, input?: Record) => Promise; + provideContext?: (context: { tools: WebMCPToolDefinition[] }) => Promise | void; + __isPolyfill?: boolean; +} + +declare global { + interface Document { + modelContext?: ModelContextContainer; + } + interface Navigator { + modelContext?: ModelContextContainer; + } +} + +export interface UseWebMCPOptions { + doc: ActionMapsDocument | null; + activePreset: string; + gameVersion: string; + gameBranch: string; + gameBuildDate: string; + suiteVersion: string; + hardwareMapping: Map; + conflictReport: ConflictReport | null; + deviceScope: string; + activeTab: 'matrix' | 'inspector' | 'conflicts'; + searchQuery: string; + onSetActiveTab: (tab: 'matrix' | 'inspector' | 'conflicts') => void; + onSetSearchQuery: (query: string) => void; + onSetDeviceScope: (scope: string) => void; + onSetHardwareMapping: (mapping: Map) => void; + onApplyDeviceOptions: (device: JoystickDeviceOption) => void; + onSaveActionInputs: (mapName: string, actionName: string, inputs: BindingInput[], label?: string) => void; + onAutoFixConflict: (conflict: ConflictDetails) => void; + onLoadSamplePreset: (fileName: string, presetName: string) => Promise; +} + +/** + * Ensures `document.modelContext` and `navigator.modelContext` exist with a unified + * registry and execution bridge for W3C WebMCP browser AI agents and E2E testing. + */ +export function ensureModelContextHost(): ModelContextContainer { + const toolRegistry = new Map>(); + + const existingDocCtx = typeof document !== 'undefined' ? document.modelContext : undefined; + const existingNavCtx = typeof navigator !== 'undefined' ? navigator.modelContext : undefined; + + if (existingDocCtx && typeof existingDocCtx.getTools === 'function' && typeof existingDocCtx.executeTool === 'function') { + return existingDocCtx; + } + + const wrapForNativeMcp = (tool: WebMCPToolDefinition): WebMCPToolDefinition => ({ + ...tool, + async execute(input: any) { + const res = await tool.execute(input); + if (res && typeof res === 'object' && 'content' in (res as Record)) { + return res; + } + return { + ...(typeof res === 'object' && res !== null ? res : { result: res }), + content: [ + { + type: 'text', + text: JSON.stringify(res, null, 2) + } + ] + }; + } + }); + + const container: ModelContextContainer = { + __isPolyfill: !existingDocCtx && !existingNavCtx, + async registerTool(tool: WebMCPToolDefinition, options?: Record) { + if (!tool || !tool.name || typeof tool.execute !== 'function') { + throw new Error('Invalid WebMCP tool definition: name and execute() are required'); + } + toolRegistry.set(tool.name, tool); + const nativeTool = wrapForNativeMcp(tool); + if (existingDocCtx && existingDocCtx !== container && typeof existingDocCtx.registerTool === 'function') { + try { + await existingDocCtx.registerTool(nativeTool, options); + } catch { + // Ignore duplicate native registration errors on hot-reload + } + } + if (existingNavCtx && existingNavCtx !== container && typeof existingNavCtx.registerTool === 'function') { + try { + await existingNavCtx.registerTool(nativeTool, options); + } catch { + // Ignore duplicate native registration errors on hot-reload + } + } + }, + async unregisterTool(name: string) { + toolRegistry.delete(name); + if (existingDocCtx && existingDocCtx !== container && typeof existingDocCtx.unregisterTool === 'function') { + try { + await existingDocCtx.unregisterTool(name); + } catch { + // Ignore if already unregistered + } + } + if (existingNavCtx && existingNavCtx !== container && typeof existingNavCtx.unregisterTool === 'function') { + try { + await existingNavCtx.unregisterTool(name); + } catch { + // Ignore if already unregistered + } + } + }, + getTools() { + return Array.from(toolRegistry.values()); + }, + async executeTool(name: string, input: Record = {}) { + const tool = toolRegistry.get(name); + if (!tool) { + throw new Error(`WebMCP tool not found: '${name}'`); + } + return await tool.execute(input || {}); + }, + async provideContext(ctx: { tools: WebMCPToolDefinition[] }) { + toolRegistry.clear(); + for (const tool of ctx.tools || []) { + await container.registerTool(tool); + } + } + }; + + if (typeof document !== 'undefined') { + try { + document.modelContext = container; + } catch { + Object.defineProperty(document, 'modelContext', { + value: container, + configurable: true, + writable: true + }); + } + } + + if (typeof navigator !== 'undefined') { + try { + if (!navigator.modelContext) { + Object.defineProperty(navigator, 'modelContext', { + value: container, + configurable: true, + writable: true + }); + } + } catch { + // Ignore read-only navigator environments + } + } + + return container; +} + +const severityLabel = (sev: ConflictSeverity): string => { + switch (sev) { + case ConflictSeverity.Fatal: + return 'Fatal'; + case ConflictSeverity.Warning: + return 'Warning'; + case ConflictSeverity.Redundant: + return 'Redundant'; + default: + return 'None'; + } +}; + +export function useWebMCP(options: UseWebMCPOptions) { + const stateRef = useRef(options); + stateRef.current = options; + + const [registeredTools, setRegisteredTools] = useState([]); + const [isNativeSupport, setIsNativeSupport] = useState(false); + const [lastToolCall, setLastToolCall] = useState<{ + toolName: string; + timestamp: string; + status: 'ok' | 'error'; + } | null>(null); + + const buildTools = useCallback((): WebMCPToolDefinition[] => { + const wrapExecute = ( + toolName: string, + fn: (input: TIn) => Promise | TOut + ) => { + return async (input: TIn): Promise => { + try { + const result = await fn(input); + setLastToolCall({ + toolName, + timestamp: new Date().toISOString(), + status: 'ok' + }); + return result; + } catch (err) { + setLastToolCall({ + toolName, + timestamp: new Date().toISOString(), + status: 'error' + }); + throw err; + } + }; + }; + + const tools: WebMCPToolDefinition[] = [ + { + name: 'get_profile_summary', + title: 'Get Star Citizen Keybinding Profile Summary', + description: + 'Returns telemetry for the currently loaded Star Citizen keybinding profile, including target game version, joystick devices, instance remapping table, action counts, and conflict summary.', + readOnlyHint: true, + inputSchema: { + type: 'object', + properties: {}, + additionalProperties: false + }, + execute: wrapExecute('get_profile_summary', () => { + const s = stateRef.current; + const doc = s.doc; + const joysticks = doc + ? doc.devices.filter((d): d is JoystickDeviceOption => d.type === 'joystick') + : []; + + let totalActions = 0; + let boundActions = 0; + if (doc) { + for (const mapGroup of Object.values(doc.actionMaps)) { + for (const act of Object.values(mapGroup.actions)) { + totalActions++; + if (act.inputs.some(inp => inp.input.trim() !== '')) { + boundActions++; + } + } + } + } + + const remapEntries: Record = {}; + s.hardwareMapping.forEach((targetInst, sourceInst) => { + remapEntries[`js${sourceInst}`] = `js${targetInst}`; + }); + + return { + profileLoaded: Boolean(doc), + profileName: doc?.profileName ?? null, + activePreset: s.activePreset, + suiteVersion: s.suiteVersion, + targetGame: { + branch: s.gameBranch, + version: s.gameVersion, + buildDate: s.gameBuildDate + }, + uiState: { + activeTab: s.activeTab, + searchQuery: s.searchQuery, + deviceScope: s.deviceScope + }, + metrics: { + actionMapCount: doc ? Object.keys(doc.actionMaps).length : 0, + totalActionsInProfile: totalActions, + boundActionsCount: boundActions + }, + joystickDevices: joysticks.map(j => ({ + instance: j.instance, + prefix: `js${j.instance}`, + exportPrefix: `js${s.hardwareMapping.get(j.instance) ?? j.instance}`, + productName: j.productName, + productGuid: j.productGuid ?? null, + inversions: j.inversions, + deadzones: j.deadzones ?? {}, + sensitivities: j.sensitivities ?? {} + })), + hardwareRemapping: remapEntries, + conflictSummary: { + deviceScope: s.deviceScope, + hasFatalConflicts: s.conflictReport?.hasFatalConflicts ?? false, + totalConflicts: s.conflictReport?.conflicts.length ?? 0, + fatalCount: s.conflictReport?.fatalCount ?? 0, + warningCount: s.conflictReport?.warningCount ?? 0, + redundantCount: s.conflictReport?.redundantCount ?? 0 + } + }; + }) + }, + { + name: 'audit_conflicts', + title: 'Audit Keybinding Conflicts', + description: + 'Runs the Star Citizen Temporal & Contextual Conflict Resolver on the active profile. Distinguishes between mutually exclusive domains/Master Modes (SCM vs NAV) and real Fatal collisions, Warning latencies, or Redundant/Obsolete bindings.', + readOnlyHint: true, + inputSchema: { + type: 'object', + properties: { + deviceScope: { + type: 'string', + description: "Hardware filter scope: 'js' (joysticks only), 'kb' (keyboard/mouse), or 'all'.", + enum: ['js', 'kb', 'all'] + }, + severity: { + type: 'string', + description: "Filter returned conflicts by severity tier: 'Fatal', 'Warning', 'Redundant', or 'all'.", + enum: ['Fatal', 'Warning', 'Redundant', 'all'] + }, + limit: { + type: 'number', + description: 'Maximum number of conflict records to return (default 50).' + } + }, + additionalProperties: false + }, + execute: wrapExecute('audit_conflicts', (input: { + deviceScope?: string; + severity?: string; + limit?: number; + }) => { + const s = stateRef.current; + if (!s.doc) { + return { error: 'No keybinding profile is currently loaded.' }; + } + + const scope = input.deviceScope || s.deviceScope || 'js'; + const report = ConflictResolver.auditDocument(s.doc, { deviceFilter: scope }); + const maxItems = typeof input.limit === 'number' && input.limit > 0 ? input.limit : 50; + + const filtered = report.conflicts.filter(c => { + if (!input.severity || input.severity === 'all') return true; + return severityLabel(c.severity).toLowerCase() === input.severity.toLowerCase(); + }); + + return { + deviceScope: scope, + hasFatalConflicts: report.hasFatalConflicts, + counts: { + total: report.conflicts.length, + fatal: report.fatalCount, + warning: report.warningCount, + redundant: report.redundantCount, + returned: Math.min(filtered.length, maxItems) + }, + conflicts: filtered.slice(0, maxItems).map(c => ({ + severity: severityLabel(c.severity), + conflictType: c.conflictType ?? 'collision', + sharedInput: c.sharedInput, + sourceContext: c.sourceContext, + sourceAction: c.sourceAction, + targetContext: c.targetContext, + targetAction: c.targetAction, + reason: c.reason, + recommendation: c.recommendation ?? null, + deprecatedAction: c.deprecatedAction ?? null + })) + }; + }) + }, + { + name: 'search_bindings_and_catalog', + title: 'Search Keybindings & Star Citizen Action Catalog', + description: + 'Searches across all 50 Star Citizen action maps in both the loaded XML profile and the canonical Data.p4k catalog by keyword, action name, physical input (e.g. js1_button4), actionMap, or Master Flight Mode (SCM/NAV).', + readOnlyHint: true, + inputSchema: { + type: 'object', + properties: { + query: { + type: 'string', + description: 'Search term matching action name, localized label, description, or input string (e.g. "eject", "v_pitch", "js1_button5").' + }, + mapName: { + type: 'string', + description: 'Optional case-insensitive ActionMap filter (e.g. "spaceship_movement", "spaceship_mining").' + }, + masterFlightMode: { + type: 'string', + description: "Optional Master Flight Mode filter ('SCM' or 'NAV').", + enum: ['SCM', 'NAV'] + }, + bindingState: { + type: 'string', + description: "Filter by whether the action is currently bound in the profile: 'bound', 'unbound', or 'all' (default 'all').", + enum: ['bound', 'unbound', 'all'] + }, + limit: { + type: 'number', + description: 'Maximum results to return (default 40).' + } + }, + additionalProperties: false + }, + execute: wrapExecute('search_bindings_and_catalog', (input: { + query?: string; + mapName?: string; + masterFlightMode?: 'SCM' | 'NAV'; + bindingState?: 'bound' | 'unbound' | 'all'; + limit?: number; + }) => { + const s = stateRef.current; + const doc = s.doc; + const catalog = new CatalogManager(); + const q = (input.query || '').trim().toLowerCase(); + const mapFilter = (input.mapName || '').trim().toLowerCase(); + const stateFilter = input.bindingState || 'all'; + const limit = typeof input.limit === 'number' && input.limit > 0 ? input.limit : 40; + + const results: Array<{ + mapName: string; + mapLabel: string; + domain: string; + actionName: string; + label: string; + defaultActivationMode?: string; + defaultMultiTap?: number; + masterFlightMode?: 'SCM' | 'NAV'; + isBound: boolean; + inputs: BindingInput[]; + }> = []; + + const seenKeys = new Set(); + + // 1. Scan canonical catalog maps and merge with active profile bindings + for (const mapCatalog of catalog.getAllActionMaps()) { + if (mapFilter && mapCatalog.mapName.toLowerCase() !== mapFilter) { + continue; + } + const docMap = doc + ? Object.values(doc.actionMaps).find( + m => m.name.toLowerCase() === mapCatalog.mapName.toLowerCase() + ) + : undefined; + + for (const catAction of mapCatalog.actions) { + if (input.masterFlightMode && catAction.masterFlightMode !== input.masterFlightMode) { + continue; + } + const docAction = docMap + ? Object.values(docMap.actions).find( + a => a.name.toLowerCase() === catAction.name.toLowerCase() + ) + : undefined; + + const activeInputs = (docAction?.inputs || []).filter(i => i.input.trim() !== ''); + const isBound = activeInputs.length > 0; + + if (stateFilter === 'bound' && !isBound) continue; + if (stateFilter === 'unbound' && isBound) continue; + + const matchText = [ + catAction.name, + catAction.label, + catAction.description || '', + mapCatalog.mapName, + mapCatalog.label, + ...activeInputs.map(i => i.input) + ] + .join(' ') + .toLowerCase(); + + if (q && !matchText.includes(q)) continue; + + seenKeys.add(`${mapCatalog.mapName.toLowerCase()}::${catAction.name.toLowerCase()}`); + results.push({ + mapName: docMap?.name || mapCatalog.mapName, + mapLabel: mapCatalog.label, + domain: mapCatalog.domain, + actionName: docAction?.name || catAction.name, + label: docAction?.label || catAction.label, + defaultActivationMode: catAction.defaultActivationMode, + defaultMultiTap: catAction.defaultMultiTap, + masterFlightMode: catAction.masterFlightMode, + isBound, + inputs: docAction?.inputs || [] + }); + + if (results.length >= limit) break; + } + if (results.length >= limit) break; + } + + // 2. Also include custom profile actions not present in the base catalog + if (doc && results.length < limit) { + for (const docMap of Object.values(doc.actionMaps)) { + if (mapFilter && docMap.name.toLowerCase() !== mapFilter) continue; + for (const docAction of Object.values(docMap.actions)) { + const key = `${docMap.name.toLowerCase()}::${docAction.name.toLowerCase()}`; + if (seenKeys.has(key)) continue; + + const activeInputs = docAction.inputs.filter(i => i.input.trim() !== ''); + const isBound = activeInputs.length > 0; + if (stateFilter === 'bound' && !isBound) continue; + if (stateFilter === 'unbound' && isBound) continue; + + const matchText = [ + docAction.name, + docAction.label || '', + docMap.name, + ...activeInputs.map(i => i.input) + ] + .join(' ') + .toLowerCase(); + + if (q && !matchText.includes(q)) continue; + + results.push({ + mapName: docMap.name, + mapLabel: docMap.label || docMap.name, + domain: 'custom', + actionName: docAction.name, + label: docAction.label || docAction.name, + defaultActivationMode: CatalogManager.getDefaultActivationMode(docAction.name), + defaultMultiTap: CatalogManager.getDefaultMultiTap(docAction.name), + masterFlightMode: CatalogManager.getMasterFlightMode(docAction.name), + isBound, + inputs: docAction.inputs + }); + + if (results.length >= limit) break; + } + if (results.length >= limit) break; + } + } + + return { + totalReturned: results.length, + results + }; + }) + }, + { + name: 'find_unused_joystick_inputs', + title: 'Find Unused Joystick Buttons & Axes', + description: + 'Inspects a specific joystick instance (e.g. js1, js2) and lists physical buttons, hats, and axes that are currently unbound across the profile (or within a specific ActionMap).', + readOnlyHint: true, + inputSchema: { + type: 'object', + properties: { + deviceInstance: { + type: 'number', + description: '1-based joystick instance number (e.g. 1 for js1, 2 for js2).' + }, + maxButtons: { + type: 'number', + description: 'Total button count on the physical stick to check (default 32).' + }, + mapName: { + type: 'string', + description: 'Optional ActionMap name to scope used/unused check to a single operational context.' + } + }, + required: ['deviceInstance'], + additionalProperties: false + }, + execute: wrapExecute('find_unused_joystick_inputs', (input: { + deviceInstance: number; + maxButtons?: number; + mapName?: string; + }) => { + const s = stateRef.current; + if (!s.doc) { + return { error: 'No keybinding profile is currently loaded.' }; + } + const inst = Number(input.deviceInstance) || 1; + const prefix = `js${inst}`; + const maxButtons = Math.min(Math.max(Number(input.maxButtons) || 32, 1), 128); + const mapScope = (input.mapName || '').trim().toLowerCase(); + + const usedHardwareKeys = new Map>(); + + for (const mapGroup of Object.values(s.doc.actionMaps)) { + if (mapScope && mapGroup.name.toLowerCase() !== mapScope) continue; + for (const act of Object.values(mapGroup.actions)) { + for (const inp of act.inputs) { + if (inp.devicePrefix.toLowerCase() === prefix.toLowerCase() && inp.hardwareKey) { + const hwKey = inp.hardwareKey.toLowerCase(); + const list = usedHardwareKeys.get(hwKey) || []; + list.push({ + mapName: mapGroup.name, + actionName: act.name, + input: inp.input + }); + usedHardwareKeys.set(hwKey, list); + } + } + } + } + + const unusedButtons: string[] = []; + const usedButtons: Array<{ input: string; bindings: Array<{ mapName: string; actionName: string; input: string }> }> = []; + + for (let b = 1; b <= maxButtons; b++) { + const key = `button${b}`; + const fullInput = `${prefix}_${key}`; + const bindings = usedHardwareKeys.get(key); + if (!bindings || bindings.length === 0) { + unusedButtons.push(fullInput); + } else { + usedButtons.push({ input: fullInput, bindings }); + } + } + + const standardAxes = ['x', 'y', 'z', 'rotx', 'roty', 'rotz', 'slider1', 'slider2']; + const unusedAxes = standardAxes + .filter(ax => !usedHardwareKeys.has(ax)) + .map(ax => `${prefix}_${ax}`); + + return { + devicePrefix: prefix, + scope: mapScope || 'entire_profile', + unusedButtonCount: unusedButtons.length, + unusedButtons, + unusedAxes, + usedButtonCount: usedButtons.length, + usedButtons + }; + }) + }, + { + name: 'set_action_binding', + title: 'Set or Clear Action Keybinding Inputs', + description: + 'Updates the and inputs for a Star Citizen action in the loaded profile. Passing an empty inputs array clears the binding (producing an explicit unbind node on XML export so Star Citizen does not revert to defaultProfile.xml).', + inputSchema: { + type: 'object', + properties: { + mapName: { + type: 'string', + description: 'ActionMap name (e.g. "spaceship_movement", "spaceship_weapons").' + }, + actionName: { + type: 'string', + description: 'Programmatic action name (e.g. "v_pitch", "v_eject", "v_toggle_mining_mode").' + }, + inputs: { + type: 'array', + description: + 'Array of binding descriptors. First item defaults to bindType "rebind", subsequent items default to "addbind". Pass [] to unbind.', + items: { + type: 'object', + properties: { + input: { + type: 'string', + description: 'CryEngine input code (e.g. "js1_button5", "lalt+js2_button3", "kb1_space").' + }, + bindType: { + type: 'string', + enum: ['rebind', 'addbind'] + }, + activationMode: { + type: 'string', + enum: ['press', 'hold', 'double_tap', 'delayed_press', 'smart_toggle'] + }, + multiTap: { + type: 'number', + description: 'Optional tap count (e.g. 2 for double-tap).' + } + } + } + } + }, + required: ['mapName', 'actionName', 'inputs'], + additionalProperties: false + }, + execute: wrapExecute('set_action_binding', (input: { + mapName: string; + actionName: string; + inputs: Array<{ + input: string; + bindType?: BindType; + activationMode?: ActivationMode; + multiTap?: number; + }>; + }) => { + const s = stateRef.current; + if (!s.doc) { + throw new Error('No keybinding profile is currently loaded.'); + } + if (!input.mapName || !input.actionName) { + throw new Error('Both mapName and actionName are required.'); + } + + const rawList = Array.isArray(input.inputs) ? input.inputs : []; + const normalizedInputs: BindingInput[] = rawList + .filter(item => item && typeof item.input === 'string' && item.input.trim() !== '') + .map((item, idx) => { + const bindType: BindType = item.bindType || (idx === 0 ? 'rebind' : 'addbind'); + const parsed = ActionMapsParser.parseInputDescriptor(item.input.trim(), bindType); + return { + ...parsed, + activationMode: item.activationMode, + multiTap: item.multiTap && item.multiTap > 1 ? item.multiTap : undefined + }; + }); + + const catEntry = CatalogManager.getActionEntry(input.actionName); + s.onSaveActionInputs(input.mapName, input.actionName, normalizedInputs, catEntry?.label); + + // Evaluate immediate conflicts for the newly bound action against the current document + const candidateAction: ActionBinding = { + name: input.actionName, + label: catEntry?.label, + inputs: normalizedInputs + }; + + const detectedConflicts: Array<{ + severity: string; + targetContext: string; + targetAction: string; + sharedInput: string; + reason: string; + }> = []; + + for (const mapGroup of Object.values(s.doc.actionMaps)) { + for (const otherAction of Object.values(mapGroup.actions)) { + if ( + mapGroup.name.toLowerCase() === input.mapName.toLowerCase() && + otherAction.name.toLowerCase() === input.actionName.toLowerCase() + ) { + continue; + } + const evaluation = ConflictResolver.evaluateActions( + input.mapName, + candidateAction, + mapGroup.name, + otherAction + ); + if (evaluation.severity !== ConflictSeverity.None) { + detectedConflicts.push({ + severity: severityLabel(evaluation.severity), + targetContext: evaluation.targetContext, + targetAction: evaluation.targetAction, + sharedInput: evaluation.sharedInput, + reason: evaluation.reason + }); + } + } + } + + return { + status: 'updated', + mapName: input.mapName, + actionName: input.actionName, + label: catEntry?.label ?? input.actionName, + unbindEmittedOnExport: normalizedInputs.length === 0, + inputs: normalizedInputs, + conflictsWithNewBinding: detectedConflicts + }; + }) + }, + { + name: 'auto_fix_obsolete_conflicts', + title: 'Auto-Fix Obsolete Star Citizen Collisions', + description: + 'Automatically strips deprecated legacy bindings (Rule R2 obsolete_collision, such as removed 3.x cruise control or quantum toggles) that collide with modern actions.', + inputSchema: { + type: 'object', + properties: { + deprecatedActionName: { + type: 'string', + description: 'Optional specific deprecated action name to strip. If omitted, fixes all obsolete_collision entries in the profile.' + } + }, + additionalProperties: false + }, + execute: wrapExecute('auto_fix_obsolete_conflicts', (input: { deprecatedActionName?: string }) => { + const s = stateRef.current; + if (!s.doc) { + throw new Error('No keybinding profile is currently loaded.'); + } + + const report = ConflictResolver.auditDocument(s.doc, { deviceFilter: 'all' }); + const targetFilter = (input.deprecatedActionName || '').trim().toLowerCase(); + + const fixable = report.conflicts.filter(c => { + if (!c.deprecatedAction) return false; + if (!targetFilter) return true; + return c.deprecatedAction.toLowerCase().includes(targetFilter); + }); + + for (const conflict of fixable) { + s.onAutoFixConflict(conflict); + } + + return { + fixedCount: fixable.length, + fixedConflicts: fixable.map(c => ({ + deprecatedAction: c.deprecatedAction, + sharedInput: c.sharedInput, + collidedWith: `${c.targetContext}.${c.targetAction}` + })) + }; + }) + }, + { + name: 'remap_joystick_instances', + title: 'Re-Index Joystick Hardware Instances (Bypass 4-Device Limit)', + description: + 'Updates the joystick instance remapping table (js1..js8+) used when exporting XML, bypassing Star Citizen pp_resortdevices 4-device ceiling.', + inputSchema: { + type: 'object', + properties: { + mapping: { + type: 'object', + description: + 'Map of current 1-based joystick instance numbers to target 1-based instance numbers (e.g. { "1": 2, "2": 1 }).' + }, + reset: { + type: 'boolean', + description: 'If true, resets all joystick instances back to identity (js1 -> js1, js2 -> js2).' + } + }, + additionalProperties: false + }, + execute: wrapExecute('remap_joystick_instances', (input: { + mapping?: Record; + reset?: boolean; + }) => { + const s = stateRef.current; + const nextMap = new Map(); + + if (s.doc) { + for (const dev of s.doc.devices) { + if (dev.type === 'joystick') { + nextMap.set(dev.instance, dev.instance); + } + } + } + + if (!input.reset && input.mapping) { + for (const [srcKey, targetVal] of Object.entries(input.mapping)) { + const srcNum = parseInt(srcKey.replace(/^js/i, ''), 10); + const dstNum = Number(targetVal); + if (!Number.isNaN(srcNum) && !Number.isNaN(dstNum) && srcNum >= 1 && dstNum >= 1) { + nextMap.set(srcNum, dstNum); + } + } + } + + s.onSetHardwareMapping(nextMap); + + const applied: Record = {}; + nextMap.forEach((dst, src) => { + applied[`js${src}`] = `js${dst}`; + }); + + return { + status: input.reset ? 'reset' : 'remapped', + hardwareMapping: applied + }; + }) + }, + { + name: 'configure_joystick_options', + title: 'Configure Joystick Options (Inversions, Deadzones, Sensitivities)', + description: + 'Adds or updates an hardware configuration block for a 1-based joystick instance, preserving axis inversions, deadzones, sensitivities, and ProductGUID.', + inputSchema: { + type: 'object', + properties: { + instance: { + type: 'number', + description: '1-based joystick instance number (e.g. 1 for js1, 2 for js2).' + }, + productName: { + type: 'string', + description: 'Device Product name (e.g. "VKBsim Gladiator EVO R").' + }, + productGuid: { + type: 'string', + description: 'Optional DirectInput ProductGUID.' + }, + inversions: { + type: 'object', + description: 'Axis inversion booleans (e.g. { "pitch": true, "flight_move_strafe_longitudinal": true }).' + }, + deadzones: { + type: 'object', + description: 'Axis deadzone numbers between 0.0 and 1.0 (e.g. { "x": 0.04, "y": 0.04 }).' + }, + sensitivities: { + type: 'object', + description: 'Axis sensitivity curves/multipliers (e.g. { "pitch": 1.25 }).' + } + }, + required: ['instance'], + additionalProperties: false + }, + execute: wrapExecute('configure_joystick_options', (input: { + instance: number; + productName?: string; + productGuid?: string; + inversions?: Record; + deadzones?: Record; + sensitivities?: Record; + }) => { + const s = stateRef.current; + if (!s.doc) { + throw new Error('No keybinding profile is currently loaded.'); + } + const inst = Number(input.instance); + if (!inst || inst < 1) { + throw new Error('instance must be a 1-based positive integer.'); + } + + const existing = s.doc.devices.find( + (d): d is JoystickDeviceOption => d.type === 'joystick' && d.instance === inst + ); + + const updatedDevice: JoystickDeviceOption = { + type: 'joystick', + instance: inst, + productName: input.productName || existing?.productName || `Joystick ${inst}`, + productGuid: input.productGuid ?? existing?.productGuid, + inversions: { + ...(existing?.inversions || {}), + ...(input.inversions || {}) + }, + deadzones: { + ...(existing?.deadzones || {}), + ...(input.deadzones || {}) + }, + sensitivities: { + ...(existing?.sensitivities || {}), + ...(input.sensitivities || {}) + } + }; + + s.onApplyDeviceOptions(updatedDevice); + + return { + status: 'configured', + device: updatedDevice + }; + }) + }, + { + name: 'workspace_control', + title: 'Control Cockpit UI Navigation, Presets & XML Export', + description: + 'Navigates HUD tabs (matrix, inspector, conflicts), updates the live search filter, switches starter HOSAS/HOTAS presets, or exports the lossless CryEngine XML with all jsX_ remappings applied.', + inputSchema: { + type: 'object', + properties: { + activeTab: { + type: 'string', + description: "Switch the active HUD tab: 'matrix', 'inspector', or 'conflicts'.", + enum: ['matrix', 'inspector', 'conflicts'] + }, + searchQuery: { + type: 'string', + description: 'Set the Keybinding Matrix search filter.' + }, + deviceScope: { + type: 'string', + description: "Set the Conflict Diagnostics device scope: 'js', 'kb', or 'all'.", + enum: ['js', 'kb', 'all'] + }, + loadPreset: { + type: 'string', + description: "Optional starter preset to load: 'vkb_omni', 'dual_vkb', or 'hotas_t16000m'.", + enum: ['vkb_omni', 'dual_vkb', 'hotas_t16000m'] + }, + exportXml: { + type: 'boolean', + description: 'If true, serializes and returns the lossless Star Citizen ActionMaps XML string.' + } + }, + additionalProperties: false + }, + execute: wrapExecute('workspace_control', async (input: { + activeTab?: 'matrix' | 'inspector' | 'conflicts'; + searchQuery?: string; + deviceScope?: string; + loadPreset?: 'vkb_omni' | 'dual_vkb' | 'hotas_t16000m'; + exportXml?: boolean; + }) => { + const s = stateRef.current; + + if (input.loadPreset) { + const presetMap: Record = { + vkb_omni: { file: 'vkb_evo_hosas_omni.xml', label: 'Dual VKB (Right + Omni Left)' }, + dual_vkb: { file: 'dual_vkb_evo_hosas.xml', label: 'Dual VKB HOSAS' }, + hotas_t16000m: { file: 'hotas_t16000m.xml', label: 'T.16000M HOTAS' } + }; + const target = presetMap[input.loadPreset]; + if (target) { + await s.onLoadSamplePreset(target.file, target.label); + } + } + + if (input.activeTab) { + s.onSetActiveTab(input.activeTab); + } + if (typeof input.searchQuery === 'string') { + s.onSetSearchQuery(input.searchQuery); + } + if (input.deviceScope) { + s.onSetDeviceScope(input.deviceScope); + } + + let exportedXml: string | undefined; + if (input.exportXml && stateRef.current.doc) { + exportedXml = ActionMapsExporter.exportToXML( + stateRef.current.doc, + stateRef.current.hardwareMapping + ); + } + + return { + activeTab: input.activeTab ?? s.activeTab, + searchQuery: typeof input.searchQuery === 'string' ? input.searchQuery : s.searchQuery, + deviceScope: input.deviceScope ?? s.deviceScope, + loadedPreset: input.loadPreset ?? null, + exportedXml: exportedXml ?? null + }; + }) + } + ]; + + return tools; + }, []); + + useEffect(() => { + const host = ensureModelContextHost(); + setIsNativeSupport(!host.__isPolyfill); + + const tools = buildTools(); + setRegisteredTools(tools); + + for (const tool of tools) { + host.registerTool(tool); + } + + return () => { + if (typeof host.unregisterTool === 'function') { + for (const tool of tools) { + host.unregisterTool(tool.name); + } + } + }; + }, [buildTools]); + + const executeRegisteredTool = useCallback(async (name: string, input: Record = {}) => { + const host = ensureModelContextHost(); + return await host.executeTool(name, input); + }, []); + + return { + registeredTools, + isNativeSupport, + lastToolCall, + executeRegisteredTool + }; +} diff --git a/docs/ARCHITECTURE_BLUEPRINT.md b/docs/ARCHITECTURE_BLUEPRINT.md index 809df9e..7268fab 100644 --- a/docs/ARCHITECTURE_BLUEPRINT.md +++ b/docs/ARCHITECTURE_BLUEPRINT.md @@ -798,6 +798,12 @@ export function useGamepadListener( } ``` +### 3.3 WebMCP Browser AI Agent Integration (`useWebMCP.ts`) + +Exposes 9 structured JSON-Schema-typed tools directly on `document.modelContext` and `navigator.modelContext` (with an automatic standards-compliant polyfill bridge) so browser-embedded AI assistants can inspect and mutate the active Star Citizen profile in memory without DOM scraping or requiring a backend server: +- **Read / Diagnostic Tools**: `get_profile_summary`, `audit_conflicts`, `search_bindings_and_catalog`, `find_unused_joystick_inputs` +- **Write / Mutate Tools**: `set_action_binding` (enforcing the `` unbind invariant and chorded modifier parsing), `auto_fix_obsolete_conflicts`, `remap_joystick_instances`, `configure_joystick_options`, and `workspace_control`. + --- ## Phase 4: Local Extraction Daemon Strategy (Go) diff --git a/docs/PROJECT_STATE.md b/docs/PROJECT_STATE.md index 4cca69c..521b7c8 100644 --- a/docs/PROJECT_STATE.md +++ b/docs/PROJECT_STATE.md @@ -27,7 +27,8 @@ This project provides a lossless, high-performance Keybinding Management Suite f | **Hardware Studio & Generator** | `apps/web/src/components/HardwareGeneratorModal.tsx` | **Complete** | Generates `` blocks, community hardware JSON profiles, starter XML templates, and PR contribution templates for unmapped devices. | | **Binding Table & Rebind Engine** | `apps/web/src/components/BindingTable.tsx` | **Complete** | Filterable, paginated 50-map matrix with live hardware listening, separated metadata tags, device chips, and inline rebind editor. | | **Conflict Viewer Diagnostics** | `apps/web/src/components/ConflictViewer.tsx` | **Complete** | Multi-severity conflict explorer with device-scoping, formatted tokens, and resolution suggestions. | -| **Contributor Hub** | `apps/web/src/App.tsx` | **Complete** | Dedicated maintainer hub separating `sc-daemon` patch extraction and PR submission tools from regular player workflows. | +| **WebMCP Browser AI Bridge** | `apps/web/src/hooks/useWebMCP.ts` | **Complete** | Exposes 9 typed client-side tools on `document.modelContext` / `navigator.modelContext` with a built-in diagnostic runner in Contributor Tools. | +| **Contributor Hub** | `apps/web/src/App.tsx` | **Complete** | Dedicated maintainer hub separating `sc-daemon` patch extraction, WebMCP bridge diagnostics, and PR submission tools from regular player workflows. | | **Go Extraction Daemon** | `daemon/` | **Complete** | Direct Zip64 central directory streamer (`io.ReaderAt`). CryEngine 16-byte XOR cipher decryptor. Zero-dependency `CryXmlB` binary XML decoder. Method 100 (zstd) decompression. Local `.scj` cache, CLI flags (`--version`, `--game-path`), sanitized paths, and HTTP server (`:8765`). | | **Cockpit Design System** | `apps/web/src/index.css` | **Complete** | Tailwind CSS v3 + custom CSS design system with constrained icon sizing, layout utilities, sci-fi glassmorphism cards, and interactive modal dialogs. | diff --git a/e2e/app-workflow.spec.ts b/e2e/app-workflow.spec.ts index fdc5e5e..71711fa 100644 --- a/e2e/app-workflow.spec.ts +++ b/e2e/app-workflow.spec.ts @@ -302,4 +302,39 @@ test.describe('Star Citizen Keybinding Architect E2E UX Suite', () => { expect(xmlContent).toContain(''); }); + + test('exposes WebMCP tools on document.modelContext and executes agent workflows end-to-end', async ({ page }) => { + // 1. Verify WebMCP tools are registered on document.modelContext + const toolNames = await page.evaluate(() => { + return document.modelContext?.getTools().map(t => t.name) ?? []; + }); + expect(toolNames).toContain('get_profile_summary'); + expect(toolNames).toContain('audit_conflicts'); + expect(toolNames).toContain('search_bindings_and_catalog'); + expect(toolNames).toContain('set_action_binding'); + expect(toolNames).toContain('remap_joystick_instances'); + + // 2. Invoke set_action_binding via document.modelContext like an embedded browser AI agent + const bindResult: any = await page.evaluate(async () => { + return await document.modelContext?.executeTool('set_action_binding', { + mapName: 'spaceship_movement', + actionName: 'v_eject', + inputs: [{ input: 'js2_button12', activationMode: 'hold' }] + }); + }); + expect(bindResult.status).toBe('updated'); + await expect(page.getByText('js2_button12')).toBeVisible(); + + // 3. Click the WebMCP header badge to open the WebMCP diagnostic panel + const headerBadge = page.getByTestId('webmcp-header-badge'); + await expect(headerBadge).toBeVisible(); + await expect(headerBadge).toContainText('WebMCP: 9 AI Tools'); + await headerBadge.click(); + const bridgePanel = page.getByTestId('webmcp-bridge-panel'); + await expect(bridgePanel).toBeVisible(); + await expect(bridgePanel).toContainText('9 Tools Ready'); + + await bridgePanel.getByRole('button', { name: /Run Tool/i }).click(); + await expect(page.getByTestId('webmcp-test-output')).toContainText('dual_vkb_evo_scm'); + }); });