chore: freeze v1.1.3 filing submission build (60 levels, full-screen safe layout)

This commit is contained in:
fannyxl committed 2026-11-25 23:14:45 +08:00
commit 96c19dca82
174 files changed
+37935

No files matched your search

+525
View File
@@ -0,0 +1,525 @@
# Changelog
All notable changes to Funplay MCP for Cocos will be documented in this file.
This project follows a simple changelog format inspired by [Keep a Changelog](https://keepachangelog.com/), and uses semantic versioning when releases are tagged.
## [Unreleased]
## [0.7.6] - 2026-11-18
### Added
- One-click MCP setup for Pi 1.0+ writes the project-bound Streamable HTTP endpoint to `.pi/mcp.json`. Configure + Skills installs missing built-ins into the shared `.agents/skills` directory.
## [0.7.5] - 2026-11-18
### Added
- One-click MCP setup for Google Antigravity writes the project-bound Streamable HTTP endpoint to `.agents/mcp_config.json`. Configure + Skills installs missing built-ins into `.agents/skills`, which Antigravity and Codex both discover.
## [0.7.4] - 2026-11-17
### Fixed
- Fixed [#28](https://github.com/FunplayAI/funplay-cocos-mcp/issues/28): Game View screenshots recognize Windows-style and URL-encoded WebView preload paths. Game capture uses a visible native Game View or Cocos GameCanvas and reports an error when no game render surface is available.
## [0.7.3] - 2026-11-17
### Added
- The built-in Cocos UI Skill v5 guides conversion from a full-page design image to an editable, responsive prefab. It covers asset reuse, separate navigation layers, reusable list rows, and region-by-region fidelity checks against captures from the Cocos preview. Image generation is optional when missing artwork needs to be recreated.
## [0.7.2] - 2026-11-10
### Added
- Configure + Skills, Project Skills, and MCP Skill tools now support Trae (`.trae/skills`), VS Code / Copilot (`.github/skills`), and Kiro (`.kiro/skills`), covering all 11 one-click clients with managed references, version checks, diffs, backups and restore.
### Fixed
- Trae setup writes the active Cocos project's `.trae/mcp.json` instead of guessing a global file. Bilingual setup guidance remains visible in the dashboard and explains the required Project MCP switch.
- VS Code setup always uses its canonical user-profile path on macOS, honors Linux XDG and portable/appdata overrides, and preserves JSONC comments and unrelated configuration.
- Codex setup honors `CODEX_HOME` and accepts an empty `[mcp_servers]` parent table with explicit server children while retaining conservative rejection of inline/ambiguous TOML.
- OpenCode recognizes existing V2 `mcp.servers` and global timeout settings, retains compatible V1 flat entries, matches previews to the chosen layout, and refuses duplicate registrations across both maps.
- Strict JSON clients reject duplicate keys before writing. URL-only clients no longer confuse explicit SSE/stdio with HTTP; setup removes the obsolete transport while retaining custom options. Disabled and local-command registrations require review instead of falsely reporting a configured HTTP connection.
## [0.7.1] - 2026-11-09
### Added
- Added a bilingual Funplay > Contact & Feedback menu and dedicated panel with the author's email, QQ group `1108522331`, and copy buttons.
### Fixed
- Serialized server start, stop, restart, and runtime configuration changes so overlapping requests cannot lose the owning listener or report a stopped server while its HTTP port remains open.
- Legacy-coordinate mouse clicks/drags and calibrated input with legacy timing now share owned release cleanup and uncertain-delivery reporting. Failed release retains the window lock; MCP stop/restart retries cleanup without replaying the press, and shutdown prevents suspended legacy gestures from sending more input.
- `refresh_assets` now requests `db://assets` instead of `db://assets/` when refreshing the assets root, avoiding Cocos Creator's missing-asset/meta errors. Contributed in [#27](https://github.com/FunplayAI/funplay-cocos-mcp/pull/27).
### Changed
- Corrected the README's built-in project Skills version from v3 to v4.
## [0.7.0] - 2026-10-29
### Added
- Project-scoped MCP URLs and explicit project/extension-session guards for mutating legacy-URL calls. Initialize, tool results and screenshot geometry carry structural identity evidence. Old URLs remain readable; writes require a verified `expected_context` pin. These checks prevent accidental misrouting, not unauthorized access.
- Opt-in `timing: "frame-paced"` for calibrated mouse drags: unscaled duration/holds, separate target-renderer animation frames, bounded receipts, retained request-key deduplication, same-tool status/cancel, stale/focus/pause checks and owned shutdown cleanup. Renderer frames are explicitly not native Game View Update evidence or gameplay acceptance. Legacy step timing remains the default.
### Changed
- One-click setup generates project-bound URLs. The existing Skills notice also reports old endpoints and offers explicit combined reconfiguration; unreadable, unsupported, unverified and manually repointed entries remain protected, including custom headers/timeouts and historical shared entries. TOML updates retain the existing conservative URL-block editor, not a full-document TOML validator.
- Built-in workflow/UI Skills v4 add conditional identity/input guidance with managed reference updates, legacy-v3 recognition and protection for locally modified content. Core/Full tool counts and project settings are unchanged.
### Fixed
- Frame-paced input recognizes native Game View child focus inside the captured foreground window, and a focus handoff after release no longer marks a finished drag as failed. Window focus loss while a button is held still interrupts input and attempts owned release cleanup.
## [0.6.10] - 2026-10-29
### Fixed
- Fixed [#26](https://github.com/FunplayAI/funplay-cocos-mcp/issues/26): an unavailable configured Host (such as a stopped WSL network adapter) no longer prevents Cocos Creator from loading the extension. MCP stays stopped, the original startup error remains visible, and editor panels remain available for recovery. Explicit start/restart failures still report errors; no automatic Host substitution or startup config rewrite is performed.
### Added
- Added Server Host and Apply Host to the MCP Server panel. Address edits are validated before saving or stopping a healthy listener; applying a corrected Host retries startup when MCP is enabled. Environment-variable overrides are identified without changing their persisted project value. Bilingual guidance explains local-only access, trusted-network exposure, and client reconfiguration after an address change.
## [0.6.9] - 2026-10-27
### Added
- Added DeepSeek Harness (DSH) support for [#25](https://github.com/FunplayAI/funplay-cocos-mcp/issues/25): generate a dedicated project-local Cordis overlay using the official Streamable HTTP MCP client. The dashboard displays an explicit `dsh web --patch` launch command; the overlay is not auto-loaded and existing global/profile YAML is never edited. Malformed, unrelated, disabled, or manually repointed entries remain protected, and owned endpoint updates are atomic.
- Configure + Skills, Project Skills, and MCP instruction/Skill tools now support DSH's nearest-Git-root `.dsh/skills` directory, including managed references, update notices, backups, and restore. Existing or locally edited Skills are preserved.
## [0.6.8] - 2026-10-20
### Added
- Added CodeBuddy IDE 4.0+ to one-click MCP setup using the active Cocos project's `.mcp.json`, with comment-preserving JSONC updates and project-specific server names. Configure + Skills installs missing workflow/UI Skills under `.codebuddy/skills`; Project Skills and MCP instruction/Skill tools support the same client, including managed references, update notices, backups, and restore. Existing configuration and locally edited Skills remain protected.
## [0.6.7] - 2026-10-13
### Fixed
- Fixed [#24](https://github.com/FunplayAI/funplay-cocos-mcp/issues/24): normal SSE GET probes no longer produce console warnings or fill the MCP runtime log. The server still returns HTTP 405 when SSE streams are unsupported, as required by Streamable HTTP; invalid Origin headers and unexpected HTTP methods retain their rejection warnings. POST tool calls, `/health`, `/tools`, and the console logging toggle are unchanged.
## [0.6.6] - 2026-10-10
### Added
- Added read-only `check_asset_ready` in the Full profile: bounded native Asset Database queries confirm an exact asset's imported metadata and stable UUID/URL identity. Database readiness does not imply script compilation, an empty import queue, or runtime loading.
- Added screenshot calibration metadata, including `captureId`, actual PNG dimensions, viewport zoom/DPR, and crop origin. Mouse click/drag and preview input support opt-in `image-pixels` coordinates, bound to the captured window and project. Stale or changed geometry is rejected; interrupted input reports uncertain delivery and attempts to release a held button without replaying.
### Changed
- Upgraded both built-in project Skills to v3 with concise entrypoints and on-demand Cocos-specific references for readiness, layout, nine-slice/importer settings, fonts/localization, and input validation. Preserve project baselines; do not proactively add SafeArea containers, scripts, or inset adjustments.
- Project Skills version checks, diffs, backups, and restore now include managed reference files across all six supported clients, while preserving unrelated files and refusing to overwrite user-owned reference destinations.
- Screenshot MCP responses retain native image content and add calibration text/structured metadata without duplicating Base64 in structured results or Recent Activity. Legacy mouse coordinate semantics remain unchanged; explicit unavailable window targets no longer fall back to another window.
### Fixed
- Game View screenshot cropping now prefers Creator's native preview WebView over text-matched toolbar elements, preserving the actual game render area and its calibrated input origin. Scene screenshots prefer the visible edit WebView; hidden, not-yet-ready, or ambiguous native viewport matches are rejected.
- Native mouse input now supplies screen coordinates and consistent pressed-button flags, allowing Creator's Game View to receive actual button clicks and the complete drag start/move/end chain without changing legacy coordinate semantics.
## [0.6.5] - 2026-10-07
### Fixed
- Fixed stdio wrapper initialization with standard MCP clients by supporting newline-delimited UTF-8 JSON-RPC messages (NDJSON), while retaining the existing `Content-Length` framing. NDJSON responses are serialized on a single line. Contributed in [#23](https://github.com/FunplayAI/funplay-cocos-mcp/pull/23).
## [0.6.4] - 2026-09-19
### Fixed
- Fixed Claude Code one-click configuration on Windows by writing forward-slash project scope paths and reusing existing scope keys regardless of drive-letter case. Contributed in [#22](https://github.com/FunplayAI/funplay-cocos-mcp/pull/22).
## [0.6.3] - 2026-09-12
### Fixed
- Fixed `Object.hasOwn is not a function` in older Cocos Creator editor runtimes (reported on 3.8.3), affecting Configure + Skills, JSONC configuration, and project prompts. Use compatible own-property checks while retaining duplicate-key validation and concurrent-edit protection. Contributed in [#21](https://github.com/FunplayAI/funplay-cocos-mcp/pull/21).
## [0.6.2] - 2026-09-11
### Added
- Added OpenCode one-click MCP configuration and project-local Skills support (`.opencode/skills`), contributed in [#19](https://github.com/FunplayAI/funplay-cocos-mcp/pull/19).
- OpenCode configuration reads and updates JSON/JSONC with comments and trailing commas, preserves unrelated text and settings, and rejects malformed or duplicate-key configurations without overwriting them.
## [0.6.1] - 2026-09-10
### Fixed
- Fixed Game View preview started through MCP leaving the native toolbar in a stopped or wrong-platform state, which disabled manual pause controls. Preview starts and mode changes now use the toolbar's own logic, repair legacy state mismatches, and verify the actual preview state.
- Routed `pause_runtime` and `resume_runtime` to the Game View preview controller instead of the edit-scene director. Repeated start/pause/resume calls are idempotent; stopped previews, rejected operations, busy or unavailable toolbars now report explicit errors.
- `get_runtime_state` and scene validation now report Game View running/paused state and toolbar synchronization. Edit-scene frame/time-scale counters remain in performance snapshots and are explicitly labeled to avoid confusing them with preview state.
## [0.6.0] - 2026-09-07
### Added
- Added isolated per-script console capture for editor/scene execution and compatibility aliases. Logs survive failures and remain available when MCP console printing is disabled; optional execution metadata preserves existing tool return data.
- Added a project-persisted Print MCP logs toggle in Settings. It immediately controls extension and HTTP server console printing, including startup messages, while preserving Recent Activity, internal diagnostics, and live MCP connections.
- Added project-derived default ports and project-specific MCP entry names. Existing fixed-port configurations remain compatible; temporary fallback endpoints must be pinned before one-click configuration.
- Added per-client Project Skills installation, status, diff, backup, and restore for Codex, Claude Code, Cursor, Qoder, and Kimi Code. Codex now uses `.agents/skills`, with protected migration of legacy `.codex/skills` built-ins.
- Added parameterized project workflows from `mcp-prompts/*.md`, refreshed on list/get, with required-argument validation, bounded file discovery, and visible parse warnings.
### Changed
- Recent Activity now preserves result hierarchy, array items, and scalar values instead of selecting six flattened fields. Script cards separate summaries, execution logs, and return values; expandable branches survive refreshes, and large/sensitive results stay bounded and redacted.
- Redesigned MCP Server, Tool Exposure, Settings, and Project Skills with consistent headings, aligned controls, lightweight sections, and responsive layouts. Skills show only available actions with file/backup details collapsed; extension update controls are in Settings.
- Removed all Output sections and the standalone Activity/log-viewing window and menu, while retaining the dashboard's Recent Activity with bounded result previews. Clear removes only interaction history. Action notices preserve success/failure feedback; backend diagnostic tools and resources are unchanged.
- Added Configure + Skills for supported clients, installing only missing built-ins and preserving existing or locally modified copies, including when files change during setup.
- One-click configuration preserves other projects and manually repointed entries, checks for concurrent edits, and writes configuration atomically. Claude Code entries are scoped to the nearest Git root.
- Dashboard Skills notices now follow the selected supported client. Project Skills includes a client selector and explicit managed-directory paths.
### Fixed
- Fixed [#18](https://github.com/FunplayAI/funplay-cocos-mcp/issues/18): corrected the built-in UI Skill's UI system overview link to the working Cocos Creator 3.8 manual URL, while retaining valid component reference links. Upgraded the UI Skill template to v2 and preserved recognition of unmodified v1 installs as updateable, including those without managed metadata.
## [0.5.2] - 2026-09-03
### Added
- Added one-click MCP client configuration for Qoder and Kimi Code, including their documented custom configuration-directory environment variables.
- Added a dashboard alert that names built-in project Skills that are not installed, have updates available, or contain local modifications, with a direct link to Project Skills management.
## [0.5.1] - 2026-08-18
### Fixed
- Normalize every cloned node produced by `create_prefab_from_node` to Cocos Creator's `UI_2D` layer (`33554432`) before serialization, while leaving the source scene hierarchy unchanged.
- Reject generated Prefab content whose serialized `cc.Node._layer` values do not match `UI_2D` before writing the asset.
## [0.5.0] - 2026-08-18
### Added
- Added a dedicated **Project Skills** panel for listing project-local Codex skills, independently installing and updating both built-in Funplay skills, previewing template differences, backing up updates, restoring the latest backup, and creating custom skills.
- Added the built-in `funplay-cocos-ui-composition` Skill for Cocos-native responsive UI work across `UITransform`, `Widget`, `SafeArea`, `Layout`, scrolling, text, input, animation, prefabs, and performance validation.
- Added managed per-Skill template version/hash metadata so MCP upgrades can report built-in Skill updates without silently replacing local changes.
### Changed
- Generate project Skills with standard `SKILL.md` YAML frontmatter containing `name` and `description`.
- Expanded `funplay-cocos-mcp-workflow` from a short checklist into a complete inspect/edit/readback/diagnostics/preview workflow adapted from the proven Funplay Unity MCP Skill structure.
- Preserve existing UI and gameplay-object Prefabs by default, editing only necessary nodes/components unless a full rebuild is explicitly requested.
### Fixed
- Fixed [#17](https://github.com/FunplayAI/funplay-cocos-mcp/issues/17): `create_prefab_from_node` now assigns unique `cc.PrefabInfo` and `cc.CompPrefabInfo` metadata before serialization and rejects incomplete output, allowing generated Prefabs to open in Cocos Creator's Prefab editor.
## [0.4.7] - 2026-08-10
### Added
- Added a checksum-verified **Install for All Projects** workflow that installs the latest release into the active Cocos Creator version's managed global extension directory, asks Creator to scan and register it without replacing a running project copy, detects conflicts, and makes it automatically available to projects opened with that Creator version.
### Fixed
- Targeted Cocos Creator 3.8's version-scoped `builtin-extensions/<version>` directory instead of the legacy user extension path.
- Kept the active project copy running after global registration so MCP Settings can report the installed global version and duplicate-copy guidance without being unloaded mid-install.
## [0.4.6] - 2026-07-30
### Fixed
- Fixed [#6](https://github.com/FunplayAI/funplay-cocos-mcp/issues/6): browser preview results now default `url` and `localUrl` to a same-host loopback address while preserving Cocos Creator's reported LAN address in `networkUrl` and `reportedUrl`.
## [0.4.5] - 2026-07-27
### Fixed
- Fixed [#5](https://github.com/FunplayAI/funplay-cocos-mcp/issues/5): create and verify genuinely linked Prefab instances, include the required `cc.Prefab` node type, and clean up nodes that fail post-creation linkage checks.
## [0.4.4] - 2026-07-20
### Added
- Added English and Chinese localization for extension menus, panel titles, controls, status messages, prompts, and empty states.
- Added a project-level language setting with `Auto / 跟随 Cocos Creator`, `中文`, and `English` options.
- Added Chinese descriptions and localized profile labels for all 105 tools shown in the Tool Exposure window while preserving MCP tool IDs and schemas in English.
### Optimized
- Kept the four focused management windows on one shared localization layer so language changes remain consistent across dashboard, tool exposure, settings, and activity workflows.
- Prevented interface-only configuration changes, including language selection, from rebuilding MCP runtime state or clearing activity logs.
### Fixed
- Fixed 12-hour timestamps such as `11:37:12 PM` overlapping tool names in the Activity window.
## [0.4.3] - 2026-07-16
### Added
- Added `get_preview_mode` and `set_preview_mode` with explicit `browser`, `gameView`, and `simulator` semantics.
### Changed
- Reworked `run_project_preview` to use the Cocos Creator 3.8.x preview APIs, return the effective mode and browser preview URL, and retain `platform` as a deprecated alias for `mode`.
### Fixed
- Fixed [#3](https://github.com/FunplayAI/funplay-cocos-mcp/issues/3): restored preview launch on Cocos Creator 3.8.8 by replacing the nonexistent `preview.start`, `preview.open-preview`, and `builder.preview` messages.
## [0.4.2] - 2026-07-12
### Added
- Added `create_scene` to the default `core` profile for creating an empty scene or copying the active scene directly to an assets path without an interactive save dialog.
### Optimized
- Expanded the default `core` profile to 38 tools and the `full` profile to 103 tools, with synchronized English, Chinese, and generated tool documentation.
### Fixed
- Fixed `run_script_diagnostics` returning `spawn EINVAL` on Windows by running the TypeScript compiler script through Node instead of launching `tsc.cmd` directly.
- Fixed TypeScript diagnostics inside Cocos Creator incorrectly treating the Creator executable as a normal Node runtime, which could report a false successful result without running `tsc`.
## [0.4.1] - 2026-07-02
### Added
- Added `create_prefab_from_node`, a Cocos Creator 3.8.x-friendly prefab creation tool that serializes a scene node in the scene process and persists the prefab through asset-db instead of relying on the brittle `scene:create-prefab` message.
- Added automatic release checks and panel actions for opening the latest GitHub Release or installing a verified update package.
- Added a checksum-verified one-click updater that downloads the release zip, verifies `SHA256SUMS.txt`, backs up the current extension, replaces package files, and reloads the extension when the Cocos package API supports it.
- Added focused Cocos panel windows for Tool Exposure, MCP Settings, and Activity & Logs, with the main MCP Server panel reduced to a dashboard-style workflow.
- Added a Unity MCP-style Tool Exposure window with grouped tool lists, per-tool toggles, category select/clear actions, and a single-card Recent Activity stream with status badges.
### Fixed
- Treat undefined editor message responses as inconclusive for prefab creation and verify the resulting prefab file/asset before reporting success.
- Refuse one-click updates for symlink or git-worktree extension installs so local development checkouts are not overwritten accidentally.
## [0.4.0] - 2026-06-11
### Added
- Added project identity metadata to `/health` and MCP `initialize` responses so clients and duplicate listeners can verify the active Cocos project safely.
- Added same-project listener attach behavior before port fallback, preventing accidental attachment to a different Cocos project on the same port.
- Added default-on JavaScript safety checks for `execute_javascript`, `execute_scene_script`, and `execute_editor_script`, with per-call `safety_checks` overrides.
- Added named tool profiles in the Cocos panel, including save, apply, delete, import, and export workflows.
- Added category-level tool exposure controls in the panel for quick enable, disable, and clear actions.
- Added asset dependency tools: `inspect_asset_dependencies` and `validate_asset_dependencies`.
- Added Cocos project/editor tools: `get_build_status`, `open_build_panel`, `run_project_preview`, `save_current_scene`, `get_editor_preference`, `set_editor_preference`, and `broadcast_editor_message`.
- Added Button event binding tools: `list_button_click_events` and `bind_button_click_event`.
- Added `create_cocos_mcp_project_skill` for generating a recommended local Codex workflow skill.
- Added release package sensitive-content scanning for npm/GitHub/MCP token-like values and private keys.
### Optimized
- Improved tool exposure UX for larger projects by making custom profiles reusable and shareable.
- Expanded generated tool documentation and README coverage for the new 37-tool `core` profile and 101-tool `full` profile.
- Improved release packaging confidence with checksum verification and content scanning.
### Changed
- Expanded the default `core` profile from 34 tools to 37 tools.
- Expanded the `full` profile from 89 tools to 101 tools.
- Split more tool implementations into focused modules under `lib/tools/`, including advanced assets, Cocos project/editor helpers, and scene event helpers.
- Persisted `executeJavascriptSafetyChecks`, active tool profile names, and saved tool profiles in project configuration.
### Fixed
- Fixed the GitHub Release workflow so release pages use generated English changelog-style `RELEASE_NOTES.md` instead of the artifact installation README.
- Fixed release package scanning false positives around normal MCP server config names while preserving credential detection.
### Security
- Added guardrails for JavaScript execution against obvious risky file-system and shell patterns, including delete/truncate calls, raw writable streams, path traversal, user/system absolute paths, and `child_process`.
## [0.3.3] - 2026-05-20
### Added
- Added generated tool reference documentation in `docs/TOOLS.md`.
- Added `docs:generate` and `docs:check` scripts to keep tool counts, profiles, categories, and descriptions synchronized with `lib/tool-registry.js`.
- Added a read-only `GET /tools` debug endpoint with curl examples for quick local troubleshooting.
- Added panel activity previews for recent tool calls and runtime logs.
- Added panel curl copy actions for `/health` and `/tools`.
### Optimized
- Added CI and release validation for generated tool documentation.
- Improved the MCP client config panel so the preview follows the selected client target.
- Improved the panel information architecture around troubleshooting and maintenance: version, update status, tool profile, client config, recent calls, and logs.
### Changed
- Refined tool category inference so `get_tool_catalog` is grouped with project/context tools.
- Split file-system tools and asset refresh helpers into `lib/tools/files.js` as the first registry modularization step.
### Fixed
- No runtime bug fixes in this release; this release focuses on product polish, debugging ergonomics, and maintainability.
## [0.3.2] - 2026-05-20
### Added
- Added an npm-installable `funplay-cocos-mcp` stdio wrapper that bridges MCP clients to the local Cocos HTTP endpoint.
- Added MCP Registry metadata in `server.json`, including npm package ownership metadata via `mcpName`.
- Added wrapper tests, npm pack dry-run verification, and registry validation scripts.
## [0.3.1] - 2026-05-20
### Added
- Added a documented release workflow and release checklist for Cocos extension publishing.
- Added release packaging scripts that generate a Cocos extension zip, release manifest, checksum file, and per-release README.
- Added CI validation for release metadata.
## [0.3.0] - 2026-05-20
### Added
- Added MCP `outputSchema` and `annotations` to listed tools.
- Added a standard structured tool result envelope with `ok`, `tool`, `callId`, `summary`, `data`, and follow-up `refs`.
- Added prefab workflow tools: `inspect_prefab`, `validate_prefab_references`, `duplicate_prefab`, `edit_prefab_json`, `create_prefab_instance`, `inspect_prefab_instance`, `apply_prefab_instance`, and `revert_prefab_instance`.
- Added `get_performance_snapshot` and expanded `validate_scene` with scene scale/performance-oriented counters.
- Added project AI instruction tools: `list_project_instructions`, `read_project_instruction`, `write_project_instruction`, and `create_project_skill`.
- Added tests for tool metadata, result envelopes, and project instruction helpers.
### Changed
- Expanded the default `core` profile from 28 tools to 34 tools.
- Expanded the `full` profile from 76 tools to 89 tools.
- Updated tool interaction logs to store concise result summaries from the standard envelope.
## [0.2.0] - 2026-05-20
### Added
- Added a panel and tool-level update checker for comparing the installed extension version with the latest GitHub release.
- Added `custom` tool exposure with per-category and per-tool include/exclude configuration.
- Added `get_tool_catalog`, `check_for_updates`, `get_recent_logs`, `search_project_logs`, `clear_logs`, and `validate_scene`.
- Added MCP log resources: `cocos://logs/editor` and `cocos://logs/project`.
- Added in-memory runtime logs alongside the existing MCP interaction history.
- Added optional Streamable HTTP session support via `enableSessions` and `Mcp-Session-Id`.
### Changed
- Expanded the default `core` profile from 22 tools to 28 tools.
- Expanded the `full` profile from 70 tools to 76 tools.
- Updated the Cocos panel to show installed version, update status, session toggle, and tool exposure controls.
- Tightened Streamable HTTP behavior for `Accept` headers, JSON-RPC notifications/responses, `202 Accepted`, unsupported GET/SSE requests, and DELETE session termination.
### Fixed
- Improved project log tailing so trailing blank lines do not hide the last useful log entries.
## [0.1.4] - 2026-05-11
### Fixed
- Fixed CI test expectations after expanding the documented `core` and `full` tool profiles.
- Aligned the latest release line with the current tested `main` branch state.
## [0.1.3] - 2026-05-11
### Added
- Added `get_editor_state` as a compact structured editor-state summary tool.
- Added `get_selection` and `set_selection` as explicit selection workflow tools for editor-side automation.
- Added persistence for the selected one-click MCP client target in the Cocos panel configuration.
### Changed
- Expanded the default `core` profile from 19 tools to 22 tools by promoting editor-state and selection workflows.
- Expanded the `full` profile from 67 tools to 70 tools.
- Updated panel config persistence so changing the selected MCP client target no longer restarts the server unnecessarily.
## [0.1.2] - 2026-04-30
### Added
- Added Node.js unit tests for MCP protocol negotiation, tool profile exports, tool execution errors, and project file path safety.
### Changed
- Updated the MCP initialize response to negotiate protocol version `2025-11-25` by default while retaining compatibility with older supported protocol versions.
- Added `structuredContent` to tool call results when a tool returns structured JSON data.
- Changed tool execution failures to return MCP tool errors instead of JSON-RPC internal errors, improving client-side self-correction.
- Updated CI to run the new Node.js test suite.
### Security
- Restricted project file and asset-path resources to paths inside the active Cocos project root.
- Added HTTP request body size limits and invalid `Origin` header rejection for the embedded MCP server.
## [0.1.1] - 2026-04-16
### Added
- Added automatic port fallback when the configured MCP port is already occupied.
- Added actual-running-port reporting in MCP server status and panel state.
- Added `.github/pull_request_template.md` for repository contribution guidance.
- Added `.github/workflows/ci.yml` for lightweight GitHub validation.
- Added a lightweight GitHub Star promotion log after successful MCP server startup.
### Changed
- Updated one-click MCP client configuration to write the actual running server port instead of the requested port when port fallback is active.
- Updated the MCP panel status line to show configured-port to actual-port fallback information.
- Updated the English and Chinese README files to document automatic port fallback behavior.
### Fixed
- Fixed VS Code one-click configuration to use platform-specific config paths with macOS fallback behavior.
- Fixed Windows one-click MCP configuration path resolution by using a more reliable home/appdata lookup strategy.
## [0.1.0] - 2026-04-15
### Added
- Embedded HTTP MCP server inside a Cocos Creator extension.
- `Funplay > MCP Server` editor panel for service management and one-click MCP client configuration.
- One-click configuration support for Claude Code / Claude Desktop, Cursor, VS Code, Trae, Kiro, and Codex.
- Primary unified tool: `execute_javascript`.
- `context: "scene"` for active scene/runtime automation.
- `context: "editor"` for Cocos editor/browser automation.
- Compatibility execution tools:
- `execute_scene_script`
- `execute_editor_script`
- MCP protocol capabilities:
- `initialize`
- `tools/list`
- `tools/call`
- `resources/list`
- `resources/read`
- `resources/templates/list`
- `prompts/list`
- `prompts/get`
- `core` tool profile with 19 high-signal tools.
- `full` tool profile with 67 tools.
- Scene and hierarchy inspection tools.
- Node, component, UI, camera, animation, prefab, and asset tools.
- File read/write/search tools and asset refresh helpers.
- TypeScript diagnostic tools for Cocos projects.
- Runtime state and time-scale control tools.
- Button, node event, component method, mouse, keyboard, and preview input simulation tools.
- Desktop, editor, scene, game, and preview screenshot tools.
- MCP resources for project context, scene state, selection, script errors, and interaction history.
- MCP prompts for script repair, playable prototype creation, scene validation, and scene auto-wiring.
- Debug logs for server lifecycle events.
- English and Chinese README files.
- MIT license file.
### Changed
- Promoted `execute_javascript` as the recommended primary tool across tool descriptions, prompts, and documentation.
- Simplified the Cocos panel to focus on service management and MCP client configuration.
- Changed the menu entry to `Funplay > MCP Server`.
- Slimmed the default `core` profile from 50 tools to 19 high-signal tools centered on project understanding, diagnostics, and visual validation.
### Fixed
- Fixed panel initialization issues caused by unsafe DOM querying.
- Fixed relative-path handling for asset open/select workflows.
- Fixed bundled Cocos TypeScript diagnostic lookup.
- Improved scene/game screenshot targeting with panel-level cropping when available.
- Improved low-level mouse drag coordinates for panel-relative input injection.
+112
View File
@@ -0,0 +1,112 @@
# Contributing to Funplay MCP for Cocos
Thanks for your interest in contributing to Funplay MCP for Cocos.
This repository is a Cocos Creator editor extension that embeds an MCP server. Contributions that improve reliability, editor compatibility, documentation, and AI-driven Cocos workflows are welcome.
## Development Setup
1. Clone the repository:
```bash
git clone https://github.com/FunplayAI/funplay-cocos-mcp.git
cd funplay-cocos-mcp
```
2. Install it into a Cocos project as an extension:
```bash
mkdir -p /path/to/your-cocos-project/extensions
ln -s "$PWD" /path/to/your-cocos-project/extensions/funplay-cocos-mcp
```
You can also copy the repository folder instead of using a symlink.
3. Restart Cocos Creator or reload extensions.
4. Open the panel:
```text
Funplay > MCP Server
```
## Validation
Before opening a pull request, run:
```bash
npm run check
```
This validates the JavaScript syntax for the extension entry points and helper modules.
If your change affects live MCP behavior, also test against a running Cocos project:
```bash
curl -sS http://127.0.0.1:8765/health
```
If you use a custom port, replace `8765` with your configured port.
## Project Structure
```text
browser.js Cocos browser/editor extension entry and service lifecycle
scene.js Scene-side execution bridge and scene tool implementations
panel/index.js Minimal MCP Server panel UI
lib/server.js HTTP JSON-RPC MCP server
lib/tool-registry.js Tool definitions and handlers
lib/resources.js MCP resources
lib/prompts.js MCP prompts
lib/client-config.js One-click MCP client configuration
lib/assets.js Asset database helpers
lib/diagnostics.js TypeScript diagnostics
lib/input.js Electron input simulation
lib/screenshots.js Screenshot helpers
```
## Contribution Guidelines
- Keep the `core` profile focused. Avoid adding noisy tools to `core` unless they are broadly useful for AI clients.
- Prefer improving `execute_javascript` workflows when one flexible tool is better than many narrow tools.
- Add tools to `full` when they are useful but not essential for the default AI workflow.
- Keep the Cocos panel simple. The main panel should focus on service management and MCP client configuration.
- Avoid adding runtime dependencies to built games; this extension should remain editor-only.
- Keep changes small and focused.
- Update `README.md`, `README_CN.md`, or `CHANGELOG.md` when behavior changes.
- Do not commit generated Cocos folders such as `library/`, `temp/`, or build output.
## Tool Design Notes
When adding a new tool:
1. Add the tool definition in `lib/tool-registry.js`.
2. Use `profile: "core"` only for high-signal tools.
3. Put scene/runtime work behind `sceneBridge.call(...)` when it must run in the active Cocos scene.
4. Use editor-side helpers for asset-db, filesystem, and panel/client configuration workflows.
5. Return JSON-serializable data where possible.
6. Add clear input schema descriptions so AI clients can choose the tool correctly.
7. Test the tool with `tools/list` and `tools/call`.
## Documentation
The documentation is bilingual:
- `README.md` for English
- `README_CN.md` for Chinese
When adding user-facing behavior, update both files when possible.
## Pull Requests
A good pull request should include:
- A clear summary of the change
- What Cocos Creator version was tested
- Whether the MCP server was tested through an AI client or direct HTTP calls
- Any screenshots if the change affects the panel or visual scene output
- Notes about compatibility or limitations
## License
By contributing, you agree that your contributions will be licensed under the MIT License used by this repository.
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Funplay
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+709
View File
@@ -0,0 +1,709 @@
<p align="center">
<h1 align="center">Funplay MCP for Cocos</h1>
<p align="center">
<strong>An Embedded MCP Server for Cocos Creator Editor</strong>
</p>
<p align="center">
<a href="#"><img src="https://img.shields.io/badge/Cocos%20Creator-3.8%2B-blue" alt="Cocos Creator 3.8+"></a>
<a href="#"><img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT"></a>
<a href="#"><img src="https://img.shields.io/badge/MCP-Compatible-green" alt="MCP Compatible"></a>
<a href="#"><img src="https://img.shields.io/badge/Platform-Editor%20Only-orange" alt="Editor Only"></a>
<a href="https://store.cocos.com/app/detail/8913"><img src="https://img.shields.io/badge/Cocos%20Store-Install-brightgreen" alt="Install from Cocos Store"></a>
</p>
<p align="center">
<a href="./README_CN.md">中文</a> | English
</p>
</p>
> If this project helps your Cocos workflow, please consider giving it a Star. It helps more developers discover the project and supports ongoing development.
For discussion and feedback, join our QQ group: **1108522331**. Open **Funplay > Contact & Feedback** to find the author's email and copy either contact detail.
---
Funplay MCP for Cocos is an MIT-licensed Cocos Creator extension that embeds an HTTP MCP server directly inside the editor. It lets AI assistants such as Claude Code, Cursor, Codex, VS Code Copilot, Trae, Antigravity, Pi, Kiro, Qoder, Kimi Code, OpenCode, CodeBuddy, and DeepSeek Harness (DSH) inspect and operate your running Cocos project.
The package follows the same product direction as Funplay MCP for Unity: keep the default tool surface focused, provide a one-click client configuration window, and make one high-flexibility execution tool the primary workflow.
For Cocos, the primary tool is `execute_javascript`:
- `context: "scene"` runs JavaScript in the active Cocos scene/runtime context
- `context: "editor"` runs JavaScript in the Cocos editor/browser context
> *"Create a login page UI with account/password fields and a main login button."*
>
> Your AI assistant can call `execute_javascript`, build the UI hierarchy under the active Canvas, attach Cocos components, inspect the result, and capture a screenshot for validation.
## Quick Start
If you just want to connect quickly, do these three things:
- Install this repository as a Cocos Creator extension
- Open `Funplay > MCP Server`
- Use the built-in one-click MCP client configuration
### 1. Install as a Cocos Creator Extension
Recommended install: use the official [Cocos Store page](https://store.cocos.com/app/detail/8913) and install the extension into your target Cocos Creator project.
For local development or unreleased builds, clone or copy this repository into your Cocos project extension directory:
```bash
cd /path/to/your-cocos-project
mkdir -p extensions
git clone https://github.com/FunplayAI/funplay-cocos-mcp.git extensions/funplay-cocos-mcp
```
Then restart Cocos Creator or reload extensions from the editor.
For a non-git install, download `Funplay.CocosMcp.v<version>.zip` from the GitHub Releases page, unzip it, and move the extracted `funplay-cocos-mcp` folder into your project `extensions/` directory.
#### Install for All Projects (Recommended)
Install and open the extension in any project first. Then open `Funplay > MCP Settings` and click **Install for All Projects** in the All Projects section. The extension downloads the latest GitHub Release, verifies `SHA256SUMS.txt`, and installs it into the active Cocos Creator version's managed global extension directory:
- macOS / Linux: `~/.CocosCreator/builtin-extensions/<Creator version>/funplay-cocos-mcp`
- Windows: `%USERPROFILE%\.CocosCreator\builtin-extensions\<Creator version>\funplay-cocos-mcp`
Cocos Creator scans and registers the installed copy immediately. Projects opened or created with that Creator version then load it automatically, and the MCP server keeps its default autostart behavior. Reopen an already-running project if its project-level copy has priority. No extension files are copied into each project's `extensions/` directory.
Global extensions are isolated by Cocos Creator version. If you use multiple Creator versions, run **Install for All Projects** once from each version.
The installer does not delete the current project copy, which protects development worktrees. If both copies exist, MCP Settings shows a duplicate-install warning. After confirming that the global copy works, remove or disable the project copy to avoid extension conflicts.
### 2. Start the MCP Server
Open the editor menu:
```text
Funplay > MCP Server
```
New projects get a stable project-derived port in `20000–29999`. Existing saved configurations keep their fixed port (including `8765`). Use the exact URL shown in MCP Server; if a temporary fallback port is active, click **Pin Current Port** or **Use Per-Project Port** before configuring a client.
If the configured port is already occupied, the extension first checks whether the existing listener belongs to the same Cocos project. Same-project listeners are reused safely; unrelated listeners trigger automatic fallback to the next available local port.
The panel is intentionally small:
- Enable or disable the MCP server
- Open focused Tool Exposure, MCP Settings, and Project Skills windows
- Automatically check the installed version against the latest GitHub release
- Open the release page or install verified release packages from the panel
- Install once in the Cocos Creator global extensions directory so existing and new projects can use it automatically
- Configure AI clients with one click and preview the selected client config
- Keep advanced tool profile editing, transport settings, and installation management out of the main server window
- Follow the Cocos Creator interface language automatically, or select Chinese/English per project in MCP Settings
- Toggle **Print MCP logs** in Settings to silence MCP console messages without losing Recent Activity or internal diagnostics
All management pages use consistent headings, aligned controls, and lightweight sections. Tool Exposure groups per-tool toggles by category; Project Skills highlights available actions and folds away file paths and backups. Recent Activity shows each call's summary and actual result as an expandable object/array tree, with execution logs and return values in separate sections for scripts. Output sections and the standalone log-viewing panel are removed. Short action notices preserve success/failure feedback, while diagnostic logs remain available to MCP tools and resources.
Script tools capture per-call `console.log/info/warn/error/debug` output, including logs before a failure, independently of **Print MCP logs**. Capture is isolated across concurrent and nested calls and stops when the script settles; global/project logs and logs from separately required modules are not collected. Use the injected `console` (also available as `env.console` in `run`/module exports). MCP responses retain their existing `data` shape and add optional `execution` metadata with context, duration, bounded/redacted logs, and an omitted-entry count. Recent Activity preserves result hierarchy and scalar values; large results and file/script bodies remain limited or omitted, with truncation notices.
The extension menu and native panel titles follow the Cocos Creator interface language. Panel controls, tool descriptions, status messages, prompts, and empty states support English and Chinese; open `Funplay > MCP Settings` to follow Creator or set a project-specific content-language override. MCP tool IDs and schemas remain in English so client integrations stay stable.
### 3. Configure Your AI Client
Use the built-in **MCP Client Config** section in the `Funplay > MCP Server` panel first.
Select your target client, click **One-Click Configure**, and the extension writes the recommended MCP config entry for you.
The MCP server name written to clients is:
```text
cocos-<project>-<hash>
```
If you prefer to edit config files manually, use the examples below as fallback references. Replace their legacy `funplay_cocos` name and `8765` port with the name and URL shown in your panel. One-click Claude Code configuration uses the project's Git-root scope in `~/.claude.json`, not the global example below. See [project setup and migration](docs/PROJECT_WORKFLOWS.md).
<details>
<summary>Claude Code / Claude Desktop</summary>
```json
{
"mcpServers": {
"funplay_cocos": {
"type": "http",
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>Cursor</summary>
```json
{
"mcpServers": {
"funplay_cocos": {
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>VS Code</summary>
One-click setup writes the user-profile `mcp.json` using VS Code's `servers` format and preserves JSONC comments. It uses `~/Library/Application Support/Code/User` on macOS, `%APPDATA%/Code/User` on Windows, and `$XDG_CONFIG_HOME/Code/User` (default `~/.config/Code/User`) on Linux, with `VSCODE_PORTABLE` / `VSCODE_APPDATA` overrides. **Configure + Skills** installs project Skills in [`.github/skills`](https://code.visualstudio.com/docs/agent-customization/agent-skills).
```json
{
"servers": {
"funplay_cocos": {
"type": "http",
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>Trae</summary>
One-click setup writes `<Cocos project>/.trae/mcp.json`, following [Trae's project MCP configuration](https://docs.trae.cn/ide_add-mcp-servers). Open this Cocos folder in Trae and enable **Project MCP** in **Settings > MCP**. This target no longer writes `~/.trae/mcp.json`. **Configure + Skills** installs missing built-ins into [`.trae/skills`](https://docs.trae.cn/ide_skills).
```json
{
"mcpServers": {
"funplay_cocos": {
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>Antigravity</summary>
One-click setup writes the active Cocos project's `.agents/mcp_config.json` using `mcpServers` and `serverUrl` for Streamable HTTP. Open this Cocos folder in Antigravity and reload its MCP configuration. **Configure + Skills** installs missing built-ins into `.agents/skills`, the project directory shared with Codex. [MCP configuration](https://antigravity.google/docs/mcp/) · [Project Skills](https://antigravity.google/docs/skills/)
```json
{
"mcpServers": {
"cocos-demo-012345": {
"serverUrl": "http://127.0.0.1:8765/mcp/project/0123456789abcdef01234567/"
}
}
}
```
</details>
<details>
<summary>Pi (1.0+)</summary>
Select **Pi** under **Funplay > MCP Server**. One-click setup saves the project's Streamable HTTP URL in `.pi/mcp.json`. **Configure + Skills** installs missing built-ins into `.agents/skills`, shared with Codex and Antigravity. [Pi MCP configuration](https://docs.pi.dev/latest/mcp) · [Pi Skills](https://docs.pi.dev/latest/skills)
Start `pi` from the Cocos project directory and trust the project when prompted. In an already trusted session, run `/reload` and check `/mcp` for connection status.
```json
{
"mcpServers": {
"cocos-demo-012345": {
"url": "http://127.0.0.1:8765/mcp/project/0123456789abcdef01234567/"
}
}
}
```
</details>
<details>
<summary>Kiro</summary>
One-click MCP setup uses `~/.kiro/settings/mcp.json`. **Configure + Skills** also installs missing built-ins in the project's [`.kiro/skills`](https://kiro.dev/docs/skills/) directory.
```json
{
"mcpServers": {
"funplay_cocos": {
"type": "http",
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>Qoder</summary>
The user-level configuration is written to `~/.qoder/settings.json`, or to `$QODER_CONFIG_DIR/settings.json` when that environment variable is set.
```json
{
"mcpServers": {
"funplay_cocos": {
"type": "http",
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>Kimi Code</summary>
The user-level configuration is written to `~/.kimi-code/mcp.json`, or to `$KIMI_CODE_HOME/mcp.json` when that environment variable is set.
```json
{
"mcpServers": {
"funplay_cocos": {
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>Codex</summary>
One-click setup uses `$CODEX_HOME/config.toml`, defaulting to `~/.codex/config.toml`, following [Codex's configuration directory](https://learn.chatgpt.com/docs/config-file/config-advanced#config-and-state-locations). An empty `[mcp_servers]` parent followed by explicit server tables is supported; inline MCP tables still require manual editing.
```toml
[mcp_servers.funplay_cocos]
url = "http://127.0.0.1:8765/"
```
</details>
<details>
<summary>OpenCode</summary>
The global config lives in `$XDG_CONFIG_HOME/opencode/opencode.json` or `~/.config/opencode/opencode.json` on every platform (`opencode.jsonc` also works).
One-click configuration prefers an existing `opencode.jsonc`. It supports comments and trailing commas in either file, preserves unrelated settings and comments, and leaves malformed or ambiguous configurations unchanged.
Existing [OpenCode V2](https://opencode.ai/docs/mcp-servers) `mcp.servers` configurations keep that nested structure. New files use the flat `mcp` map below for V1 compatibility; the current [OpenCode schema](https://opencode.ai/config.json) also accepts that legacy form. Setup does not migrate custom timeout/authentication options between formats.
```json
{
"mcp": {
"funplay_cocos": {
"type": "remote",
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>CodeBuddy (IDE 4.0+)</summary>
One-click setup writes `<Cocos project>/.mcp.json`, the project configuration supported by [CodeBuddy IDE 4.0+](https://intl.cloud.tencent.com/zh/document/product/1256/77264). It preserves other servers, comments, and trailing commas. Open this Cocos project folder as the CodeBuddy workspace, reload the client if necessary, and enable/approve the MCP server when prompted. Older IDE versions and the standalone CodeBuddy editor extension have different configuration locations; this target does not write their global settings or the CLI's global files.
**Configure + Skills** also installs missing built-in Skills into `<Cocos project>/.codebuddy/skills`, following the [official Skills directory](https://www.codebuddy.cn/docs/ide/Features/Skills). Existing Skills are kept; review updates in **Project Skills**.
```json
{
"mcpServers": {
"funplay_cocos": {
"type": "http",
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>DeepSeek Harness (DSH)</summary>
Select **DeepSeek Harness (DSH)** in the MCP Server panel. Configure generates `<Cocos project>/.dsh/funplay-cocos-mcp.patch.json`, a JSON-formatted YAML overlay for the [official Cordis MCP client](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/mcp/mcp-client/README.md). It does not change `$DSH_HOME`, global/profile YAML, dependencies, credentials, or approval settings.
**The overlay is not auto-loaded.** Start DSH from the Cocos project directory using the exact command shown in the panel, or add its `--patch` argument to your existing DSH launch command. For example, with `dsh` installed:
```sh
dsh web --patch '/absolute/path/to/cocos-project/.dsh/funplay-cocos-mcp.patch.json'
```
When launching through npm, use `npx @deepseek-ai/dsh web --patch <the same absolute path>`. Other official profiles can use the same overlay through `--patch`; third-party desktop launchers may require their own launch configuration. Keep Cocos and its MCP server running. The generated overlay uses the project's actual server name and URL, not the legacy example name/port.
**Configure + Skills** also installs missing built-ins under `<nearest Git root>/.dsh/skills`, or under the Cocos project when no Git root exists, following [DSH's filesystem Skills provider](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/skill/skill-filesystem/README.md). Existing copies remain protected and can be reviewed in Project Skills. Multiple Cocos projects inside one Git repository share that Skills root but have separate MCP overlays.
</details>
### Optional: npm stdio Wrapper
If your MCP client prefers a local `stdio` command, install the npm wrapper after starting the Cocos editor server:
```bash
npm install -g funplay-cocos-mcp
```
Example MCP client entry:
```json
{
"mcpServers": {
"funplay_cocos": {
"command": "funplay-cocos-mcp",
"env": {
"FUNPLAY_COCOS_MCP_URL": "http://127.0.0.1:8765/"
}
}
}
}
```
The wrapper bridges stdio MCP traffic to the embedded Cocos HTTP endpoint. You can also run it with `npx funplay-cocos-mcp --url http://127.0.0.1:8765/`.
The stdio transport supports standard newline-delimited UTF-8 JSON-RPC messages (NDJSON). The wrapper also accepts the existing `Content-Length` framing and writes responses using the same framing as the incoming message.
### 4. Verify the Connection
Open your AI client and try a few safe requests first:
- "Call `get_project_info` and summarize the current Cocos project."
- "Read `cocos://project/context` and tell me the editor status."
- "Use `execute_javascript` with `context: \"scene\"` to return the active scene name."
- "Use `execute_javascript` with `context: \"editor\"` to return the project path."
If these work, the MCP server, resources, prompts, and primary execution tool are connected correctly.
For local transport debugging, the panel can copy these commands, or you can run them directly:
```bash
curl http://127.0.0.1:8765/health
curl http://127.0.0.1:8765/tools
```
### 5. Start Building
Try a higher-level prompt in your AI client:
> Create a login page UI in the current Cocos scene with account/password fields, a login button, and a guest-login button. Use `execute_javascript` first, inspect the hierarchy, then capture a screenshot.
## Before You Start
- This extension is **Editor-only**. It is meant to automate Cocos Creator, not to add runtime dependencies to your final game build.
- New projects use a project-derived port. The MCP Server dashboard shows the exact endpoint and supports pinning a fixed port.
- If the configured port is busy, the server automatically falls back to the next available port and the panel/client config use the actual running port.
- `GET /health` and `GET /tools` are read-only debug endpoints for quick local checks outside an MCP client.
- The default `core` profile exposes 39 high-signal tools. Switch to `full` for all 106 tools, or use `custom` to include/exclude tool categories and individual tools.
- The panel checks GitHub releases automatically and also supports manual checks.
- One-click update downloads the GitHub Release zip, verifies `SHA256SUMS.txt`, backs up the current extension, replaces the package files, and reloads the extension when the Cocos package API supports it. If reload is unavailable, restart Cocos Creator after installation. Git worktree and symlink installs are intentionally left to manual `git pull` or package replacement.
- **Install for All Projects** uses the same release and SHA256 verification flow, targets the active Creator version's managed global directory, then asks Creator to scan and register the package. It preserves an active project copy instead of switching packages underneath an open settings window; the global copy is enabled immediately when no project copy is active, or on the next project open otherwise.
- **Project Skills** manages the built-in `funplay-cocos-mcp-workflow` and `funplay-cocos-ui-composition` skills plus custom skills for all 13 one-click clients. The workflow skill is v4. The UI composition skill is v5 and covers splitting full-page designs into editable prefabs and checking fidelity by region. Version checks, diffs, backups, and restore include managed references, and user-owned reference files are protected. Codex, Antigravity, and Pi share `.agents/skills`. Codex and Antigravity can migrate their legacy built-ins while retaining the original files.
- Streamable HTTP responses follow the MCP transport requirements for `Accept`, `MCP-Protocol-Version`, JSON-RPC notifications/responses, and optional `Mcp-Session-Id` sessions.
- Tool listings include MCP `outputSchema` and `annotations`; structured tool results use a standard envelope with `ok`, `tool`, `callId`, `summary`, `data`, and follow-up `refs`.
- `execute_javascript` safety checks are enabled by default. They block obvious risky filesystem and shell patterns such as delete/truncate calls, raw writable streams, path traversal, user/system absolute paths, and `child_process`. This is a guardrail, not a full sandbox; a call can explicitly pass `safety_checks: false` when you have reviewed the risk.
- All exposed MCP tools execute directly. There is no extra approval toggle inside the Cocos extension.
- File tools and `cocos://asset/path/...` resources are restricted to the active Cocos project root.
- The recommended workflow is `execute_javascript` first, then focused helper tools for screenshots, diagnostics, assets, and inspection.
- If you change the server port or tool exposure in the panel, the extension saves the config and restarts the server when needed.
## Why This Project
- **`execute_javascript` First** — One high-flexibility JavaScript tool can orchestrate scene/runtime work and editor-side automation without flooding AI clients with too many narrow tool calls
- **Embedded Cocos Extension** — No separate Python daemon or external bridge process is required for the Cocos-side plugin
- **One-Click Client Configuration** — Configure Claude Code, Cursor, VS Code, Trae, Antigravity, Pi (1.0+), Kiro, Qoder, Kimi Code, Codex, OpenCode, and CodeBuddy (IDE 4.0+), or generate a DSH overlay with an explicit `--patch` launch command
- **Project Context Built In** — Exposes live project, scene, selection, script diagnostics, logs, and interaction-history resources
- **Focused by Default, Full When Needed** — `core` reduces tool-list noise; `full` exposes every available tool; `custom` plus saved profiles lets you tune and restore tool exposure by category or tool
- **Visual Validation** — Scene/editor/preview screenshots and input simulation help AI verify UI and gameplay changes
## Highlights
- **106 Built-in Tools** — Scene hierarchy, editor state, selection workflows, prefabs, assets, asset dependencies, project instructions, UI creation, components, files, logs, script diagnostics, screenshots, runtime control, build/preview helpers, editor preferences, event binding, and input simulation
- **Primary Unified Tool** — `execute_javascript` supports both `scene` and `editor` contexts
- **Resources & Prompts** — Live project/log resources plus reusable workflows like script fixing, scene validation, and playable prototype creation
- **Cocos Panel UI** — A compact `Funplay > MCP Server` dashboard plus focused Tool Exposure, MCP Settings, and Project Skills windows for larger workflows
- **Screenshot and Input Support** — Capture editor/scene/game/preview screenshots and send Electron-level mouse/keyboard events; mouse clicks/drags can use exact PNG pixels with a fresh screenshot `captureId`
- **Vendor Agnostic** — Works with any AI client that supports MCP over HTTP JSON-RPC
## Relationship to Funplay MCP for Unity
Funplay MCP for Cocos follows the same design principles as Funplay MCP for Unity, adapted to Cocos Creator's JavaScript/TypeScript editor environment.
| Area | Funplay MCP for Cocos | Funplay MCP for Unity |
|------|------------------------|------------------------|
| Editor integration | Cocos Creator extension | Unity Editor package |
| Embedded server | Built-in HTTP MCP server | Built-in HTTP MCP server |
| Primary execution tool | `execute_javascript` | `execute_code` |
| Primary language | JavaScript in scene/editor contexts | C# in Unity editor/runtime contexts |
| Default profile | `core` with 39 tools | `core` focused tool profile |
| Full profile | 106 tools plus `custom` exposure | 79 tools |
| Client setup | One-click config panel | One-click config window |
## MCP Capabilities
The current package exposes four capability layers:
- **Tools** — 39 tools in `core`, 106 tools in `full`, plus `custom` include/exclude rules and saved tool profiles
- **Primary execution** — `execute_javascript` for scene/runtime and editor/browser automation
- **Prompts** — `fix_script_errors`, `create_playable_prototype`, `scene_validation`, and `auto_wire_scene`, plus parameterized project workflows loaded from `mcp-prompts/*.md`. See [project isolation, Skills and workflow setup](docs/PROJECT_WORKFLOWS.md).
- **Resources** — project context, scene summaries, current selection, script diagnostics, asset selection, logs, and MCP interaction history
For the generated tool reference, including categories, profiles, and read/mutation hints, see [docs/TOOLS.md](./docs/TOOLS.md).
The default `core` set is intentionally small: `execute_javascript`, `execute_scene_script`, `execute_editor_script`, `get_editor_state`, `get_tool_catalog`, `check_for_updates`, `get_selection`, `list_project_instructions`, `read_project_instruction`, `set_selection`, `get_project_info`, `get_build_status`, `get_preview_mode`, `create_scene`, `get_scene_info`, `get_hierarchy`, `list_scenes`, `open_scene`, `inspect_prefab`, `validate_prefab_references`, `inspect_prefab_instance`, `list_assets`, `inspect_asset`, `inspect_asset_dependencies`, `validate_asset_dependencies`, `open_asset`, `select_asset`, `run_script_diagnostics`, `get_recent_logs`, `search_project_logs`, `clear_logs`, `validate_scene`, `get_performance_snapshot`, `get_script_diagnostic_context`, `get_runtime_state`, `capture_editor_screenshot`, `capture_scene_screenshot`, `capture_preview_screenshot`, and `list_editor_windows`.
### Preview Modes
Creator 3.8.x preview automation uses the same modes and editor APIs as the built-in preview toolbar:
| Mode | Behavior |
|------|----------|
| `browser` | Opens the scene in the system browser; `get_preview_mode` and `run_project_preview` return same-host and network preview URLs when available. |
| `gameView` | Starts the scene inside Cocos Creator's Game View. |
| `simulator` | Starts the scene in the native simulator. |
Use `get_preview_mode` to inspect the active mode, `set_preview_mode` to switch it, and `run_project_preview` to start it. `run_project_preview` still accepts `platform` as a deprecated alias for `mode`.
Game View starts through the native preview toolbar so its manual Pause/Resume buttons remain usable. Repeated starts leave an existing preview running (including its paused state). `pause_runtime` and `resume_runtime` control that same Game View preview and are idempotent; they require a running Game View and do not control browser/simulator previews or the edit-scene director. Switching away from Game View stops it through the toolbar first; rejected operations report an error instead of claiming success.
Enable these control tools in `full` or a custom tool profile. When scripting, prefer them over directly calling `scene.editor-preview-set-play`, which bypasses toolbar synchronization.
`get_runtime_state` (also used by `validate_scene`) reports `scope: "gameView"`, actual `running`/`paused` values, `busy`, and `toolbarSynchronized`. It no longer presents edit-scene frame/time-scale counters as preview state; those remain in `get_performance_snapshot.runtime` with `scope: "editScene"`. `set_time_scale` continues to affect only the edit scene. Preview controls require a compatible, ready Creator main-window toolbar; an unavailable toolbar produces an explicit error.
Browser preview results distinguish same-host automation from LAN access:
| Field | Meaning |
|-------|---------|
| `url` / `localUrl` | Loopback URL intended for an MCP client or browser running on the same computer as Cocos Creator. |
| `networkUrl` | Original non-loopback URL for another device on the same network; empty when Creator reports a loopback or wildcard host. |
| `reportedUrl` | Exact URL string reported by Cocos Creator before normalization. |
| `urlWarning` | Non-empty only when the reported value cannot be normalized as an absolute HTTP(S) URL. |
## Built-in Resources
| Resource | Description |
|----------|-------------|
| `cocos://project/context` | Full project and editor context |
| `cocos://project/summary` | Short project summary |
| `cocos://scene/active` | Active scene snapshot |
| `cocos://scene/current` | Alias for the current scene |
| `cocos://selection/current` | Current editor selection |
| `cocos://selection/asset` | Current selected asset |
| `cocos://errors/scripts` | Script diagnostics |
| `cocos://logs/editor` | Recent MCP runtime logs and tool interactions |
| `cocos://logs/project` | Recent tails from common project log files |
| `cocos://mcp/interactions` | Recent MCP interaction history |
## Built-in Tools
Funplay MCP for Cocos currently ships with **106 tool functions** in the `full` profile:
| Category | Tools |
|----------|-------|
| **Script Execution** | `execute_javascript`, `execute_scene_script`, `execute_editor_script` |
| **Editor State** | `get_editor_state`, `get_tool_catalog`, `check_for_updates`, `get_selection`, `set_selection`, `get_editor_selection` |
| **Project Instructions** | `list_project_instructions`, `read_project_instruction`, `write_project_instruction`, `create_project_skill`, `create_cocos_mcp_project_skill` |
| **Project & Scene** | `get_project_info`, `get_scene_info`, `get_hierarchy`, `find_nodes`, `inspect_node`, `list_scenes`, `open_scene`, `run_scene_asset` |
| **Node Editing** | `create_node`, `delete_node`, `set_node_transform` |
| **Assets & Prefabs** | `list_assets`, `inspect_asset`, `inspect_asset_dependencies`, `validate_asset_dependencies`, `check_asset_ready`, `open_asset`, `select_asset`, `delete_asset`, `list_prefabs`, `inspect_prefab`, `validate_prefab_references`, `duplicate_prefab`, `edit_prefab_json`, `create_prefab_from_node`, `create_prefab_instance`, `inspect_prefab_instance`, `apply_prefab_instance`, `revert_prefab_instance`, `instantiate_prefab` |
| **Components** | `list_components`, `inspect_component`, `add_component`, `remove_component`, `set_component_property`, `reset_component_property` |
| **UI** | `create_canvas`, `create_label`, `create_button`, `create_sprite` |
| **Camera** | `list_cameras`, `create_camera`, `set_camera_properties` |
| **Animation** | `list_animations`, `add_animation_clip`, `play_animation`, `stop_animation` |
| **Files** | `read_file`, `get_file_snippet`, `write_file`, `replace_in_file`, `search_files`, `list_directory`, `exists`, `refresh_assets` |
| **Diagnostics & Logs** | `run_script_diagnostics`, `get_script_diagnostic_context`, `get_recent_logs`, `search_project_logs`, `clear_logs`, `validate_scene`, `get_performance_snapshot` |
| **Build & Editor** | `get_build_status`, `get_preview_mode`, `set_preview_mode`, `open_build_panel`, `run_project_preview`, `save_current_scene`, `get_editor_preference`, `set_editor_preference`, `broadcast_editor_message` |
| **Runtime** | `get_runtime_state`, `pause_runtime`, `resume_runtime`, `set_time_scale` |
| **Interaction & Events** | `emit_node_event`, `simulate_button_click`, `list_button_click_events`, `bind_button_click_event`, `invoke_component_method`, `simulate_mouse_click`, `simulate_mouse_drag`, `simulate_key_press`, `simulate_key_combo`, `simulate_preview_input` |
| **Screenshots & Windows** | `capture_desktop_screenshot`, `capture_editor_screenshot`, `capture_scene_screenshot`, `capture_game_screenshot`, `capture_preview_screenshot`, `list_editor_windows` |
## Primary Tool Examples
### Scene Context
```json
{
"context": "scene",
"code": "return { sceneName: scene.name, rootCount: scene.children.length };",
"args": {}
}
```
### Editor Context
```json
{
"context": "editor",
"code": "return { projectPath: context.projectPath, toolCount: helpers.listTools().length };",
"args": {}
}
```
Editor-context scripts receive `Editor`, `fs`, `path`, `os`, `require`, `context`, `args`, and helper functions such as `helpers.getStatus()`, `helpers.listTools()`, `helpers.readResource(uri)`, `helpers.callTool(name, args)`, and `helpers.configureClient(targetId)`.
## Optional Configuration
Place `funplay-cocos-mcp.config.json` in the Cocos project root:
```json
{
"host": "127.0.0.1",
"port": 8765,
"toolProfile": "core",
"enabledToolCategories": [],
"disabledToolCategories": [],
"enabledTools": [],
"disabledTools": [],
"enableSessions": false,
"enableConsoleLogging": true,
"executeJavascriptSafetyChecks": true,
"autostart": true,
"maxInteractionLogEntries": 50,
"activeToolProfileName": "",
"savedToolProfiles": []
}
```
Environment variables are also supported:
- `COCOS_MCP_HOST`
- `COCOS_MCP_PORT`
- `COCOS_MCP_PROFILE`
If a configured Host is unavailable (for example, a stopped WSL adapter), only
the MCP listener stops; the extension and its panels remain available. Open
**Funplay > MCP Server**, edit **Server Host**, and click **Apply Host**. Use
`127.0.0.1` for same-machine access. Applying the address retries startup when
MCP is enabled; otherwise use **Enable MCP Server** or **Restart** when ready.
The panel retains the startup error until a successful start. No address is
silently substituted and existing configuration is not rewritten at startup.
`COCOS_MCP_HOST` takes priority over the project file; if set, change that
environment variable and restart Creator instead. Network/wildcard addresses
can expose unauthenticated editor access: use only on a trusted network and
reconfigure MCP clients after changing the address.
`toolProfile: "custom"` starts from the `core` set, then adds `enabledToolCategories` / `enabledTools` and removes `disabledToolCategories` / `disabledTools`. The panel can save these exposure settings as named `savedToolProfiles` for quick restore or sharing. `enableSessions` is off by default because this server does not need cross-request client state for normal editor automation.
`enableConsoleLogging` defaults to `true`. Turn it off in **MCP Settings > Console Logs > Print MCP logs** to stop the extension and HTTP server from printing MCP information, warnings, and errors to the Cocos console. It takes effect immediately, persists per project, and does not restart MCP, clear history, mute project-script logs, or change stdio protocol output.
## v0.7.0: project-bound connections and frame-paced input
New generated MCP URLs use `http://127.0.0.1:<port>/mcp/project/<project-id>/`.
Existing pinned ports are preserved. Independently compare
`initialize.funplay.context.project_path` and `project_id` with your intended project
before writing. Legacy `/` and `/mcp` endpoints remain readable, but mutations need
the verified `expected_context` token, either in tool arguments or
`params._meta.expected_context`. A scoped URL binds the project; an explicit token
also pins the extension/Editor lifetime. Reinitializing an arbitrary responding
server is not proof that it is the intended project. This is routing protection,
not authentication.
For old configurations, use the existing connection/Skills notice to reconfigure,
then reconnect/restart your MCP client. Migration preserves unrelated entries,
custom headers/timeouts, historical shared entries and locally edited Skills.
Unreadable or unverified configurations require review instead of an automatic rewrite.
The Full-profile `simulate_mouse_drag` keeps legacy `steps`/`stepDelayMs` by default.
For a new calibrated gesture, explicitly use:
```json
{
"timing": "frame-paced",
"coordinateSpace": "image-pixels",
"captureId": "<fresh screenshot captureId>",
"requestKey": "drag-test-001",
"startX": 100, "startY": 100, "endX": 300, "endY": 200,
"durationMs": 600, "pressHoldMs": 100, "endHoldMs": 100,
"waitMs": 1200
}
```
Measure coordinates from that exact PNG. A running response is only an
acknowledgment. Query the same tool with `action: "status"` and its `jobId` or
`requestKey`; cancel with `action: "cancel"`, without coordinates. Retained
identical starts recover their original receipt rather than replaying. Only the
latest 32 receipts are retained, not across eviction or Editor reload. Missing
receipts require state inspection before any new gesture. `simulate_preview_input`
supports the same fields in drag mode, with separate receipt ownership and tool exposure.
Frames come from the target Electron renderer, not a verified native Game View
engine Update loop. Receipts explicitly report `nativeGameUpdateVerified: false`
and `businessOutcomeVerified: false`. Game View pause/stop is checked separately.
Focus loss, stale geometry, stalled frames or cancellation interrupt input and
attempt only the owned release. Failed release keeps that window locked until
explicit cleanup succeeds. No project input/background policies are changed.
Legacy-coordinate clicks/drags and calibrated input with legacy timing also
attempt owned release after interrupted dispatch. If release fails, the result
reports uncertain delivery and the window remains locked. Stop/restart MCP to
retry that release cleanup; do not replay the gesture without inspecting the
actual state. Shutdown also cancels suspended legacy mouse gestures.
## Architecture
```text
Cocos Creator Extension
├─ browser.js
│ ├─ Embedded HTTP MCP Server
│ ├─ Tool Registry
│ ├─ Resource Provider
│ ├─ Prompt Provider
│ └─ One-Click Client Configuration
├─ scene.js
│ └─ Scene/runtime execution bridge
├─ panel/index.js
│ └─ Minimal MCP Server dashboard
├─ panel/tool-exposure.js, panel/settings.js, panel/project-skills.js
│ └─ Focused maintenance windows
└─ lib/
├─ assets, diagnostics, screenshots, input
├─ tool-profiles, javascript-safety
├─ tools/
│ ├─ files
│ ├─ assets-advanced
│ ├─ cocos-project
│ └─ scene-events
└─ server, resources, prompts, tool registry
```
The server speaks MCP-style HTTP JSON-RPC 2.0 and supports tools, resources, resource templates, prompts, health checks, and a read-only `/tools` debug endpoint.
## Development
Run checks before publishing changes:
```bash
npm run check
npm test
npm run docs:check
npm run release:check
npm run pack:dry-run
```
Regenerate the tool reference after changing `lib/tool-registry.js`:
```bash
npm run docs:generate
```
To generate a GitHub Release-ready extension package:
```bash
npm run release:package
```
The package is written to `releases/<version>/` with a zip, manifest, generated release notes, checksum file, and release README. Upload all five files so the public checksums can be verified. See [RELEASE_WORKFLOW.md](./RELEASE_WORKFLOW.md) and [RELEASE_CHECKLIST.md](./RELEASE_CHECKLIST.md) for the full process.
Validate MCP Registry metadata before publishing:
```bash
npm run registry:validate
```
## License
MIT License. See [LICENSE](./LICENSE).
+681
View File
@@ -0,0 +1,681 @@
<p align="center">
<h1 align="center">Funplay MCP for Cocos</h1>
<p align="center">
<strong>嵌入 Cocos Creator 编辑器的 MCP Server</strong>
</p>
<p align="center">
<a href="#"><img src="https://img.shields.io/badge/Cocos%20Creator-3.8%2B-blue" alt="Cocos Creator 3.8+"></a>
<a href="#"><img src="https://img.shields.io/badge/License-MIT-blue.svg" alt="License: MIT"></a>
<a href="#"><img src="https://img.shields.io/badge/MCP-Compatible-green" alt="MCP Compatible"></a>
<a href="#"><img src="https://img.shields.io/badge/Platform-Editor%20Only-orange" alt="Editor Only"></a>
<a href="https://store.cocos.com/app/detail/8913"><img src="https://img.shields.io/badge/Cocos%20Store-Install-brightgreen" alt="Install from Cocos Store"></a>
</p>
<p align="center">
中文 | <a href="./README.md">English</a>
</p>
</p>
> 如果这个项目对你有帮助,欢迎顺手点一个 Star。它能帮助更多 Cocos 开发者发现项目,也能支持后续持续维护。
交流或问题反馈欢迎加入 QQ 群:**1108522331**。打开 **Funplay > 联系反馈**,可以查看作者邮箱并复制邮箱或群号。
---
Funplay MCP for Cocos 是一个采用 MIT 协议的 Cocos Creator 扩展,它把 HTTP MCP Server 直接嵌入编辑器,让 Claude Code、Cursor、Codex、VS Code Copilot、Trae、Antigravity、Pi、Kiro、Qoder、Kimi Code、OpenCode、CodeBuddy、DeepSeek Harness(DSH)等 AI 助手可以直接检查和操作正在运行的 Cocos 项目。
这个项目延续 Funplay MCP for Unity 的产品方向:默认工具面保持聚焦,提供一键客户端配置,并围绕一个高灵活度主执行工具组织工作流。
在 Cocos 里,主工具是 `execute_javascript`:
- `context: "scene"` 在当前 Cocos 场景/运行态上下文执行 JavaScript
- `context: "editor"` 在 Cocos 编辑器/browser 上下文执行 JavaScript
> *“在当前场景里创建一个登录页 UI,包含账号/密码输入框和登录按钮。”*
>
> AI 助手可以调用 `execute_javascript`,在当前 Canvas 下生成 UI 层级,挂载 Cocos 组件,检查层级,并截图验证效果。
## 快速开始
如果你只想尽快连上,先做这三步:
- 把这个仓库安装为 Cocos Creator 扩展
- 打开 `Funplay > MCP Server`
- 使用内置的一键 MCP 客户端配置
### 1. 安装为 Cocos Creator 扩展
推荐安装方式:通过官方 [Cocos Store 页面](https://store.cocos.com/app/detail/8913) 安装到目标 Cocos Creator 项目。
如果要本地开发或使用未发布版本,可以把仓库 clone 或复制到 Cocos 项目的扩展目录:
```bash
cd /path/to/your-cocos-project
mkdir -p extensions
git clone https://github.com/FunplayAI/funplay-cocos-mcp.git extensions/funplay-cocos-mcp
```
然后重启 Cocos Creator,或在编辑器里重新加载扩展。
如果不想用 git 安装,可以从 GitHub Releases 下载 `Funplay.CocosMcp.v<version>.zip`,解压后把 `funplay-cocos-mcp` 目录移动到项目的 `extensions/` 目录。
#### 为所有项目安装(推荐)
先在任意一个项目中安装并打开扩展,然后进入 `Funplay > MCP Settings`,在“所有项目”区域点击 **为所有项目安装**。扩展会下载最新 GitHub Release、校验 `SHA256SUMS.txt`,再安装到当前 Cocos Creator 版本管理的全局扩展目录:
- macOS / Linux:`~/.CocosCreator/builtin-extensions/<Creator 版本>/funplay-cocos-mcp`
- Windows:`%USERPROFILE%\.CocosCreator\builtin-extensions\<Creator 版本>\funplay-cocos-mcp`
安装完成后,扩展会让 Cocos Creator 立即扫描并注册这份全局副本。之后由同一 Creator 版本打开或新建的项目都会自动加载它,MCP Server 仍默认自动启动;如果当前已打开项目的项目副本优先,请重新打开项目。不会向每个项目的 `extensions/` 目录重复复制文件。
Cocos Creator 会按版本隔离全局扩展。如果同时使用多个 Creator 版本,需要在每个版本中分别执行一次“为所有项目安装”。
为了避免覆盖开发代码,安装过程不会删除当前项目副本。如果当前项目同时存在同名扩展,设置窗口会显示重复安装提示;确认全局副本正常工作后,请移除或禁用项目副本,避免扩展冲突。
### 2. 启动 MCP Server
打开编辑器菜单:
```text
Funplay > MCP Server
```
新项目会获得 `20000–29999` 范围内的稳定项目独立端口。已有配置保留原来的固定端口(包括 `8765`)。请使用 MCP Server 面板显示的实际 URL;如果当前使用临时回退端口,请先点击“固定当前端口”或“使用项目独立端口”,再配置客户端。
如果配置端口已被占用,扩展会先检查已有 listener 是否属于同一个 Cocos 项目;同项目 listener 会被安全复用,无关 listener 才会自动回退到下一个可用本地端口。
面板刻意保持精简:
- 启用或停用 MCP Server
- 打开聚焦的 Tool Exposure、MCP Settings 和 Project Skills 子窗口
- 自动检查当前安装版本是否落后于 GitHub 最新 Release
- 从面板打开 Release 页面,或安装已校验的 Release 包
- 一键安装到 Cocos Creator 全局扩展目录,让已有项目和新项目自动可用
- 一键配置 AI 客户端,并随目标客户端预览对应配置
- 把高级工具 profile 编辑、传输设置和安装管理从主窗口拆出去
- 自动跟随 Cocos Creator 的界面语言,或在 MCP Settings 中为项目指定中文/英文
- 在设置中关闭“打印 MCP 日志”,停止控制台刷屏,同时保留最近活动和内部诊断记录
各管理页面统一标题、对齐控件和轻量分区。Tool Exposure 按分类管理工具开关;Project Skills 突出可用操作,将文件路径和备份信息折叠收纳。“最近活动”显示每次调用的摘要和真实结果,对象、数组按层级展开;脚本调用分开展示执行日志与返回值。各页“输出”与独立日志查看窗口仍保持移除。操作后显示简短成功/失败提示,底层诊断记录仍可通过 MCP 工具和资源读取。
脚本工具按次采集 `console.log/info/warn/error/debug` 输出,失败前的日志也会保留,不受“打印 MCP 日志”开关影响。并发、嵌套调用的日志相互隔离,脚本完成后停止采集;不混入全局/项目日志或单独 require 的模块内部日志。使用脚本中注入的 `console`(`run`/模块导出函数也可通过 `env.console` 使用)。MCP 响应保持原有 `data` 结构,新增可选的 `execution` 信息,包含执行上下文、耗时、已限量并脱敏的日志及省略条数。最近活动保留结果层级和标量值;大结果及文件/脚本正文仍限量或省略,并显示截断提示。
扩展菜单和原生窗口标题会跟随 Cocos Creator 的界面语言。窗口内的控件、工具描述、状态提示、确认信息和空状态支持中文与英文;打开 `Funplay > MCP Settings` 可以跟随 Creator,也可以为当前项目固定内容语言。MCP 工具 ID 和 schema 保持英文,确保客户端集成稳定。
### 3. 配置 AI 客户端
优先使用 `Funplay > MCP Server` 面板里的 **MCP Client Config** 区域。
选择目标客户端,点击 **One-Click Configure**,扩展会直接写入推荐的 MCP 配置项。
写入客户端的 MCP server 名称是:
```text
cocos-<project>-<hash>
```
如果你更想手动编辑配置文件,再参考下面这些示例,并将示例中的旧名称 `funplay_cocos` 和端口 `8765` 替换为面板显示的名称和 URL。Claude Code 一键配置使用 `~/.claude.json` 中按 Git 根目录划分的项目配置,而不是下面的全局示例。详见[配置与迁移说明](docs/PROJECT_WORKFLOWS.md)。
<details>
<summary>Claude Code / Claude Desktop</summary>
```json
{
"mcpServers": {
"funplay_cocos": {
"type": "http",
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>Cursor</summary>
```json
{
"mcpServers": {
"funplay_cocos": {
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>VS Code</summary>
一键配置使用 VS Code 用户配置目录的 `mcp.json` 和 `servers` 格式,并保留 JSONC 注释。macOS 使用 `~/Library/Application Support/Code/User`,Windows 使用 `%APPDATA%/Code/User`,Linux 使用 `$XDG_CONFIG_HOME/Code/User`(默认 `~/.config/Code/User`),同时支持 `VSCODE_PORTABLE` / `VSCODE_APPDATA` 覆盖。“配置 + Skills”会将项目 Skills 安装至 [`.github/skills`](https://code.visualstudio.com/docs/agent-customization/agent-skills)。
```json
{
"servers": {
"funplay_cocos": {
"type": "http",
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>Trae</summary>
一键配置按 [Trae 官方项目 MCP 规则](https://docs.trae.cn/ide_add-mcp-servers)写入 `<Cocos 项目>/.trae/mcp.json`。请在 Trae 中打开此 Cocos 项目目录,并在“设置 > MCP”启用“项目级 MCP”。此目标不再写入 `~/.trae/mcp.json`。“配置 + Skills”会将缺失的内置 Skill 安装至 [`.trae/skills`](https://docs.trae.cn/ide_skills)。
```json
{
"mcpServers": {
"funplay_cocos": {
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>Antigravity(反重力)</summary>
一键配置写入当前 Cocos 项目的 `.agents/mcp_config.json`,通过 `mcpServers` 下的 `serverUrl` 配置 Streamable HTTP。请在 Antigravity 中打开此 Cocos 项目并重新加载 MCP 配置。“配置 + Skills”会把缺失的内置 Skill 安装到与 Codex 共用的 `.agents/skills`。[MCP 配置文档](https://antigravity.google/docs/mcp/) · [项目 Skills 文档](https://antigravity.google/docs/skills/)
```json
{
"mcpServers": {
"cocos-demo-012345": {
"serverUrl": "http://127.0.0.1:8765/mcp/project/0123456789abcdef01234567/"
}
}
}
```
</details>
<details>
<summary>Pi(1.0 或更高版本)</summary>
在 **Funplay > MCP Server** 中选择 **Pi**。一键配置把项目专属的 Streamable HTTP 地址写入 `.pi/mcp.json`。“配置 + Skills”会把缺失的内置 Skill 安装到与 Codex、Antigravity 共用的 `.agents/skills`。[Pi MCP 配置](https://docs.pi.dev/latest/mcp) · [Pi Skills](https://docs.pi.dev/latest/skills)
在 Cocos 项目目录运行 `pi`,并按提示信任项目。已信任的会话可以执行 `/reload`,再用 `/mcp` 查看连接状态。
```json
{
"mcpServers": {
"cocos-demo-012345": {
"url": "http://127.0.0.1:8765/mcp/project/0123456789abcdef01234567/"
}
}
}
```
</details>
<details>
<summary>Kiro</summary>
一键 MCP 配置使用 `~/.kiro/settings/mcp.json`。“配置 + Skills”同时将缺失的内置 Skill 安装至项目的 [`.kiro/skills`](https://kiro.dev/docs/skills/) 目录。
```json
{
"mcpServers": {
"funplay_cocos": {
"type": "http",
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>Qoder</summary>
用户级配置会写入 `~/.qoder/settings.json`;设置了 `QODER_CONFIG_DIR` 环境变量时,则写入 `$QODER_CONFIG_DIR/settings.json`。
```json
{
"mcpServers": {
"funplay_cocos": {
"type": "http",
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>Kimi Code</summary>
用户级配置会写入 `~/.kimi-code/mcp.json`;设置了 `KIMI_CODE_HOME` 环境变量时,则写入 `$KIMI_CODE_HOME/mcp.json`。
```json
{
"mcpServers": {
"funplay_cocos": {
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>Codex</summary>
一键配置遵循 [Codex 配置目录规则](https://learn.chatgpt.com/docs/config-file/config-advanced#config-and-state-locations),使用 `$CODEX_HOME/config.toml`,默认是 `~/.codex/config.toml`。支持空的 `[mcp_servers]` 父表配合显式服务器子表;内联 MCP 表仍需手动编辑。
```toml
[mcp_servers.funplay_cocos]
url = "http://127.0.0.1:8765/"
```
</details>
<details>
<summary>OpenCode</summary>
全局配置位于所有平台的 `$XDG_CONFIG_HOME/opencode/opencode.json` 或 `~/.config/opencode/opencode.json`(`opencode.jsonc` 同样可用)。
一键配置优先使用已有的 `opencode.jsonc`,支持两种文件中的注释和尾逗号,保留其他设置及注释;遇到格式错误或存在歧义的配置时,不会覆盖原文件。
已有 [OpenCode V2](https://opencode.ai/docs/mcp-servers) 的 `mcp.servers` 配置会保持嵌套结构。新文件使用下方的平铺 `mcp` 格式以兼容 V1;当前 [OpenCode 配置 schema](https://opencode.ai/config.json) 仍接受此旧格式。工具不会在新旧格式之间迁移自定义超时或认证选项。
```json
{
"mcp": {
"funplay_cocos": {
"type": "remote",
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>CodeBuddy(IDE 4.0+)</summary>
一键配置写入 `<Cocos 项目>/.mcp.json`,使用 [CodeBuddy IDE 4.0 起支持的项目级配置](https://intl.cloud.tencent.com/zh/document/product/1256/77264),并保留其他服务器、注释和尾逗号。请在 CodeBuddy 中直接打开此 Cocos 项目目录,必要时重载客户端,并按提示启用或批准 MCP 服务器。旧版 IDE 和独立的 CodeBuddy 编辑器插件使用不同的配置位置;此选项不会写入它们的全局设置或 CLI 全局文件。
“配置 + Skills”还会按 [官方 Skills 目录规范](https://www.codebuddy.cn/docs/ide/Features/Skills),将缺少的内置 Skills 安装到 `<Cocos 项目>/.codebuddy/skills`。已有 Skills 保持不变;需要更新时可在“项目 Skills”中预览确认。
```json
{
"mcpServers": {
"funplay_cocos": {
"type": "http",
"url": "http://127.0.0.1:8765/"
}
}
}
```
</details>
<details>
<summary>DeepSeek Harness(DSH)</summary>
在 MCP Server 面板选择 **DeepSeek Harness (DSH)**,点击配置会生成 `<Cocos 项目>/.dsh/funplay-cocos-mcp.patch.json`,这是供 [官方 Cordis MCP 客户端](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/mcp/mcp-client/README.md) 使用的 JSON 格式 YAML 覆盖层。不会修改 `$DSH_HOME`、全局或 profile YAML、依赖、凭据及审批设置。
**该文件不会自动加载。** 请在 Cocos 项目目录使用面板显示的完整命令启动 DSH,或将其中的 `--patch` 参数追加到原有 DSH 启动命令。例如已安装 `dsh` 时:
```sh
dsh web --patch '/absolute/path/to/cocos-project/.dsh/funplay-cocos-mcp.patch.json'
```
通过 npm 启动时使用 `npx @deepseek-ai/dsh web --patch <同一绝对路径>`。其他官方 profile 也可通过 `--patch` 使用此文件;第三方桌面启动器可能需要单独设置启动参数。请保持 Cocos 及其 MCP 服务运行。生成文件会使用当前项目实际的服务器名称与 URL,不沿用旧示例名称及端口。
“配置 + Skills”还会按 [DSH 文件系统 Skills 规范](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/skill/skill-filesystem/README.md),将缺少的内置 Skills 安装到 `<最近 Git 根目录>/.dsh/skills`;没有 Git 仓库时使用 Cocos 项目目录。已有文件保持不变,可在“项目 Skills”中检查更新。同一 Git 仓库中的多个 Cocos 项目共用 Skills 根目录,但各有独立 MCP 覆盖层。
</details>
### 可选:npm stdio Wrapper
如果 MCP 客户端更适合使用本地 `stdio` 命令,可以在启动 Cocos 编辑器内置服务后安装 npm wrapper:
```bash
npm install -g funplay-cocos-mcp
```
示例 MCP 客户端配置:
```json
{
"mcpServers": {
"funplay_cocos": {
"command": "funplay-cocos-mcp",
"env": {
"FUNPLAY_COCOS_MCP_URL": "http://127.0.0.1:8765/"
}
}
}
}
```
这个 wrapper 会把 stdio MCP 流量桥接到 Cocos 内置 HTTP endpoint。也可以直接运行 `npx funplay-cocos-mcp --url http://127.0.0.1:8765/`。
stdio 传输支持标准的换行分隔 UTF-8 JSON-RPC 消息(NDJSON)。wrapper 同时接受原有的 `Content-Length` 分帧格式,并使用与输入消息相同的分帧格式返回响应。
### 4. 验证连接
先在 AI 客户端里试几个安全请求:
- “调用 `get_project_info`,总结当前 Cocos 项目。”
- “读取 `cocos://project/context`,告诉我当前编辑器状态。”
- “用 `execute_javascript` 的 `context: \"scene\"` 返回当前场景名。”
- “用 `execute_javascript` 的 `context: \"editor\"` 返回项目路径。”
如果这些都正常返回,说明 MCP server、resources、prompts 和主执行工具已经连通。
如果要排查本地传输链路,面板可以直接复制下面的命令,也可以手动执行:
```bash
curl http://127.0.0.1:8765/health
curl http://127.0.0.1:8765/tools
```
### 5. 开始构建
可以在 AI 客户端里尝试:
> 在当前 Cocos 场景里创建一个登录页 UI,包含账号/密码输入框、登录按钮和游客登录按钮。优先使用 `execute_javascript`,创建后检查层级并截图验证。
## 开始前说明
- 这是一个 **仅限 Editor** 的扩展,用于自动化 Cocos Creator,不会给最终游戏包添加运行时依赖。
- 新项目使用稳定的项目独立端口;MCP Server 面板会显示实际地址,也支持固定端口。
- 如果配置端口被占用,服务会先通过项目身份识别同项目已有 listener;无法确认同项目时才会自动回退到下一个可用端口,面板与一键客户端配置会使用实际运行端口。
- `GET /health` 和 `GET /tools` 是只读调试端点,方便不用 MCP 客户端也能快速检查本地服务。
- 默认 `core` profile 暴露 39 个高频工具;如果需要完整工具集,可在面板切到 `full`,暴露全部 106 个工具;也可以用 `custom` 按分类或工具名增删。
- 面板会自动检查 GitHub Release,也支持手动检查。
- 一键更新会下载 GitHub Release zip,校验 `SHA256SUMS.txt`,备份当前扩展目录,替换插件文件,并在 Cocos package API 支持时 reload 扩展;如果当前 Cocos 版本没有可靠 reload 能力,安装后重启 Cocos Creator 即可。Git worktree 和 symlink 安装会保留为手动 `git pull` 或手动替换包,避免覆盖开发目录。
- “为所有项目安装”使用同一套 Release 与 SHA256 校验流程,目标是当前 Creator 版本管理的全局目录,并会请求 Creator 扫描和注册扩展。为了避免在设置窗口打开时切换扩展,它会保留正在运行的项目副本;没有项目副本时会立即启用全局副本,否则在下次打开项目时启用。
- **项目 Skills** 按客户端管理 `funplay-cocos-mcp-workflow`、`funplay-cocos-ui-composition` 和自定义 Skills,覆盖 13 个一键配置客户端。MCP 工作流技能为 v4,UI 组合技能为 v5,涵盖整页效果图拆分、可编辑 Prefab 搭建和逐区保真验收。版本检测、差异、备份与恢复包含托管参考文件,用户自有参考文件受保护。Codex、Antigravity 和 Pi 共用 `.agents/skills`。Codex 和 Antigravity 迁移旧路径中的内置 Skill 时会保留原文件。
- Streamable HTTP 响应已补齐 MCP 传输层要求,包括 `Accept`、`MCP-Protocol-Version`、JSON-RPC notification/response,以及可选 `Mcp-Session-Id` session。
- 工具列表会包含 MCP `outputSchema` 和 `annotations`;结构化工具结果统一使用包含 `ok`、`tool`、`callId`、`summary`、`data`、`refs` 的标准 envelope。
- `execute_javascript` 安全检查默认开启,会拦截明显高风险的文件系统和 shell 模式,例如删除/截断调用、原始写入流、路径穿越、用户/系统绝对路径和 `child_process`。这是防护栏,不是完整沙箱;确认风险后可在单次调用中显式传入 `safety_checks: false`。
- 所有已暴露的 MCP 工具都会直接执行,Cocos 扩展里没有额外 approval 开关。
- 文件工具和 `cocos://asset/path/...` 资源默认只能访问当前 Cocos 项目根目录内的路径。
- 推荐工作流是优先使用 `execute_javascript`,再配合截图、诊断、资产、检查类工具。
- 如果在面板里修改端口或工具暴露模式,扩展会自动保存配置,并在需要时重启服务。
## 为什么做这个项目
- **`execute_javascript` 主工具优先** — 一个高灵活度 JavaScript 工具就能编排场景/运行态和编辑器自动化,避免 AI 客户端被大量细碎工具干扰
- **嵌入式 Cocos 扩展** — Cocos 侧不需要单独 Python 守护进程或外部 bridge
- **一键客户端配置** — 在 Cocos Creator 内直接配置 Claude Code、Cursor、VS Code、Trae、Antigravity、Pi(1.0+)、Kiro、Qoder、Kimi Code、Codex、OpenCode、CodeBuddy(IDE 4.0+),或生成 DSH 配置文件及明确的 `--patch` 启动命令
- **内建项目上下文** — 直接暴露项目、场景、选择、脚本诊断、日志和交互历史资源
- **默认聚焦,必要时全量** — `core` 降低工具列表噪音,需要时切到 `full` 暴露全部工具;`custom` 与保存的 profile 可按分类或工具名调整并恢复
- **可视化验证** — 截图和输入模拟让 AI 能验证 UI 与玩法改动
## 核心特性
- **106 个内置工具** — 覆盖场景层级、编辑器状态、选择工作流、Prefab、资产、资产依赖、项目指令、UI 创建、组件、文件、日志、脚本诊断、截图、运行态控制、构建/预览辅助、编辑器偏好、事件绑定和输入模拟
- **统一主工具** — `execute_javascript` 同时支持 `scene` 和 `editor` 两种上下文
- **Resources 与 Prompts** — 实时项目/日志资源,以及脚本修复、场景验证、可玩原型等可复用工作流
- **Cocos 图形面板** — `Funplay > MCP Server` 是精简 Dashboard,并提供 Tool Exposure、MCP Settings、Project Skills 子窗口承载复杂工作流
- **截图与输入支持** — 支持编辑器/场景/Game/Preview 截图,以及 Electron 级鼠标键盘事件;鼠标点击和拖拽可绑定新截图的 `captureId`,使用实际 PNG 像素坐标
- **厂商无关** — 兼容任意支持 HTTP JSON-RPC MCP 的 AI 客户端
## 与 Funplay MCP for Unity 的关系
Funplay MCP for Cocos 延续 Funplay MCP for Unity 的设计原则,并针对 Cocos Creator 的 JavaScript/TypeScript 编辑器环境做了适配。
| 维度 | Funplay MCP for Cocos | Funplay MCP for Unity |
|------|------------------------|------------------------|
| 编辑器集成 | Cocos Creator 扩展 | Unity Editor 包 |
| 内置服务 | 内嵌 HTTP MCP Server | 内嵌 HTTP MCP Server |
| 主执行工具 | `execute_javascript` | `execute_code` |
| 主语言 | 场景/编辑器上下文中的 JavaScript | Unity 编辑器/运行态中的 C# |
| 默认工具集 | `core`,39 个工具 | 聚焦版 `core` 工具集 |
| 完整工具集 | 106 个工具,并支持 `custom` 暴露 | 79 个工具 |
| 客户端配置 | 一键配置面板 | 一键配置窗口 |
## MCP 能力结构
当前包提供四层能力:
- **Tools** — `core` 下 39 个工具,`full` 下 106 个工具,并支持 `custom` include/exclude 规则和命名工具 profile
- **Primary execution** — `execute_javascript` 用于场景/运行态和编辑器/browser 自动化
- **Prompts** — `fix_script_errors`、`create_playable_prototype`、`scene_validation`、`auto_wire_scene`,以及从 `mcp-prompts/*.md` 读取的带参数项目工作流。详见[项目隔离、Skills 与工作流配置](docs/PROJECT_WORKFLOWS.md)。
- **Resources** — 项目上下文、场景摘要、当前选择、脚本诊断、资产选择、日志和 MCP 交互历史
自动生成的工具参考文档见 [docs/TOOLS.md](./docs/TOOLS.md),里面包含工具分类、profile 和读写/变更提示。
当前默认 `core` 工具集刻意保持精简,只包含:`execute_javascript`、`execute_scene_script`、`execute_editor_script`、`get_editor_state`、`get_tool_catalog`、`check_for_updates`、`get_selection`、`list_project_instructions`、`read_project_instruction`、`set_selection`、`get_project_info`、`get_build_status`、`get_preview_mode`、`create_scene`、`get_scene_info`、`get_hierarchy`、`list_scenes`、`open_scene`、`inspect_prefab`、`validate_prefab_references`、`inspect_prefab_instance`、`list_assets`、`inspect_asset`、`inspect_asset_dependencies`、`validate_asset_dependencies`、`open_asset`、`select_asset`、`run_script_diagnostics`、`get_recent_logs`、`search_project_logs`、`clear_logs`、`validate_scene`、`get_performance_snapshot`、`get_script_diagnostic_context`、`get_runtime_state`、`capture_editor_screenshot`、`capture_scene_screenshot`、`capture_preview_screenshot`、`list_editor_windows`。
### 预览模式
Creator 3.8.x 的预览自动化使用与内置预览工具栏相同的模式和编辑器 API:
| 模式 | 行为 |
|------|------|
| `browser` | 在系统浏览器中打开场景;可用时,`get_preview_mode` 和 `run_project_preview` 会分别返回同机和局域网预览 URL。 |
| `gameView` | 在 Cocos Creator 的 Game View 中启动场景。 |
| `simulator` | 在原生模拟器中启动场景。 |
使用 `get_preview_mode` 查询当前模式,使用 `set_preview_mode` 切换模式,使用 `run_project_preview` 启动预览。`run_project_preview` 仍兼容旧的 `platform` 参数,但该参数已弃用,推荐改用 `mode`。
Game View 通过原生预览工具栏启动,手动暂停/恢复按钮会保持可用。重复启动不会停止已有预览,也会保留其暂停状态。`pause_runtime` 和 `resume_runtime` 控制同一个 Game View 预览且可重复调用;它们要求 Game View 已启动,不控制浏览器、模拟器或编辑场景 director。切换到其他模式前会先通过工具栏停止 Game View,操作被拒绝时会明确报错,不会误报成功。
请使用 `full` 范围,或在自定义范围中启用上述控制工具。编写脚本时也应优先使用这些工具,避免直接调用会绕过工具栏同步的 `scene.editor-preview-set-play`。
`get_runtime_state`(`validate_scene` 也使用它)返回 `scope: "gameView"`、实际的 `running`/`paused`、`busy` 和 `toolbarSynchronized`。它不再将编辑场景的帧数/时间缩放当作预览状态;这些计数仍可通过 `get_performance_snapshot.runtime` 查询,并标记为 `scope: "editScene"`。`set_time_scale` 仍只影响编辑场景。预览控制要求 Creator 主窗口的兼容工具栏已就绪;工具栏不可用时会明确报错。
浏览器预览结果会区分同机自动化与局域网访问:
| 字段 | 含义 |
|------|------|
| `url` / `localUrl` | 供与 Cocos Creator 运行在同一台电脑上的 MCP 客户端或浏览器使用的 loopback 地址。 |
| `networkUrl` | 供同一局域网内其他设备使用的 Creator 原始非 loopback 地址;当 Creator 返回 loopback 或通配主机时为空。 |
| `reportedUrl` | Cocos Creator 返回且尚未规范化的原始 URL 字符串。 |
| `urlWarning` | 仅当原始值无法按绝对 HTTP(S) URL 规范化时返回非空警告。 |
## 内置 Resources
| Resource | 说明 |
|----------|------|
| `cocos://project/context` | 完整项目与编辑器上下文 |
| `cocos://project/summary` | 项目摘要 |
| `cocos://scene/active` | 当前场景快照 |
| `cocos://scene/current` | 当前场景别名 |
| `cocos://selection/current` | 当前编辑器选择 |
| `cocos://selection/asset` | 当前选中资产 |
| `cocos://errors/scripts` | 脚本诊断信息 |
| `cocos://logs/editor` | 最近 MCP 运行日志和工具交互 |
| `cocos://logs/project` | 常见项目日志文件的尾部内容 |
| `cocos://mcp/interactions` | 最近 MCP 交互历史 |
## 内置工具
Funplay MCP for Cocos 当前在 `full` profile 下提供 **106 个工具函数**:
| 分类 | 工具 |
|------|------|
| **脚本执行** | `execute_javascript`, `execute_scene_script`, `execute_editor_script` |
| **编辑器状态** | `get_editor_state`, `get_tool_catalog`, `check_for_updates`, `get_selection`, `set_selection`, `get_editor_selection` |
| **项目指令** | `list_project_instructions`, `read_project_instruction`, `write_project_instruction`, `create_project_skill`, `create_cocos_mcp_project_skill` |
| **项目与场景** | `get_project_info`, `get_scene_info`, `get_hierarchy`, `find_nodes`, `inspect_node`, `list_scenes`, `open_scene`, `run_scene_asset` |
| **节点编辑** | `create_node`, `delete_node`, `set_node_transform` |
| **资产与 Prefab** | `list_assets`, `inspect_asset`, `inspect_asset_dependencies`, `validate_asset_dependencies`, `check_asset_ready`, `open_asset`, `select_asset`, `delete_asset`, `list_prefabs`, `inspect_prefab`, `validate_prefab_references`, `duplicate_prefab`, `edit_prefab_json`, `create_prefab_from_node`, `create_prefab_instance`, `inspect_prefab_instance`, `apply_prefab_instance`, `revert_prefab_instance`, `instantiate_prefab` |
| **组件** | `list_components`, `inspect_component`, `add_component`, `remove_component`, `set_component_property`, `reset_component_property` |
| **UI** | `create_canvas`, `create_label`, `create_button`, `create_sprite` |
| **相机** | `list_cameras`, `create_camera`, `set_camera_properties` |
| **动画** | `list_animations`, `add_animation_clip`, `play_animation`, `stop_animation` |
| **文件** | `read_file`, `get_file_snippet`, `write_file`, `replace_in_file`, `search_files`, `list_directory`, `exists`, `refresh_assets` |
| **诊断与日志** | `run_script_diagnostics`, `get_script_diagnostic_context`, `get_recent_logs`, `search_project_logs`, `clear_logs`, `validate_scene`, `get_performance_snapshot` |
| **构建与编辑器** | `get_build_status`, `get_preview_mode`, `set_preview_mode`, `open_build_panel`, `run_project_preview`, `save_current_scene`, `get_editor_preference`, `set_editor_preference`, `broadcast_editor_message` |
| **运行态** | `get_runtime_state`, `pause_runtime`, `resume_runtime`, `set_time_scale` |
| **交互与事件** | `emit_node_event`, `simulate_button_click`, `list_button_click_events`, `bind_button_click_event`, `invoke_component_method`, `simulate_mouse_click`, `simulate_mouse_drag`, `simulate_key_press`, `simulate_key_combo`, `simulate_preview_input` |
| **截图与窗口** | `capture_desktop_screenshot`, `capture_editor_screenshot`, `capture_scene_screenshot`, `capture_game_screenshot`, `capture_preview_screenshot`, `list_editor_windows` |
## 主工具示例
### Scene 上下文
```json
{
"context": "scene",
"code": "return { sceneName: scene.name, rootCount: scene.children.length };",
"args": {}
}
```
### Editor 上下文
```json
{
"context": "editor",
"code": "return { projectPath: context.projectPath, toolCount: helpers.listTools().length };",
"args": {}
}
```
Editor 上下文脚本可以访问 `Editor`、`fs`、`path`、`os`、`require`、`context`、`args`,以及 `helpers.getStatus()`、`helpers.listTools()`、`helpers.readResource(uri)`、`helpers.callTool(name, args)`、`helpers.configureClient(targetId)` 等辅助函数。
## 可选配置
在 Cocos 项目根目录放置 `funplay-cocos-mcp.config.json`:
```json
{
"host": "127.0.0.1",
"port": 8765,
"toolProfile": "core",
"enabledToolCategories": [],
"disabledToolCategories": [],
"enabledTools": [],
"disabledTools": [],
"enableSessions": false,
"enableConsoleLogging": true,
"executeJavascriptSafetyChecks": true,
"autostart": true,
"maxInteractionLogEntries": 50,
"activeToolProfileName": "",
"savedToolProfiles": []
}
```
也支持环境变量:
- `COCOS_MCP_HOST`
- `COCOS_MCP_PORT`
- `COCOS_MCP_PROFILE`
当配置的 Host 不可用(例如 WSL 网卡尚未启动)时,仅 MCP 监听服务停止,插件及面板仍可打开。
进入 **Funplay > MCP 服务**,修改 **监听地址** 后点击 **应用地址**;本机访问可填写
`127.0.0.1`。启用服务时会重试启动,否则可在需要时点击 **启用 MCP 服务** 或 **重启**。
面板保留启动错误,直到服务成功启动;不会自动替换监听地址,也不会在启动失败时改写配置文件。
`COCOS_MCP_HOST` 环境变量优先于项目文件;设置了该变量时,需修改环境变量并重启 Creator。
网络/通配地址可能开放未认证的编辑器访问,请仅在可信网络使用,并在修改地址后重新配置 MCP 客户端。
`toolProfile: "custom"` 会从 `core` 集合开始,再加入 `enabledToolCategories` / `enabledTools`,并移除 `disabledToolCategories` / `disabledTools`。面板可以把这些暴露设置保存为命名 `savedToolProfiles`,方便恢复或分享。`enableSessions` 默认关闭,因为常规编辑器自动化不需要跨请求客户端状态。
`enableConsoleLogging` 默认开启。在 **MCP 设置 > 控制台日志 > 打印 MCP 日志** 取消勾选,即可停止扩展及 HTTP 服务向 Cocos 控制台打印 MCP 信息、警告和错误。设置立即生效并按项目保存,不会重启 MCP、清空历史、静音项目脚本日志或影响 stdio 协议输出。
## v0.7.0:项目专属连接与跨渲染帧拖拽
新生成的 MCP 地址使用 `http://127.0.0.1:<端口>/mcp/project/<项目标识>/`,保留已有固定端口。
写入前需独立核对 `initialize.funplay.context` 中的 `project_path` 和 `project_id`,不能把任意响应服务当成目标项目。
旧 `/`、`/mcp` 地址仍允许读取;写入需把核对过的 `expected_context` 放在工具参数或 `params._meta.expected_context` 中。
项目专属地址绑定项目;显式标识还会固定扩展/编辑器实例,重载后旧标识可能失效。这是防串线机制,不是身份认证。
旧客户端可从现有连接/Skills 提示卡显式重新配置,然后重连或重启客户端。
其他项目、手动修改的地址、自定义请求头与超时、历史通用条目和本地 Skills 修改会保留;配置不可读或归属不明时不会自动覆盖。
Full 工具 `simulate_mouse_drag` 默认保留旧 `steps`/`stepDelayMs` 模式。
需要跨渲染帧测试时,显式传入 `timing: "frame-paced"`、`coordinateSpace: "image-pixels"`、
新截图的 `captureId`、唯一的 `requestKey`,以及从该 PNG 量取的起止坐标。
`durationMs` 范围 50~10000,默认 600;`pressHoldMs`、`endHoldMs` 范围 0~2000,默认 100。
`waitMs` 默认 1200,超过等待时间可先返回运行中的回执,而不是宣称拖拽完成。
通过**同一个工具**传 `action: "status"` 和 `jobId` 或 `requestKey` 查询;传 `action: "cancel"` 取消时无需坐标。
相同且仍保留的请求不会重复发送,不同参数复用同一个 key 会报冲突。
仅保留最近 32 份回执,不能跨淘汰或编辑器重载充当持久事务;回执丢失时先检查实际状态,不自动换 key 重放。
`simulate_preview_input` 的拖拽模式也支持这些字段,但回执按原始工具分别归属,并遵守当前工具开放范围。
这里观察的是目标 Electron 渲染器的帧,不是经过验证的原生 Game View 游戏 Update 帧。
回执明确返回 `nativeGameUpdateVerified: false`、`businessOutcomeVerified: false`,游戏行为仍需独立回读或截图确认。
Game View 的暂停/停止状态另行检查;失焦、截图过期、几何变化、帧停滞和取消会中断并尝试释放本次按键。
释放失败时保留窗口锁,需显式取消该任务重试清理;不会自动更改项目输入或后台运行策略。
旧坐标点击/拖拽及使用旧计时的截图校准输入,也会在发送异常后尝试释放本次按下的鼠标。
释放失败时返回投递结果不确定并保留窗口锁,可停止或重启 MCP 重试释放清理;先检查实际状态,勿直接重放手势。
停止服务也会取消仍在等待中的旧鼠标手势,阻止后续输入继续发送。
## 架构
```text
Cocos Creator Extension
├─ browser.js
│ ├─ Embedded HTTP MCP Server
│ ├─ Tool Registry
│ ├─ Resource Provider
│ ├─ Prompt Provider
│ └─ One-Click Client Configuration
├─ scene.js
│ └─ Scene/runtime execution bridge
├─ panel/index.js
│ └─ Minimal MCP Server dashboard
├─ panel/tool-exposure.js, panel/settings.js, panel/project-skills.js
│ └─ Focused maintenance windows
└─ lib/
├─ assets, diagnostics, screenshots, input
├─ tool-profiles, javascript-safety
├─ tools/
│ ├─ files
│ ├─ assets-advanced
│ ├─ cocos-project
│ └─ scene-events
└─ server, resources, prompts, tool registry
```
服务使用 MCP 风格的 HTTP JSON-RPC 2.0,支持 tools、resources、resource templates、prompts、health check 和只读 `/tools` 调试端点。
## 开发
发布改动前可以跑检查:
```bash
npm run check
npm test
npm run docs:check
npm run release:check
npm run pack:dry-run
```
修改 `lib/tool-registry.js` 后可以重新生成工具参考:
```bash
npm run docs:generate
```
生成可上传到 GitHub Release 的扩展包:
```bash
npm run release:package
```
产物会写入 `releases/<version>/`,包含 zip、manifest、生成的 release notes、checksum 和 release README。请上传全部五个文件,确保公开附件可以完整校验。完整流程见 [RELEASE_WORKFLOW.md](./RELEASE_WORKFLOW.md) 和 [RELEASE_CHECKLIST.md](./RELEASE_CHECKLIST.md)。
发布 MCP Registry 前可以验证元数据:
```bash
npm run registry:validate
```
## 协议
MIT License。详见 [LICENSE](./LICENSE)。
@@ -0,0 +1,387 @@
#!/usr/bin/env node
'use strict';
const fs = require('fs');
const http = require('http');
const https = require('https');
const path = require('path');
const DEFAULT_URL = 'http://127.0.0.1:8765/';
const DEFAULT_TIMEOUT_SECONDS = 120;
const ACCEPT_HEADER = 'application/json, text/event-stream';
async function main() {
const args = process.argv.slice(2);
if (hasFlag(args, '--help') || hasFlag(args, '-h')) {
printHelp();
return 0;
}
if (hasFlag(args, '--version')) {
console.error(`funplay-cocos-mcp ${readPackageVersion()}`);
return 0;
}
const urlText = getOption(args, '--url')
|| process.env.FUNPLAY_COCOS_MCP_URL
|| DEFAULT_URL;
const timeoutText = getOption(args, '--timeout-seconds')
|| process.env.FUNPLAY_COCOS_MCP_TIMEOUT_SECONDS
|| String(DEFAULT_TIMEOUT_SECONDS);
const endpoint = parseEndpoint(urlText);
if (!endpoint) {
console.error(`Invalid --url value: ${urlText}`);
return 2;
}
const timeoutSeconds = Number.parseInt(timeoutText, 10);
if (!Number.isFinite(timeoutSeconds) || timeoutSeconds <= 0) {
console.error(`Invalid timeout value: ${timeoutText}`);
return 2;
}
console.error(`[Funplay Cocos MCP] Bridging stdio to ${endpoint.href}`);
await bridgeStdioToHttp({
input: process.stdin,
output: process.stdout,
endpoint,
timeoutMs: timeoutSeconds * 1000
});
return 0;
}
async function bridgeStdioToHttp({ input, output, endpoint, timeoutMs }) {
let sessionId = '';
let activeFraming = 'content-length';
while (true) {
const { message, framing } = await readMessage(input);
if (message === null) {
return;
}
if (framing) {
activeFraming = framing;
}
let parsed = null;
let requestId = null;
try {
parsed = JSON.parse(message);
requestId = getRequestId(parsed);
} catch (error) {
await writeJsonRpcError(output, null, -32700, 'Parse error', activeFraming);
continue;
}
try {
const response = await postJsonRpc(endpoint, message, {
timeoutMs,
sessionId
});
const nextSessionId = response.headers['mcp-session-id'];
if (typeof nextSessionId === 'string' && nextSessionId) {
sessionId = nextSessionId;
}
if (response.statusCode >= 200 && response.statusCode < 300 && response.body.trim()) {
await writeMessage(output, response.body, activeFraming);
continue;
}
if (response.statusCode >= 200 && response.statusCode < 300 && isNotification(parsed)) {
continue;
}
if (requestId !== null) {
const messageText = response.body.trim()
? `Cocos MCP server returned HTTP ${response.statusCode}: ${response.body}`
: `Cocos MCP server returned HTTP ${response.statusCode}.`;
await writeJsonRpcError(output, requestId, -32000, messageText, activeFraming);
}
} catch (error) {
console.error(`[Funplay Cocos MCP] ${error.message}`);
if (requestId !== null) {
await writeJsonRpcError(output, requestId, -32000, `Proxy transport error: ${error.message}`, activeFraming);
}
}
}
}
function postJsonRpc(endpoint, body, { timeoutMs, sessionId }) {
return new Promise((resolve, reject) => {
const client = endpoint.protocol === 'https:' ? https : http;
const request = client.request(
endpoint,
{
method: 'POST',
headers: {
Accept: ACCEPT_HEADER,
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
...(sessionId ? { 'Mcp-Session-Id': sessionId } : {})
},
timeout: timeoutMs
},
(response) => {
const chunks = [];
response.on('data', (chunk) => chunks.push(chunk));
response.on('end', () => {
resolve({
statusCode: response.statusCode || 0,
headers: response.headers,
body: Buffer.concat(chunks).toString('utf8')
});
});
}
);
request.on('timeout', () => {
request.destroy(new Error(`HTTP request timed out after ${timeoutMs / 1000} seconds.`));
});
request.on('error', reject);
request.end(body);
});
}
function parseEndpoint(value) {
try {
const endpoint = new URL(value);
if (endpoint.protocol !== 'http:' && endpoint.protocol !== 'https:') {
return null;
}
return endpoint;
} catch (error) {
return null;
}
}
function getRequestId(value) {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return null;
}
return Object.prototype.hasOwnProperty.call(value, 'id') ? value.id : null;
}
function isNotification(value) {
return Boolean(value && typeof value === 'object' && !Array.isArray(value) && value.method && !Object.prototype.hasOwnProperty.call(value, 'id'));
}
async function writeJsonRpcError(output, id, code, message, framing = 'content-length') {
await writeMessage(output, JSON.stringify({
jsonrpc: '2.0',
id,
error: {
code,
message
}
}), framing);
}
async function readMessage(input) {
const headers = new Map();
while (true) {
const line = await readHeaderLine(input);
if (line === null) {
if (headers.size === 0) {
return { message: null, framing: 'content-length' };
}
return Promise.reject(new Error('Unexpected EOF while reading MCP headers.'));
}
const trimmed = line.trim();
if (headers.size === 0 && (trimmed.startsWith('{') || trimmed.startsWith('['))) {
// Direct NDJSON line (standard MCP stdio specification)
return { message: trimmed, framing: 'ndjson' };
}
if (line === '') {
break;
}
const separator = line.indexOf(':');
if (separator <= 0) {
continue;
}
headers.set(line.slice(0, separator).trim().toLowerCase(), line.slice(separator + 1).trim());
}
const contentLength = Number.parseInt(headers.get('content-length') || '', 10);
if (!Number.isFinite(contentLength) || contentLength < 0) {
throw new Error('Missing Content-Length header.');
}
const payload = await readExact(input, contentLength);
return { message: payload.toString('utf8'), framing: 'content-length' };
}
function readHeaderLine(input) {
return new Promise((resolve, reject) => {
const chunks = [];
function cleanup() {
input.off('readable', onReadable);
input.off('end', onEnd);
input.off('error', onError);
}
function onReadable() {
let byte;
while ((byte = input.read(1)) !== null) {
if (byte[0] === 0x0a) {
cleanup();
if (chunks.length > 0 && chunks[chunks.length - 1][0] === 0x0d) {
chunks.pop();
}
resolve(Buffer.concat(chunks).toString('utf8'));
return;
}
chunks.push(byte);
}
}
function onEnd() {
cleanup();
resolve(chunks.length === 0 ? null : Buffer.concat(chunks).toString('utf8'));
}
function onError(error) {
cleanup();
reject(error);
}
input.on('readable', onReadable);
input.once('end', onEnd);
input.once('error', onError);
onReadable();
});
}
function readExact(input, length) {
return new Promise((resolve, reject) => {
const chunks = [];
let remaining = length;
function cleanup() {
input.off('readable', onReadable);
input.off('end', onEnd);
input.off('error', onError);
}
function onReadable() {
while (remaining > 0) {
const chunk = input.read(remaining);
if (chunk === null) {
return;
}
chunks.push(chunk);
remaining -= chunk.length;
}
cleanup();
resolve(Buffer.concat(chunks, length));
}
function onEnd() {
cleanup();
reject(new Error('Unexpected EOF while reading MCP payload.'));
}
function onError(error) {
cleanup();
reject(error);
}
input.on('readable', onReadable);
input.once('end', onEnd);
input.once('error', onError);
onReadable();
});
}
function writeMessage(output, json, framing = 'content-length') {
const body = framing === 'ndjson' ? JSON.stringify(JSON.parse(json)) : json;
const payload = Buffer.from(body, 'utf8');
return new Promise((resolve, reject) => {
if (framing === 'ndjson') {
output.write(payload, (payloadError) => {
if (payloadError) {
reject(payloadError);
return;
}
output.write('\n', (newlineError) => {
if (newlineError) {
reject(newlineError);
return;
}
resolve();
});
});
return;
}
output.write(`Content-Length: ${payload.length}\r\n\r\n`, 'ascii', (headerError) => {
if (headerError) {
reject(headerError);
return;
}
output.write(payload, (payloadError) => {
if (payloadError) {
reject(payloadError);
return;
}
resolve();
});
});
});
}
function hasFlag(args, name) {
return args.some((arg) => arg.toLowerCase() === name.toLowerCase());
}
function getOption(args, name) {
for (let i = 0; i < args.length - 1; i += 1) {
if (args[i].toLowerCase() === name.toLowerCase()) {
return args[i + 1];
}
}
return '';
}
function readPackageVersion() {
try {
const packagePath = path.resolve(__dirname, '..', 'package.json');
const packageJson = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
return packageJson.version || '0.0.0';
} catch (error) {
return '0.0.0';
}
}
function printHelp() {
console.error('funplay-cocos-mcp');
console.error('Bridges stdio MCP traffic to a local Cocos Creator HTTP MCP server.');
console.error();
console.error('Options:');
console.error(' --url <http://127.0.0.1:8765/> Cocos MCP HTTP endpoint.');
console.error(' --timeout-seconds <120> HTTP timeout per request.');
console.error(' --version Print the proxy version.');
console.error(' --help Show this help.');
console.error();
console.error('Environment:');
console.error(' FUNPLAY_COCOS_MCP_URL');
console.error(' FUNPLAY_COCOS_MCP_TIMEOUT_SECONDS');
}
if (require.main === module) {
main().then((code) => {
process.exitCode = code;
}).catch((error) => {
console.error(`[Funplay Cocos MCP] ${error.message}`);
process.exitCode = 1;
});
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,5 @@
# Funplay MCP for Cocos
面向 Cocos Creator 编辑器的高级 MCP Server,支持 `execute_javascript`、Prompts/Resources、截图、资源依赖校验、工具 Profile、客户端一键配置、按 Creator 版本管理的全局安装和编辑器自动化。
让 Claude Code、Cursor、Codex、VS Code Copilot、Trae、Kiro、Qoder、Kimi Code、OpenCode、CodeBuddy IDE 等 AI 编程助手直接连接正在运行的 Cocos Creator 项目,读取真实编辑器上下文,并辅助完成场景检查、资源分析、日志排查和常用开发工作流。
@@ -0,0 +1,5 @@
# Funplay MCP for Cocos
The Most Advanced MCP Server for Cocos Creator Editor with `execute_javascript`, prompts/resources, screenshots, asset dependency validation, tool profiles, one-click client configuration, version-aware global installation, and editor automation.
Connect AI coding assistants such as Claude Code, Cursor, Codex, VS Code Copilot, Trae, Kiro, Qoder, Kimi Code, OpenCode, and CodeBuddy IDE directly to your running Cocos Creator project, with real editor context for scene inspection, asset analysis, log debugging, and common development workflows.
@@ -0,0 +1,109 @@
# Funplay MCP for Cocos
## 【功能介绍】
Funplay MCP for Cocos 是一款面向 **Cocos Creator 3.8 及以上版本**的开源 AI 开发插件。它将 MCP Server 直接嵌入 Cocos Creator 编辑器,让 Claude Code、Cursor、Codex、VS Code Copilot、Trae、Kiro、Qoder、Kimi Code、OpenCode、CodeBuddy 等支持 MCP 的 AI 编程助手连接当前项目,读取真实编辑器上下文并执行开发工作流。
与只能分析项目文件的普通 AI 助手不同,本插件能够访问当前打开的场景、节点层级、组件、资源、Prefab、日志、脚本诊断、编辑器状态和截图。AI 可以基于项目的实际状态进行分析、修改和验证,减少开发者在编辑器、终端和 AI 客户端之间反复切换。
### 核心能力
- **统一 JavaScript 执行工具**:通过 `execute_javascript` 在场景或编辑器上下文中执行组合操作,适合创建 UI、调整节点、检查运行状态和处理重复性编辑器工作。
- **106 个内置工具**:覆盖场景与节点、组件、资源与 Prefab、文件、日志、脚本诊断、截图、运行状态、构建、预览、事件绑定和输入模拟等常见工作流。
- **真实编辑器上下文**:读取当前项目、活动场景、节点层级、选中对象、资源信息、脚本错误、编辑器日志和最近 MCP 调用记录。
- **场景与资源自动化**:支持创建和打开场景、检查和修改节点及组件、创建 Prefab、分析资源依赖、验证 Prefab 引用并刷新资源数据库。
- **预览与可视化验证**:支持浏览器预览、编辑器 Game View 和模拟器模式,可获取浏览器预览地址,并通过编辑器、场景或预览截图验证结果。
- **一键配置 AI 客户端**:可在插件面板中为 Claude Code、Cursor、Codex、VS Code、Trae、Kiro、Qoder、Kimi Code、OpenCode、CodeBuddy IDE(4.0+)生成或写入 MCP 配置;支持 Skills 的客户端还可一键安装缺少的内置工作流和 UI Skills。
- **灵活的工具 Profile**:默认 `core` Profile 提供 39 个高频工具;需要完整能力时可切换到 `full`,也可以按分类或工具名称自定义暴露范围。
- **多窗口管理面板**:提供风格统一的 MCP Server、Tool Exposure、MCP Settings、Project Skills 窗口,用于管理服务、工具范围、客户端配置和 Skills,不再附带输出或日志查看区域。
- **中英文界面**:菜单和窗口标题跟随 Cocos Creator;窗口内控件与状态提示可跟随 Creator,也可按项目手动指定中文或英文。
- **自动更新与一键更新**:可检查 GitHub Release 新版本,下载更新包并校验 SHA256;普通安装支持面板内更新。
- **一次安装,所有项目可用**:可把经过 SHA256 校验的 Release 安装到当前 Creator 版本管理的全局扩展目录,由该版本打开或新建的项目都能自动加载。
- **本地运行与安全边界**:服务默认只监听 `127.0.0.1`,文件工具限制在当前项目目录内,`execute_javascript` 默认启用高风险操作检查。
- **开放兼容**:同时提供 MCP Tools、Resources 和 Prompts,兼容支持 Streamable HTTP 或 stdio MCP 配置的客户端。
### 适用场景
- 让 AI 快速理解已有 Cocos 项目的场景、资源和代码结构。
- 创建或调整 UI、节点、组件、Prefab 和常用编辑器内容。
- 排查 TypeScript 错误、编辑器日志、资源依赖和 Prefab 引用问题。
- 启动并切换预览模式,通过截图或浏览器地址验证实际效果。
- 为团队建立可复用的 AI 项目指令、工具 Profile 和自动化工作流。
### 兼容性与说明
- 最低支持版本:**Cocos Creator 3.8**。
- 本插件仅在编辑器中运行,不会向最终游戏包添加运行时代码。
- AI 客户端及其模型服务需要由用户自行安装和配置,本插件不包含第三方 AI 服务。
- 新项目使用稳定的项目独立端口,已有固定端口配置保持不变。面板显示实际地址;若端口被占用而临时回退,须先固定端口或解决冲突再一键配置客户端。
- 具备修改能力的工具会直接操作当前项目,建议使用 Git 或其他版本管理工具,并在重要操作前确认改动范围。
## 【使用教程】
1. **安装插件**
从 Cocos Store 将 Funplay MCP for Cocos 安装到目标项目,然后使用 Cocos Creator 3.8 或更高版本打开该项目。
2. **为所有项目启用(推荐)**
打开 `Funplay > MCP Settings`,在“所有项目”区域点击“为所有项目安装”。安装包通过 SHA256 校验后写入当前 Creator 版本管理的全局目录,并让 Creator 扫描和注册它;之后由该版本打开或新建的项目都可以自动加载。当前项目副本会继续运行,重新打开项目后再切换到全局副本;如出现重复安装提示,请先在干净项目中确认全局副本,再移除或禁用项目副本。同时使用多个 Creator 版本时,每个版本需要分别执行一次。
3. **打开控制面板**
在 Cocos Creator 顶部菜单中选择:
`Funplay > MCP Server`
4. **启动 MCP Server**
在面板中确认服务状态并点击启动。默认地址为:
`http://127.0.0.1:8765/`
如果默认端口被占用,请以面板显示的实际运行端口为准。
5. **选择并配置 AI 客户端**
在客户端配置区域选择对应客户端,然后点击一键配置;支持 Skills 的客户端可选择“配置 + Skills”。CodeBuddy IDE 需 4.0 或更高版本,配置写入 Cocos 项目根目录的 `.mcp.json`,Skills 安装到 `.codebuddy/skills`;请在 CodeBuddy 中打开同一项目目录,并按提示启用或批准服务器。也可以复制面板生成的配置,手动添加到其他支持 MCP 的客户端。
6. **确认连接**
回到 AI 客户端,确认 `funplay-cocos-mcp` 已连接并能看到工具列表。首次使用可以先调用 `get_project_info`、`get_scene_info` 或 `get_hierarchy` 检查项目和场景信息。
7. **开始使用**
例如可以向 AI 提出:
> 检查当前场景层级和脚本错误,并告诉我最需要处理的问题。
> 在当前场景创建一个包含标题、输入框和按钮的登录界面,完成后截图验证。
> 切换到浏览器预览模式,启动当前场景并返回预览地址。
8. **按需调整工具范围**
默认 `core` Profile 适合常用检查和开发任务。如果需要文件写入、完整场景编辑、预览切换等更多能力,可在 `Funplay > Tool Exposure` 中切换到 `full` 或创建自定义 Profile。
9. **检查更新**
在 MCP Server 面板中可以检查新版本。普通商店安装可使用一键更新;Git worktree 或软链接开发安装请继续使用 Git 更新,避免覆盖开发目录。
## 【联系方式】
**开源仓库**
https://github.com/FunplayAI/funplay-cocos-mcp
**问题反馈与功能建议**
https://github.com/FunplayAI/funplay-cocos-mcp/issues
**作者**
Funplay / FunplayAI
**联系邮箱**
3256714392@qq.com
本项目采用 MIT 开源协议。欢迎通过 GitHub Issue 提交兼容性问题、功能建议和使用反馈。
@@ -0,0 +1,109 @@
# Funplay MCP for Cocos
## 【Feature Introduction】
Funplay MCP for Cocos is an open-source AI development extension for **Cocos Creator 3.8 and later**. It embeds an MCP Server directly in the Cocos Creator editor, allowing MCP-compatible coding assistants such as Claude Code, Cursor, Codex, VS Code Copilot, Trae, Kiro, Qoder, Kimi Code, OpenCode, and CodeBuddy to connect to the active project, read real editor context, and execute development workflows.
Unlike an assistant that can only analyze project files, Funplay MCP for Cocos can inspect the active scene, node hierarchy, components, assets, prefabs, logs, script diagnostics, editor state, and screenshots. This lets AI work from the project's actual state and helps reduce repeated switching between the editor, terminal, and AI client.
### Key Features
- **Unified JavaScript execution**: Use `execute_javascript` in scene or editor context to combine operations such as creating UI, editing nodes, inspecting runtime state, and automating repetitive editor tasks.
- **106 built-in tools**: Covers scenes and nodes, components, assets and prefabs, files, logs, script diagnostics, screenshots, runtime state, builds, previews, event binding, and input simulation.
- **Live editor context**: Read the current project, active scene, hierarchy, selection, asset metadata, script errors, editor logs, and recent MCP activity.
- **Scene and asset automation**: Create and open scenes, inspect or edit nodes and components, create prefabs, analyze asset dependencies, validate prefab references, and refresh the asset database.
- **Preview and visual verification**: Use Browser Preview, Editor Game View, or Simulator Preview; retrieve the browser preview URL and verify results with editor, scene, or preview screenshots.
- **One-click AI client setup**: Generate or write MCP configuration for Claude Code, Cursor, Codex, VS Code, Trae, Kiro, Qoder, Kimi Code, OpenCode, and CodeBuddy IDE (4.0+) from the extension panel. Supported Skills clients can also install missing built-in workflow and UI Skills in one action.
- **Flexible tool profiles**: The default `core` profile exposes 39 high-signal tools. Switch to `full` for all tools, or create a custom profile by category or individual tool.
- **Focused management windows**: Consistent MCP Server, Tool Exposure, MCP Settings, and Project Skills windows keep service controls, tool exposure, client setup, and skill management organized, without output or log-viewing panels.
- **English and Chinese UI**: Menus and native panel titles follow Cocos Creator; panel controls and status messages can follow Creator or use a project-specific language override.
- **Update checks and one-click updates**: Detect new GitHub Releases, download the extension package, and verify its SHA256 checksum before installation.
- **Install once for every project**: Install a SHA256-verified release in the active Creator version's managed global extension directory so projects opened with that version load it automatically.
- **Local operation and guardrails**: The server listens on `127.0.0.1` by default, file tools stay inside the active project, and risky `execute_javascript` patterns are checked by default.
- **Open MCP compatibility**: Provides MCP Tools, Resources, and Prompts for clients using Streamable HTTP or a stdio MCP configuration.
### Typical Use Cases
- Help AI understand the scenes, assets, and code structure of an existing Cocos project.
- Create or adjust UI, nodes, components, prefabs, and common editor content.
- Diagnose TypeScript errors, editor logs, asset dependencies, and broken prefab references.
- Start and switch preview modes, then verify the result through screenshots or a browser URL.
- Build reusable project instructions, tool profiles, and AI workflows for a team.
### Compatibility and Notes
- Minimum supported version: **Cocos Creator 3.8**.
- This is an editor-only extension and does not add runtime code to the final game build.
- AI clients and model services must be installed and configured separately; no third-party AI service is bundled with the extension.
- New projects use a stable project-derived port; existing fixed endpoints remain unchanged. The panel shows the active address. Pin a temporary fallback port or resolve the conflict before configuring a client.
- Tools with write or mutation capabilities operate directly on the current project. Use Git or another version control system and review the intended scope before major changes.
## 【Usage Guide】
1. **Install the extension**
Install Funplay MCP for Cocos from Cocos Store into the target project, then open the project with Cocos Creator 3.8 or later.
2. **Enable it for all projects (recommended)**
Open `Funplay > MCP Settings` and click **Install for All Projects** in the All Projects section. The package is verified with SHA256 before it is written to the active Creator version's managed global directory, then Creator scans and registers it. Projects subsequently opened or created with that Creator version load it automatically. The current project copy stays active until the project is reopened; if a duplicate-install warning appears, verify the global copy in a clean project before removing or disabling the project copy. Repeat once for each Creator version you use.
3. **Open the control panel**
From the Cocos Creator top menu, select:
`Funplay > MCP Server`
4. **Start the MCP Server**
Check the server status in the panel and start it. The default endpoint is:
`http://127.0.0.1:8765/`
If that port is already in use, use the active port displayed in the panel.
5. **Select and configure an AI client**
Select your client in the configuration section, then use one-click setup or **Configure + Skills** for supported Skills clients. CodeBuddy IDE requires version 4.0 or later: MCP setup uses the Cocos project's `.mcp.json`, and Skills use `.codebuddy/skills`. Open that same project folder in CodeBuddy and enable/approve the server when prompted. You can also copy the generated configuration into another MCP-compatible client manually.
6. **Confirm the connection**
Return to the AI client and confirm that `funplay-cocos-mcp` is connected and its tools are available. For a first test, call `get_project_info`, `get_scene_info`, or `get_hierarchy` to inspect the active project and scene.
7. **Start working**
Example requests:
> Inspect the current scene hierarchy and script errors, then identify the most important issues.
> Create a login UI with a title, input fields, and buttons in the active scene, then capture a screenshot to verify it.
> Switch to Browser Preview, launch the active scene, and return the preview URL.
8. **Adjust tool exposure when needed**
The default `core` profile is suitable for common inspection and development tasks. For file writes, complete scene editing, preview switching, and other advanced operations, open `Funplay > Tool Exposure` and select `full` or create a custom profile.
9. **Check for updates**
Use the MCP Server panel to check for a new release. Standard Store installations can use one-click update. Git worktree or symlink development installations should continue using Git so the updater does not overwrite development files.
## 【Contact】
**Open-source repository**
https://github.com/FunplayAI/funplay-cocos-mcp
**Issue reports and feature requests**
https://github.com/FunplayAI/funplay-cocos-mcp/issues
**Author**
Funplay / FunplayAI
**Contact email**
3256714392@qq.com
This project is available under the MIT License. Compatibility reports, feature requests, and usage feedback are welcome through GitHub Issues.
@@ -0,0 +1,159 @@
# Project isolation, Skills, and workflows
## 多项目与迁移
- 新项目按项目路径生成稳定端口,并使用 `cocos-<project>-<hash>` 配置名称。同名目录位于不同路径时也使用不同名称;端口哈希仍可能冲突,面板会明确显示回退状态。
- 已有 `funplay-cocos-mcp.config.json` 保留固定端口。点击“使用项目独立端口”可以主动切换;“固定当前端口”可保存当前实际端口。切换后需重新配置客户端。
- 临时回退端口不会被一键配置写入客户端。先解决冲突或固定端口,避免重启后指向错误项目。
- 一键配置保留其他 MCP 配置。只有当前编辑器正在运行、旧 `funplay_cocos` 条目准确指向当前端口且仍是工具生成的简单格式时,才会迁移旧条目;其他旧条目保留供人工检查。手动改过地址的项目条目不会被静默覆盖。
- Claude Code 使用 `~/.claude.json` 的 `projects[Git 仓库根目录].mcpServers`,不是所有项目共享的顶层条目。没有 Git 仓库时使用 Cocos 项目目录。这里的 Claude Code 配置不是 Claude Desktop 配置。
- Trae 写入 `<Cocos 项目>/.trae/mcp.json`,与 `.trae/skills` 使用同一个项目根目录。请在 Trae 中打开此 Cocos 项目,并在“设置 > MCP”启用“项目级 MCP”。旧的用户目录 `.trae/mcp.json` 不会被自动修改或迁移。
- Antigravity 的一键配置在当前 Cocos 项目的 `.agents/mcp_config.json` 中写入项目专属 `serverUrl`,并保留其他服务器及已有配置项。请在 Antigravity 中打开此项目并重载 MCP 配置。[Antigravity MCP 文档](https://antigravity.google/docs/mcp/)
- Pi 1.0+ 的一键配置在当前 Cocos 项目的 `.pi/mcp.json` 中保存 Streamable HTTP 地址。从 Cocos 项目目录启动 `pi`,按提示信任项目后即可加载 MCP 和 `.agents/skills`。已信任的会话可执行 `/reload` 再用 `/mcp` 查看状态。[Pi MCP 文档](https://docs.pi.dev/latest/mcp) · [Pi Skills 文档](https://docs.pi.dev/latest/skills)
- CodeBuddy 使用 IDE 4.0 起支持的 `<Cocos 项目>/.mcp.json`,不写 CLI 或旧编辑器插件的全局配置。请在 CodeBuddy 中打开该 Cocos 项目目录,并按客户端提示启用或批准服务器;不会自动放宽 MCP 审批设置。
- DeepSeek Harness(DSH)生成独立的 `<Cocos 项目>/.dsh/funplay-cocos-mcp.patch.json` Cordis 覆盖层,以 JSON(有效 YAML)格式配置官方 `@deepseek-ai/dsh-mcp-client` 的 `streamable-http` 连接。不会修改全局/profile YAML、安装依赖或改变审批设置。**文件不会自动加载**:请在 Cocos 项目目录运行面板显示的 `dsh web --patch '<绝对路径>'`,或给原启动命令追加相同 `--patch` 参数。配置状态表示文件已生成,不代表 DSH 已连接;同一 DSH Host 加载的服务器可被该 Host 的其他会话看到,不应把项目覆盖层当成会话权限隔离。
## Client-specific managed Skills
Open **Funplay > Project Skills**, choose a client, then install either built-in Skill. The MCP Server dashboard checks the selected client's managed directory. Unsupported clients do not show an install/update notice.
The dashboard's **Configure + Skills** action configures the selected MCP client and installs any missing built-in Skills. Existing Skills are kept, including old versions, legacy-path installs and local edits; use Project Skills to review, back up and update them. If configuration succeeds but a Skill cannot be installed, the dashboard reports partial completion instead of claiming the whole setup succeeded.
All management pages share aligned controls, lightweight sections, and responsive layouts. Extension update and global-install controls are in **Settings**. Project Skills hides unavailable actions and collapses file/backup details. Recent Activity preserves each result's field order, nested objects, array items, and scalar values instead of flattening six selected fields. Branches and JSON disclosures retain their expanded state across refreshes. Preview limits are 200 nodes, 6 nested levels, 24 keys per object, 12 items per array, 800 characters per string, and approximately 16,000 total characters; truncation is marked and sensitive fields/file bodies are omitted. Clear removes only MCP interaction history without clearing runtime logs. Output sections and the standalone Activity/log-viewing window are removed. Successful actions show a short, auto-dismissed notice; failures remain visible until dismissed. Diagnostic logs and MCP interaction summaries remain available through the existing MCP tools/resources.
Script cards separate the execution summary, scoped console logs, and return value. `execute_javascript` and both compatibility aliases inject a per-invocation `console` with `log/info/warn/error/debug` capture; `run(env)` and module-export functions also receive `env.console`. Logs before a thrown error survive scene IPC. Capture stops when the script settles and never patches the global console, so concurrent/nested calls, unrelated project logs, separately required modules, and later background callbacks cannot contaminate another call. Console forwarding is unchanged. Capture retains up to 50 entries, 1,000 characters per message, and about 20,000 characters per call, with redaction and an explicit `logsOmitted` count. Protocol responses keep their existing `data` and add optional `execution: { context, durationMs, logs, logsOmitted }` metadata, also on script error envelopes.
**Settings > Console Logs > Print MCP logs** controls only the extension and HTTP server's Cocos console printing, including warnings and errors. It defaults on and is saved as `enableConsoleLogging` in the project config. Changes apply immediately without restarting MCP, disconnecting clients, clearing Recent Activity/internal diagnostics, or muting project-script logs. A saved off setting also suppresses startup printing.
| Client | Managed project directory |
| --- | --- |
| Codex | `.agents/skills` |
| Claude Code | `.claude/skills` |
| Cursor | `.cursor/skills` |
| VS Code / Copilot | `.github/skills` |
| Trae | `.trae/skills` |
| Antigravity | `.agents/skills` (shared with Codex) |
| Pi | `.agents/skills` (shared with Codex and Antigravity) |
| Kiro | `.kiro/skills` |
| Qoder | `.qoder/skills` |
| Kimi Code | `<nearest Git root>/.kimi-code/skills` (project directory when no Git root exists) |
| OpenCode | `.opencode/skills` |
| CodeBuddy | `.codebuddy/skills` |
| DeepSeek Harness (DSH) | `<nearest Git root>/.dsh/skills` (project directory when no Git root exists) |
The manager checks these **managed project directories**, not every user-level or cross-client compatibility directory an agent may also discover. It does not change global Skills, agent rules, or user-authored `AGENTS.md` / `CLAUDE.md` files. Open the AI client at the relevant project/Git root so it can discover the files.
Client paths were checked against the official [Codex](https://learn.chatgpt.com/docs/build-skills#where-codex-loads-local-skills), [Claude Code](https://code.claude.com/docs/en/skills#where-skills-live), [Cursor](https://cursor.com/docs/skills), [VS Code](https://code.visualstudio.com/docs/agent-customization/agent-skills), [Trae](https://docs.trae.cn/ide_skills), [Kiro](https://kiro.dev/docs/skills/), [Qoder](https://docs.qoder.com/cli/Skills), [Kimi Code](https://moonshotai.github.io/kimi-code/en/customization/skills.html#skill-locations), [OpenCode](https://opencode.ai/docs/skills), and [CodeBuddy](https://www.codebuddy.cn/docs/ide/Features/Skills) documentation. CodeBuddy's project MCP location follows its [official IDE release notes](https://intl.cloud.tencent.com/zh/document/product/1256/77264); Trae's location and required Project MCP switch follow its [project MCP guide](https://docs.trae.cn/ide_add-mcp-servers).
DSH's launch overlay and Skills locations follow its official [CLI reference](https://github.com/deepseek-ai/deepseek-harness/blob/master/apps/cli/reference/README.md), [MCP client](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/mcp/mcp-client/README.md), and [filesystem Skills provider](https://github.com/deepseek-ai/deepseek-harness/blob/master/packages/skill/skill-filesystem/README.md). DSH is in developer preview; this integration targets the official launcher rather than guessing third-party desktop configuration paths. A dedicated overlay must remain a single JSON `insert` containing this project's MCP row. Malformed or unrelated content, duplicate keys, disabled entries and manually repointed endpoints are not overwritten. Custom HTTP headers and timeouts are preserved when an owned endpoint changes. DSH Skills follow the Git root, so projects in the same repository share the managed copies and backups.
### Legacy Codex and Antigravity Skills
When a built-in Skill is absent from `.agents/skills`, the manager looks for it in `.codex/skills` for Codex and `.agent/skills` for Antigravity. Updating backs up the old content, retains the original file, and installs the current template in `.agents/skills`. Modified content requires explicit confirmation. Existing backups from the legacy directory are available to restore. Custom Skills can be moved manually. [Antigravity Skills documentation](https://antigravity.google/docs/skills/)
New backups are stored alongside the managed Skills directory, under `skill-backups/<skill-name>/`. Codex, Antigravity, and Pi share the managed copies and backups under `.agents/` in the same project.
### Built-in skill references
Both built-ins now route from a concise `SKILL.md` to conditional references, instead of loading all specialist guidance on every task:
- `funplay-cocos-mcp-workflow/references/project-readiness.md`: exact asset identity, separate import/compile/preview checks, and persistence.
- `funplay-cocos-ui-composition/references/image-to-prefab.md` covers turning a full design image into editable Cocos prefabs, including asset splitting, shared navigation, and region-by-region fidelity acceptance against actual preview captures.
- `funplay-cocos-ui-composition/references/layout-and-adaptation.md`: design baselines, layout ownership, scrolling, and explicitly requested safe-area changes.
- `references/sprites-and-importers.md`, `references/text-and-localization.md`, and `references/input-and-validation.md` in the UI Skill: nine-slice/importers, font/localization checks, and real input/visual validation respectively.
Image generation is optional for the image-to-prefab workflow. The Cocos extension imports assets, builds the prefab, and captures the preview. If a background or icon needs to be created from scratch, use the AI client's available image tools or supply the artwork.
The UI guidance preserves existing project composition and does not proactively introduce SafeArea containers, adaptation scripts, extra margins, or duplicate insets. New adaptation requires an explicit request or a demonstrated overlap confirmed with the user.
Managed metadata tracks hashes for `SKILL.md` and each known reference. A missing/older reference prompts an update even when the entrypoint is current. Modified managed files require a confirmed backup update; an unowned conflicting reference is never overwritten, even with confirmation. Unrelated files are retained. Backups keep their existing `.md` entrypoint and add a `.md.files.json` companion for references and metadata; keep both files together for bundle restore. Legacy backups without a companion restore only the entrypoint. Each file write checks its read snapshot, but the bundle is not a cross-file filesystem transaction; a failed write must be reviewed before retrying.
## Asset Database readiness
Enable the Full profile (or explicitly expose `check_asset_ready` in a custom profile). Example tool arguments:
```json
{"target":"db://assets/ui/Main.prefab","waitMs":1500,"pollIntervalMs":100}
```
This read-only check uses native `query-ready`, asset-info, UUID, and URL queries. An exact target needs imported metadata, matching UUID/URL round trips, and two consecutive stable observations. Omitting `target` checks only database query readiness. `waitMs` is bounded to 0–10,000 ms; zero requests one bounded observation and cannot establish stable readiness. Busy, missing, importing, identity mismatch, timeout, unavailable, and unknown results are not success. No refresh or mutation is retried by this tool.
`ready: true` is **not** proof that the importer queue is empty, source bytes are current, TypeScript compiled, or the runtime loaded the new asset. Check script diagnostics, exact persisted bindings, preview errors and runtime behavior separately. Refresh only the changed source when needed.
## Screenshot-calibrated mouse input
1. Capture the target with an editor/scene/game/preview screenshot tool; inspect the returned native image and `data.geometry`.
2. Use its `captureId` with `coordinateSpace: "image-pixels"`. Coordinates are measured in the **exact returned PNG**, from its top-left corner, not a resized chat preview or a reference design image.
3. Read back the resulting state or capture another screenshot to verify the requested action.
Example click arguments (replace the ID and coordinates with the actual capture):
```json
{"coordinateSpace":"image-pixels","captureId":"capture_from_the_response","x":420,"y":260}
```
Supported by `simulate_mouse_click`, `simulate_mouse_drag`, and mouse actions of `simulate_preview_input`. Drag uses `startX/startY/endX/endY` in the same PNG. `windowId` can select an exact Electron window for capture and legacy input; a missing explicit target never falls back to a different window. Calibrated input targets the receipt's original window/project and does not require repeating its window/panel selectors.
Metadata includes actual encoded image dimensions, viewport DPR/zoom, crop origin, and per-axis pixel-to-window scale. Receipts expire after 60 seconds, are bounded to 32 entries, and disappear when the extension reloads. Both endpoints are validated; hidden/destroyed windows, viewport/zoom/crop changes, renderer/canvas replacement, and observed editor scene changes require recapture. Scene identity and observable geometry are checked, not every runtime business-state change: `runtimeContentVerified` remains false, and cross-origin frame reloads may not be observable.
Successful input reports `events_submitted` with `businessOutcomeVerified: false`. Failure reports `INPUT_NOT_SENT` or `INPUT_OUTCOME_UNKNOWN`; after a partial dispatch, the extension attempts a mouse-button release but never replays the action. Inspect state before retrying an uncertain outcome. Synthetic events are not proof of Button hit testing, absence of occlusion, or gameplay success. Desktop screenshots cannot calibrate Electron input. Omitting `coordinateSpace` preserves legacy window coordinates and panel-center offsets; keyboard input is unchanged.
## Project-authored MCP prompts
Create Markdown files in `<Cocos project>/mcp-prompts/`. These are MCP workflow templates, not executable scripts or automatically applied instructions. A client explicitly requests a template through `prompts/get`.
Example: `mcp-prompts/inspect-prefab.md`
```markdown
---
name: inspect_prefab
description: Inspect a Cocos prefab without modifying it.
arguments: prefab_path(required), focus
---
Inspect prefab {prefab_path}. Focus: {focus}.
1. Read cocos://project/context and confirm the active Cocos project.
2. Resolve the exact asset URL and UUID. Inspect the prefab and its references using the exposed tool catalog.
3. Report missing references, unexpected layers, or hierarchy problems with exact asset/node identifiers.
This workflow is read-only. Do not rebuild or modify the prefab.
```
```json
{
"jsonrpc": "2.0",
"id": 1,
"method": "prompts/get",
"params": {
"name": "inspect_prefab",
"arguments": {
"prefab_path": "db://assets/ui/Main.prefab",
"focus": "UI_2D layers and serialized references"
}
}
}
```
- The frontmatter is a small dependency-free format, **not general YAML**: unquoted single-line `name`, `description`, and comma-separated `arguments` only. A `(required)` suffix marks mandatory arguments.
- Names match `[a-z][a-z0-9_-]{0,63}`. Descriptions are at most 512 characters. The body must not be empty.
- Argument values must be strings. Missing required values, unknown names/arguments, and non-string values return JSON-RPC `-32602`. Omitted optional placeholders become empty strings. Substitution is single-pass and never evaluates code.
- Built-in names cannot be shadowed. Duplicate names, oversized files, malformed definitions, and symlinks are skipped with warnings in the Cocos editor console and MCP diagnostic logs.
- Discovery is limited to the first 100 top-level `.md` files in name order, each at most 256 KiB. Prompt arguments are limited to 65,536 characters each.
- Files are re-read on `prompts/list` and `prompts/get`; no editor restart is required. Clients that cache the prompt list may need a refresh/reconnect. The server does not advertise prompt-list change notifications.
- Existing built-in prompts remain callable without arguments. Optional context arguments are `touched_paths`, `idea`, `focus`, and `target` / `component_type`, respectively.
## Connection examples
Use the exact server name and URL in the MCP Server panel. Documentation examples containing `funplay_cocos` and port `8765` illustrate a legacy/fixed endpoint, not the new default. The stdio wrapper's legacy default is also `8765`; pass `--url` or `FUNPLAY_COCOS_MCP_URL` explicitly for a project-derived port.
Generated JSON preserves unrelated settings and entries. VS Code, OpenCode, and CodeBuddy accept comment-preserving JSONC edits; strict-JSON clients still reject comments and trailing commas. Duplicate keys and malformed/non-object configurations are left untouched with an error. Disabled or command-based entries require manual review instead of being reported as configured HTTP connections. TOML updates preserve unrelated sections and options, accept an empty `[mcp_servers]` parent with explicit server tables, and leave ambiguous forms such as inline MCP tables or multiline strings to manual configuration. Codex respects `CODEX_HOME`. VS Code uses the canonical platform-specific user-profile path even before that directory exists, including its portable/appdata overrides. OpenCode retains existing `mcp.servers` nesting or compatible V1 flat entries without migrating custom options. Configuration writes preserve file permissions and reject a changed read snapshot before atomic replacement.
To pin a port explicitly in `funplay-cocos-mcp.config.json`:
```json
{
"host": "127.0.0.1",
"portMode": "fixed",
"port": 8765
}
```
Use `"portMode": "project"` to derive the port again. `COCOS_MCP_PORT` overrides the saved choice for that editor process.
+240
View File
@@ -0,0 +1,240 @@
# Tool Reference
<!-- This file is generated by `npm run docs:generate`. Do not edit by hand. -->
Generated from `lib/tool-registry.js`. The default `core` profile exposes 39 tools; the `full` profile exposes 106 tools.
## Profile Summary
| Profile | Tool Count | Purpose |
|---|---:|---|
| `core` | 39 | Focused default surface for common editor automation. |
| `full` | 106 | All built-in tools, including destructive and low-level helpers. |
## Core Tools
`capture_editor_screenshot`, `capture_preview_screenshot`, `capture_scene_screenshot`, `check_for_updates`, `clear_logs`, `create_scene`, `execute_editor_script`, `execute_javascript`, `execute_scene_script`, `get_build_status`, `get_editor_state`, `get_hierarchy`, `get_performance_snapshot`, `get_preview_mode`, `get_project_info`, `get_recent_logs`, `get_runtime_state`, `get_scene_info`, `get_script_diagnostic_context`, `get_selection`, `get_tool_catalog`, `inspect_asset`, `inspect_asset_dependencies`, `inspect_prefab`, `inspect_prefab_instance`, `list_assets`, `list_editor_windows`, `list_project_instructions`, `list_scenes`, `open_asset`, `open_scene`, `read_project_instruction`, `run_script_diagnostics`, `search_project_logs`, `select_asset`, `set_selection`, `validate_asset_dependencies`, `validate_prefab_references`, `validate_scene`
## Tools By Category
### Animation
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `add_animation_clip` | `full` | stateful | Add an AnimationClip asset to a node Animation component. |
| `list_animations` | `full` | read-only | [core] List Animation components in the active scene or under one node. |
| `play_animation` | `full` | stateful | [core] Play an Animation component clip on a node. |
| `stop_animation` | `full` | stateful | [core] Stop an Animation component clip on a node. |
### Assets
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `check_asset_ready` | `full` | read-only | [specialist] Check bounded AssetDB readiness and optionally a stable imported UUID/URL identity. Does not prove importer queue, script compilation, source bytes, or runtime loading completion. |
| `create_scene` | `core`, `full` | stateful | [core] Create an empty scene or a copy of the active scene at an explicit assets path without opening an interactive save dialog. |
| `delete_asset` | `full` | mutating | Delete an asset from asset-db by uuid, db url, or path. |
| `inspect_asset` | `core`, `full` | read-only | [specialist] Inspect asset-db info, metadata, and serialized asset data by uuid or path. Prefer this when you need a precise structured asset read. |
| `inspect_asset_dependencies` | `core`, `full` | read-only | [specialist] Inspect UUID-style dependencies referenced by a serialized Cocos asset. |
| `list_assets` | `core`, `full` | read-only | [specialist] Query project assets from asset-db by pattern or asset type. Prefer this when you need exact asset discovery; otherwise use execute_javascript for broader automation. |
| `list_scenes` | `core`, `full` | read-only | [specialist] List scene assets in the project. Prefer this when you need exact scene discovery before opening one; otherwise stay in execute_javascript for broader workflows. |
| `open_asset` | `core`, `full` | stateful | [specialist] Open an asset inside Cocos Creator by uuid, db url, or path. Use this only when opening the asset itself is the explicit next step. |
| `open_scene` | `core`, `full` | stateful | [specialist] Open a scene asset in Cocos Creator by uuid, db url, or path. Use this when scene switching is the explicit goal; otherwise keep execute_javascript as the main planning tool. |
| `run_scene_asset` | `full` | mutating | Load a scene asset by uuid directly into the current runtime scene context. |
| `select_asset` | `core`, `full` | stateful | [specialist] Select an asset in the Cocos editor. Use this when editor selection state matters; otherwise keep execute_javascript as the primary workflow. |
### Broadcast
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `broadcast_editor_message` | `full` | stateful | [core] Send or broadcast a Cocos editor message for advanced editor automation. |
### Build
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `get_build_status` | `core`, `full` | read-only | [specialist] Query Cocos build/preview status using known builder message variants. |
| `get_preview_mode` | `core`, `full` | read-only | [specialist] Query the active Cocos Creator preview mode. Browser results use a same-host loopback url/localUrl and preserve Creator's reported LAN address as networkUrl. |
| `open_build_panel` | `full` | stateful | [core] Open the Cocos build panel, defaulting to the builder panel id. |
| `run_project_preview` | `full` | stateful | [core] Start Cocos Creator 3.8.x preview in browser, editor Game View, or simulator mode. Game View uses the native toolbar and does not toggle off an already running preview. Browser results use a same-host loopback url/localUrl and preserve Creator's reported LAN address as networkUrl. |
| `save_current_scene` | `full` | stateful | [core] Save the currently open Cocos scene using available editor scene messages. |
| `set_preview_mode` | `full` | mutating | [core] Switch Cocos Creator 3.8.x preview mode through the native toolbar, synchronizing its state and stopping Game View before switching away. |
### Camera
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `create_camera` | `full` | stateful | Create a Camera node in the active scene. |
| `list_cameras` | `full` | read-only | [core] List Camera components in the active scene. |
| `set_camera_properties` | `full` | mutating | Set selected Camera component properties. |
### Components
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `add_component` | `full` | stateful | Add a component to a node by component class name. |
| `inspect_component` | `full` | read-only | [core] Inspect a component attached to a node. |
| `invoke_component_method` | `full` | mutating | [core] Invoke a method on a component for runtime validation and test hooks. |
| `list_components` | `full` | read-only | [core] List components attached to a scene node. |
| `remove_component` | `full` | mutating | Remove a component from a node by name or index. |
| `reset_component_property` | `full` | mutating | Reset or clear a component property by dot path. |
| `set_component_property` | `full` | mutating | Set a component property by dot path using a JSON value. |
### Diagnostics
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `get_script_diagnostic_context` | `core`, `full` | read-only | [specialist] Run TypeScript diagnostics and attach source snippets for each error. This is a preferred specialist tool for compile-error triage before repair. |
| `run_script_diagnostics` | `core`, `full` | stateful | [specialist] Run a TypeScript no-emit check for the current Cocos project and return parsed diagnostics. This is a preferred specialist tool for script errors when diagnostics are needed. |
| `validate_asset_dependencies` | `core`, `full` | read-only | [specialist] Validate UUID-style dependencies for one asset or a project asset query. |
| `validate_prefab_references` | `core`, `full` | read-only | [specialist] Validate prefab asset references by checking serialized UUID references against asset-db. |
| `validate_scene` | `core`, `full` | read-only | [specialist] Run a compact validation pass over the active scene, runtime state, TypeScript diagnostics, and recent project log errors. |
### Events
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `bind_button_click_event` | `full` | stateful | [core] Bind a Cocos Button click event to a target node component method. |
| `emit_node_event` | `full` | mutating | [core] Emit a custom event on a target scene node with an optional JSON payload. |
| `list_button_click_events` | `full` | read-only | [core] List click event bindings on a Cocos Button component. |
| `simulate_button_click` | `full` | mutating | [core] Simulate a Cocos Button click by emitting click events on the target button node. |
### Execution
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `execute_editor_script` | `core`, `full` | mutating | [compat] Execute JavaScript in the editor/browser context. Prefer execute_javascript with context="editor" as the main unified tool; use this when you specifically want the editor-only compatibility entrypoint. |
| `execute_javascript` | `core`, `full` | mutating | [primary] Execute JavaScript in either the scene or editor context. Use context="scene" for live scene/runtime inspection and mutation, or context="editor" for Editor APIs, asset-db workflows, MCP orchestration, local filesystem access, and higher-level automation. Prefer this as the main flexible tool when many narrow tools would be noisy. |
### Files
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `exists` | `full` | read-only | [core] Check whether a project file or directory exists. |
| `get_file_snippet` | `full` | read-only | [core] Read a focused snippet around a file line number. |
| `list_directory` | `full` | read-only | [core] List files and directories inside a project directory. |
| `read_file` | `full` | read-only | [core] Read a file from the Cocos project. |
| `refresh_assets` | `full` | stateful | [core] Best-effort asset database refresh for a file or the assets root. |
| `replace_in_file` | `full` | mutating | [core] Replace text in a file, useful for script auto-fix loops. |
| `search_files` | `full` | read-only | [core] Search project files by simple wildcard pattern. |
| `write_file` | `full` | mutating | [core] Write or overwrite a file in the Cocos project. |
### Input
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `simulate_key_combo` | `full` | mutating | [core] Send a low-level Electron modified key press such as Ctrl+S or Cmd+P. |
| `simulate_key_press` | `full` | mutating | [core] Send a low-level Electron key press to the editor, preview, or simulator window. |
| `simulate_mouse_click` | `full` | mutating | [core] Send a low-level Electron mouse click to the editor, preview, or simulator window. |
| `simulate_mouse_drag` | `full` | mutating | [core] Send an Electron mouse drag. Legacy steps remain supported; opt into frame-paced timing for bounded, cancellable, idempotent movement across target-renderer frames. Frame delivery is not gameplay acceptance. |
| `simulate_preview_input` | `full` | mutating | [core] Preview/simulator input wrapper. Defaults to click or key press; drag mode also supports frame-paced timing and same-tool status/cancel receipts. Renderer input delivery is not game acceptance. |
### Instructions
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `create_cocos_mcp_project_skill` | `full` | stateful | [core] Create the recommended Funplay Cocos MCP workflow Skill for a supported client (defaults to Codex). |
| `create_project_skill` | `full` | stateful | [core] Create a project Skill for a supported client. Defaults to Codex under .agents/skills. |
| `list_project_instructions` | `core`, `full` | read-only | [specialist] List project AI instruction files and Skills for a supported client (defaults to Codex). |
| `read_project_instruction` | `core`, `full` | read-only | [specialist] Read a project AI instruction file such as AGENTS.md, CLAUDE.md, or a project SKILL.md. |
| `write_project_instruction` | `full` | mutating | [core] Create or update a project AI instruction file inside the Cocos project. |
### Logs
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `clear_logs` | `core`, `full` | mutating | [specialist] Clear in-memory MCP logs and, only with explicit confirmation, truncate common project log files. |
| `get_recent_logs` | `core`, `full` | read-only | [specialist] Return recent MCP runtime logs, recent tool interactions, and tails of common project log files. |
| `search_project_logs` | `core`, `full` | read-only | [specialist] Search common Cocos project log files for a string or regular expression. |
### Other
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `get_performance_snapshot` | `core`, `full` | read-only | [specialist] Return edit-scene scale and performance-oriented counters such as node/component counts, UI counts, depth, memory, and warnings. Its director counters are not Game View preview state. |
| `list_editor_windows` | `core`, `full` | read-only | [specialist] List available Electron windows so screenshots or input-targeting can choose the correct window. Use this when window targeting is the explicit problem. |
### Prefabs
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `apply_prefab_instance` | `full` | stateful | [core] Apply a scene prefab instance back to its associated prefab asset using the Cocos editor scene apply-prefab message. |
| `create_prefab_from_node` | `full` | stateful | [core] Create a prefab asset from an existing scene node using scene-process serialization and asset-db persistence. The cloned hierarchy is normalized to UI_2D without modifying the source nodes. Use this instead of raw scene:create-prefab on Cocos Creator 3.8.x. |
| `create_prefab_instance` | `full` | stateful | [core] Create and verify a linked prefab instance in the editor hierarchy using Cocos scene create-node when available. |
| `duplicate_prefab` | `full` | stateful | [core] Create a new prefab asset by duplicating an existing prefab file without copying its .meta UUID. |
| `edit_prefab_json` | `full` | stateful | [core] Edit a prefab JSON file by JSON path assignment or literal search/replace, then validate references. |
| `inspect_prefab` | `core`, `full` | read-only | [specialist] Inspect a prefab asset, its metadata, serialized file path, and UUID-like asset references. |
| `inspect_prefab_instance` | `core`, `full` | read-only | [specialist] Inspect whether a scene node is linked to a prefab instance and return prefab metadata when available. |
| `instantiate_prefab` | `full` | stateful | Instantiate a prefab into the active scene by prefab uuid. |
| `list_prefabs` | `full` | read-only | [core] List prefab assets in the project. |
| `revert_prefab_instance` | `full` | stateful | [core] Revert a scene prefab instance from its associated prefab asset using available Cocos editor prefab revert messages. |
### Preferences
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `get_editor_preference` | `full` | read-only | [core] Read a Cocos editor preference through Editor.Profile when available. |
| `set_editor_preference` | `full` | mutating | [core] Write a Cocos editor preference through Editor.Profile when available. |
### Project
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `get_editor_state` | `core`, `full` | read-only | [specialist] Return a structured editor-state snapshot including project info, runtime server status, current selection, and visible Electron windows. Prefer this when you want one compact editor summary. |
| `get_project_info` | `core`, `full` | read-only | [specialist] Return the active Cocos project path, version, and MCP server configuration. Prefer this for a fast structured project summary; use execute_javascript when you need to inspect and act in one step. |
| `get_tool_catalog` | `core`, `full` | read-only | [specialist] Return every built-in MCP tool with profile, category, and current exposure state. Use this before changing custom tool exposure. |
### Runtime
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `get_runtime_state` | `core`, `full` | read-only | [specialist] Return the editor Game View preview running/paused state and toolbar synchronization status, not edit-scene director counters. Does not inspect browser or simulator runtime state. |
| `pause_runtime` | `full` | stateful | [core] Pause an active editor Game View preview through the native toolbar. Idempotent; does not pause the edit-scene director, browser, or simulator. |
| `resume_runtime` | `full` | stateful | [core] Resume a paused editor Game View preview through the native toolbar. Idempotent; requires a running Game View preview. |
| `set_time_scale` | `full` | mutating | [core] Set the edit-scene Cocos scheduler time scale. Does not change the separate Game View preview runtime. |
### Scene
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `create_node` | `full` | stateful | Create a new node under the active scene or a specified parent path. |
| `delete_node` | `full` | mutating | Delete a node by path, uuid, or name. |
| `execute_scene_script` | `core`, `full` | mutating | [compat] Execute JavaScript in the active Cocos scene context. Prefer execute_javascript with context="scene" as the main unified tool; use this when you specifically want the scene-only compatibility entrypoint. |
| `find_nodes` | `full` | read-only | [core] Find scene nodes by exact name, partial path, or component type. |
| `get_hierarchy` | `core`, `full` | read-only | [specialist] Return a structured hierarchy tree from the active scene or a specific node path. Prefer execute_javascript for broader reasoning or repair; use this when you want a predictable hierarchy snapshot. |
| `get_scene_info` | `core`, `full` | read-only | [specialist] Return a structured summary of the active Cocos scene. Prefer execute_javascript for multi-step inspection or mutation; use this when you specifically want a compact scene snapshot. |
| `inspect_node` | `full` | read-only | [core] Inspect a specific node by path, uuid, or name. |
| `set_node_transform` | `full` | mutating | Update node position, rotation, scale, or active state. |
### Screenshots
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `capture_desktop_screenshot` | `full` | read-only | [core] Capture a screenshot from the local desktop and return it as an MCP image payload. |
| `capture_editor_screenshot` | `core`, `full` | read-only | [specialist] Capture the focused Cocos Creator editor window and return it as an MCP image payload. Prefer screenshot tools only when visual verification is explicitly needed. |
| `capture_game_screenshot` | `full` | read-only | [core] Capture the visible Cocos Game View or GameCanvas from the selected window. Reports an error when no game viewport is visible. |
| `capture_preview_screenshot` | `core`, `full` | read-only | [specialist] Capture the preview or simulator window as an MCP image payload. Prefer this only when you need visual proof of game or preview output. |
| `capture_scene_screenshot` | `core`, `full` | read-only | [specialist] Capture the Scene panel region from the editor window with panel-level cropping when available. Prefer this only for visual validation of scene-side results. |
### Selection
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `get_editor_selection` | `full` | read-only | [compat] Return the current node and asset selection in the Cocos editor. Prefer get_selection as the primary structured selection read tool. |
| `get_selection` | `core`, `full` | read-only | [specialist] Return the current editor selection in a compact structured form. Prefer this when selection state matters for the next action. |
| `set_selection` | `core`, `full` | mutating | [specialist] Set or clear the current editor selection for an asset or node. Use this when downstream editor workflows depend on selection state. |
### Ui
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `create_button` | `full` | stateful | Create a UI Button node with child Label. |
| `create_canvas` | `full` | stateful | Create a Cocos Canvas node with UITransform. |
| `create_label` | `full` | stateful | Create a UI Label node under a parent. |
| `create_sprite` | `full` | stateful | Create a UI Sprite node, optionally assigning a SpriteFrame asset uuid. |
### Updates
| Tool | Profiles | Access | Description |
|---|---|---|---|
| `check_for_updates` | `core`, `full` | read-only | [specialist] Check the latest Funplay Cocos MCP GitHub release and compare it with the installed extension version. |
+295
View File
@@ -0,0 +1,295 @@
'use strict';
module.exports = {
language_code: 'en',
title: 'Funplay Cocos MCP',
panel_server: 'MCP Server',
panel_tool_exposure: 'Tool Exposure',
panel_settings: 'MCP Settings',
panel_project_skills: 'Project Skills',
panel_contact: 'Contact & Feedback',
menu_server: 'MCP Server',
menu_tool_exposure: 'Tool Exposure',
menu_settings: 'MCP Settings',
menu_project_skills: 'Project Skills',
menu_contact: 'Contact & Feedback',
'common.dismiss': 'Dismiss',
'common.action_completed': 'Done.',
'common.action_failed': 'The action did not complete.',
'common.copy_failed': 'Could not copy. Check clipboard permissions and try again.',
'skills_manager.file_details': 'Location & backups',
'common.unknown': 'Unknown',
'common.clear': 'Clear',
'common.yes': 'Yes',
'common.no': 'No',
'common.enable': 'Enable',
'common.disable': 'Disable',
'common.select': 'Select',
'common.save': 'Save',
'common.apply': 'Apply',
'common.delete': 'Delete',
'common.export': 'Export',
'common.import': 'Import',
'common.refresh': 'Refresh',
'common.copy_url': 'Copy URL',
'common.copy_health_curl': 'Copy Health Curl',
'common.copy_tools_curl': 'Copy Tools Curl',
'common.configuration_saved': 'Configuration saved.',
'common.save_failed': 'Save config failed: {error}',
'common.error': 'Error: {error}',
'common.nothing_to_copy': 'Nothing to copy.',
'dashboard.version': 'Version {version}',
'dashboard.running': 'Running',
'dashboard.stopped': 'Stopped',
'dashboard.project': 'Project',
'dashboard.port_fallback': 'Port fallback: {requested} -> {actual}',
'dashboard.attached_listener': 'Attached listener',
'dashboard.service': 'Service',
'dashboard.server_port': 'Server Port',
'dashboard.server_host': 'Server Host',
'dashboard.apply_host': 'Apply Host',
'dashboard.host_hint': 'Use an address assigned to this machine; 127.0.0.1 is local only. Apply Host retries when MCP is enabled. Network/wildcard addresses can expose unauthenticated editor access; use only on a trusted network. Reconfigure clients after changing Host.',
'dashboard.host_env_hint': 'COCOS_MCP_HOST overrides the project Host. Change that environment variable and restart Cocos Creator; editing the JSON file cannot override it.',
'dashboard.start_error': 'MCP could not listen on {host}:{port}: {error}. The extension is still available. Check Server Host (use 127.0.0.1 for local access), then Apply Host or Restart. No automatic Host fallback was made.',
'dashboard.derived_port_hint': 'Derived from this project’s path ({port}).',
'dashboard.fixed_port_hint': 'Fixed port. Project-derived ports help keep projects separate.',
'dashboard.client_setup': 'One-Click MCP Configuration',
'dashboard.configure_short': 'Configure',
'dashboard.configure_skills': 'Configure + Skills',
'client.status': 'Status',
'client.needs_reconfigure': 'Reconnect with a project-bound URL',
'client.legacy_endpoint': 'This client still uses an unbound URL. Reconfigure MCP, then reconnect/restart the client; legacy URLs allow reads but writes need a verified project/Editor context. Existing Skills and local edits are preserved.',
'client.legacy_unverified': 'This old endpoint has no verified ownership record. Start this project’s MCP server first, or review the entry manually; no unverified endpoint will be overwritten.',
'client.config_read_error': 'Client configuration needs review: {error}',
'client.reconfigure': 'Reconfigure MCP',
'client.reconfigure_skills': 'Reconfigure MCP + Skills',
'client.skills_setup_hint': 'Configure + Skills installs missing built-ins. Existing Skills are kept.',
'client.trae_project_hint': 'In Trae, open this Cocos project folder and enable Project MCP in Settings > MCP to load .trae/mcp.json. Project Skills are installed in .trae/skills.',
'client.antigravity_project_hint': 'Open this Cocos project folder in Antigravity and reload its MCP configuration. It reads .agents/mcp_config.json and discovers project Skills in .agents/skills.',
'client.pi_project_hint': 'Start Pi 1.0+ in this Cocos project directory and trust the project when prompted. Pi reads .pi/mcp.json and .agents/skills. In a trusted session, run /reload and check /mcp.',
'client.configuring': 'Configuring…',
'client.configure_complete': 'Client configured. Reconnect it to load this project.',
'client.patch_generated': 'Overlay generated (load with --patch)',
'client.patch_configure_complete': 'DSH overlay saved. It is not loaded automatically.',
'client.patch_setup_complete': 'DSH overlay saved; {count} Skill(s) installed. Load the overlay explicitly.',
'client.patch_launch_hint': 'Start DSH from this Cocos project directory (or add the same --patch argument to your existing launch command):\n{command}',
'client.setup_complete': 'Client configured; {count} Skill(s) installed. Reconnect the client to load changes.',
'client.setup_review': 'Client configured; {count} Skill(s) installed. Existing Skills needing review were kept — open Project Skills to update them.',
'client.configure_failed': 'Configuration failed: {error}',
'client.setup_partial': 'Client configuration was saved, but Skills setup did not finish: {error}',
'settings.updates': 'Extension Updates',
'settings.console_logs': 'Console Logs',
'settings.print_mcp_logs': 'Print MCP logs',
'settings.print_mcp_logs_hint': 'Immediately controls MCP messages, warnings, and errors printed to the Cocos console. Recent Activity, internal diagnostics, and project-script logs are unaffected.',
'installation.short_duplicate': 'Project and global copies detected. See Settings for details.',
'installation.short_error': 'Global installation needs attention. See Settings for details.',
'dashboard.use_project_port': 'Use Per-Project Port',
'dashboard.pin_current_port': 'Pin Current Port',
'client.fallback_blocked': 'A temporary fallback port is active. Pin Current Port or Use Per-Project Port before configuring the client.',
'dashboard.tool_exposure': 'Tool Exposure',
'dashboard.enable_server': 'Enable MCP Server',
'dashboard.restart': 'Restart',
'dashboard.check_updates': 'Check Updates',
'dashboard.open_release': 'Open Release',
'dashboard.install_update': 'Install Update',
'dashboard.edit_tools': 'Edit Tools',
'dashboard.settings': 'Settings',
'dashboard.recent_activity': 'Recent Activity',
'activity.tool_fallback': 'tool',
'activity.no_calls': 'No recent MCP calls.',
'activity.log_badge': 'Entry',
'activity.result_preview': 'Result JSON · size-limited and redacted',
'activity.call_completed': 'Call completed.',
'activity.execution_completed': 'Script executed.',
'activity.execution_failed': 'Script execution failed.',
'activity.execution_logs': 'Execution logs',
'activity.no_execution_logs': 'No console output in this call.',
'activity.return_value': 'Return value',
'activity.result': 'Result',
'activity.context_editor': 'Editor',
'activity.context_scene': 'Scene',
'activity.items_omitted': '{count} more entries omitted (preview limit).',
'activity.logs_omitted': '{count} more log entries omitted (capture limit).',
'activity.field_message': 'Message',
'activity.field_summary': 'Summary',
'activity.field_sceneName': 'Scene',
'activity.field_projectName': 'Project',
'activity.field_cocosVersion': 'Cocos version',
'activity.field_running': 'Running',
'activity.field_childCount': 'Children',
'activity.field_nodeCount': 'Nodes',
'activity.field_count': 'Count',
'activity.field_name': 'Name',
'activity.field_toolProfile': 'Tool profile',
'activity.field_port': 'Port',
'activity.field_path': 'Path',
'activity.field_url': 'URL',
'dashboard.project_skills': 'Project Skills',
'dashboard.mcp_client': 'MCP Client',
'dashboard.configure_client': 'One-Click Configure',
'dashboard.preview_config': 'Preview selected config',
'updates.reload_scheduled': 'Reload scheduled in {delay}ms',
'updates.reload_not_scheduled': 'Reload not scheduled: {reason}',
'updates.installed': 'Installed {version}. {reload}. Backup: {backup}',
'updates.check_failed': 'Update check failed: {error}',
'updates.published': ', published {date}',
'updates.available': 'Update available: {version}{published}. {status}',
'updates.ready': 'Ready to install.',
'updates.incomplete': 'Release assets are incomplete; install manually.',
'updates.auto_check_failed': 'Automatic update check failed: {error}',
'updates.none_installable': 'No installable update is available.',
'updates.confirm_title': 'Install Funplay Cocos MCP {version} now?',
'updates.confirm_body': 'The updater will verify SHA256SUMS.txt, back up the current extension, replace the package files, and reload the extension when Cocos supports it.',
'tools.title': 'Tool Exposure',
'tools.hint': 'Edit exactly which tools MCP clients can see. Changes restart the running server automatically.',
'tools.edit_list': 'Edit Tool List',
'tools.profile_core': 'Core',
'tools.profile_full': 'Full',
'tools.profile_custom': 'Custom',
'tools.tools': 'Tools',
'tools.select_all': 'Select All',
'tools.use_default': 'Use Default',
'tools.named_profiles': 'Named Profiles',
'tools.profile_name': 'Profile name',
'tools.raw_lists': 'Raw Include / Exclude Lists',
'tools.enabled_categories': 'Enabled Categories',
'tools.disabled_categories': 'Disabled Categories',
'tools.enabled_tools': 'Enabled Tools',
'tools.disabled_tools': 'Disabled Tools',
'tools.saved_profile': 'Profile: {name}',
'tools.full_hint': 'full exposes every registered tool.',
'tools.custom_hint': 'custom uses your include/exclude rules.',
'tools.core_hint': 'core keeps the client tool list focused.',
'tools.dashboard_summary': 'Active: {profile}{saved} | {enabled}/{total} tools. {hint}',
'tools.exposure_summary': 'Active: {profile}{saved} | {enabled}/{total} tools ({source})',
'tools.with_overrides': 'with overrides',
'tools.default_list': 'default list',
'tools.profile_name_required': 'Profile name is required.',
'tools.no_saved_profiles': 'No saved profiles',
'tools.no_profile_selected': 'Select a saved profile first.',
'tools.profiles_copied': 'Copied tool profiles to clipboard.',
'tools.no_profiles_found': 'No profiles found.',
'tools.import_failed': 'Import profiles failed: {error}',
'tools.exposure_saved': 'Tool exposure saved: {name} {state}.',
'tools.enabled': 'enabled',
'tools.disabled': 'disabled',
'settings.title': 'MCP Settings',
'settings.hint': 'Project-level defaults for interface, transport, JavaScript safety, and local diagnostics.',
'settings.interface': 'Interface',
'settings.language': 'Language',
'settings.language_auto': 'Follow Cocos Creator',
'settings.language_zh': 'Chinese',
'settings.language_en': 'English',
'settings.language_auto_hint': 'The panel follows the current Cocos Creator language ({language}).',
'settings.language_override_hint': 'The panel language is fixed to {language} for this project.',
'settings.language_name_en': 'English',
'settings.language_name_zh': 'Chinese',
'settings.safety': 'Safety',
'settings.javascript_safety': 'Default JavaScript safety checks',
'settings.javascript_safety_hint': 'Default for execute_javascript calls when safety_checks is omitted. Explicit safety_checks=false can still bypass this for trusted local calls.',
'settings.transport': 'Transport',
'settings.sessions': 'MCP Sessions',
'settings.sessions_hint': 'Direct HTTP is the default. Sessions add MCP-Session-Id handling for clients that require session-aware Streamable HTTP.',
'settings.diagnostics': 'Diagnostics',
'community.title': 'Contact & Feedback',
'community.hint': 'Questions, ideas, or feedback? Get in touch with the author or join the community.',
'community.author_email': 'Author Email',
'community.copy_email': 'Copy Email',
'community.email_copied': 'Copied author email.',
'community.qq_group': 'QQ Group',
'community.copy_group': 'Copy Group Number',
'community.group_copied': 'Copied QQ group number: 1108522331.',
'community.feedback_hint': 'For problem reports, include your Cocos Creator version, plugin version, and steps to reproduce.',
'installation.title': 'All Projects',
'installation.hint': 'Install one checksum-verified release for this Cocos Creator version. Projects opened with this version can then load it automatically.',
'installation.install_all': 'Install for All Projects',
'installation.update_global': 'Update Global Install',
'installation.installed_all': 'Available to All Projects',
'installation.copy_path': 'Copy Global Path',
'installation.path_copied': 'Copied the global extension path.',
'installation.path': 'Global path: {path}',
'installation.scope_global': 'global',
'installation.scope_project': 'project',
'installation.scope_external': 'development/external',
'installation.current_scope': 'Current install: {scope}.',
'installation.global_missing': 'No global install was found.',
'installation.global_ready': 'Global version {version} is available to projects opened with Cocos Creator {editorVersion}.',
'installation.global_invalid': 'The global path is occupied by an invalid package: {error}',
'installation.duplicate': 'A project copy also exists at {path} and may have priority while this project is open. Remove or disable it after verifying the global copy in a clean project.',
'installation.restart_required': 'Reopen this project or restart Cocos Creator to activate the global copy.',
'installation.already_available': 'The extension is already available to projects opened with this Creator version.',
'installation.confirm_title': 'Install Funplay Cocos MCP for all projects using this Creator version?',
'installation.confirm_body': 'The latest release will be downloaded, verified with SHA256SUMS.txt, and installed at {path}. Cocos Creator will scan and register it. The current project copy will stay active; reopen the project to switch to the global copy.',
'client.no_targets': 'No client targets available.',
'client.configured': 'Configured',
'client.not_configured': 'Not configured',
'client.select_first': 'Select a client target first.',
'client.url_copied': 'Copied URL to clipboard.',
'client.health_copied': 'Copied health curl command.',
'client.tools_copied': 'Copied tools curl command.',
'skills_manager.title': 'Project Skills',
'skills_manager.hint': 'Manage project Skills for the selected client without silently replacing local changes.',
'skills_manager.unsupported': 'Automatic Skills installation is not supported for this client yet. Choose a supported client above.',
'skills_manager.read_error': 'Unable to read this client’s Skills: {error}',
'skills_manager.legacy_path': 'Legacy location: {path}. Updating backs it up and installs to the new location; the original file is retained.',
'skills_manager.recommended': 'Built-in Funplay Skills',
'skills_manager.installed': 'Installed Project Skills',
'skills_manager.install': 'Install Skill',
'skills_manager.update': 'Back Up & Update',
'skills_manager.current_action': 'Up to Date',
'skills_manager.view_changes': 'View Changes',
'skills_manager.restore_backup': 'Restore Latest Backup',
'skills_manager.reveal': 'Show in Folder',
'skills_manager.diff_preview': 'Diff Preview',
'skills_manager.status_missing': 'Not Installed',
'skills_manager.status_current': 'Up to Date',
'skills_manager.status_update_available': 'Update Available',
'skills_manager.status_modified': 'Locally Modified',
'skills_manager.detail_missing': 'Install built-in template v{latest} to make this guidance available to AI clients.',
'skills_manager.detail_current': 'Built-in template v{latest} is installed and has no local changes.',
'skills_manager.detail_update_available': 'Template v{installed} can be updated to v{latest}. The installed file will be backed up first.',
'skills_manager.detail_modified': 'Local changes were detected. Review the diff before replacing this file with template v{latest}.',
'skills_manager.path': 'Skill path: {path}',
'skills_manager.latest_backup': '{count} backup(s). Latest: {path}',
'skills_manager.no_backup': 'No backups yet.',
'skills_manager.no_built_in_skills': 'No built-in project skills are available.',
'skills_manager.no_skills': 'No project skills are installed.',
'skills_manager.official_badge': 'Built-in',
'skills_manager.invalid_format': 'Legacy or invalid SKILL.md frontmatter',
'skills_manager.notice_missing': 'The recommended project Skill is not installed. Open Project Skills to install it.',
'skills_manager.notice_update': 'A project Skill update is available (v{installed} -> v{latest}). Open Project Skills to review it.',
'skills_manager.notice_modified': 'The recommended project Skill has local changes. Open Project Skills to compare or back it up before updating.',
'skills_manager.notice_summary': '{count} of {total} built-in project Skill(s) need installation, review, or an update. Open Project Skills to manage them.',
'skills_manager.notice_missing_list': 'Not installed ({count}): {names}',
'skills_manager.notice_update_list': 'Updates available ({count}): {names}',
'skills_manager.notice_modified_list': 'Locally modified ({count}): {names}',
'skills_manager.manage': 'Manage Skills',
'skills_manager.diff_summary': 'Diff ready: {added} added line(s), {removed} removed line(s).',
'skills_manager.already_current': 'This built-in project Skill is already up to date.',
'skills_manager.confirm_update_title': 'Update this built-in project Skill?',
'skills_manager.confirm_update_body': 'The current file at {path} will be backed up before the latest template replaces it.',
'skills_manager.confirm_modified_title': 'Replace this locally modified project Skill?',
'skills_manager.confirm_modified_body': 'Local changes at {path} will be backed up, then the latest official template will replace the file. Review the diff first if needed.',
'skills_manager.confirm_restore_title': 'Restore the latest project Skill backup?',
'skills_manager.confirm_restore_body': 'Restore {path}. The current Skill will also be backed up first.',
'skills_manager.create_custom': 'Create Custom Skill',
'skills_manager.skill_name': 'Skill name',
'skills_manager.skill_name_placeholder': 'scene-qa',
'skills_manager.skill_title': 'Title',
'skills_manager.skill_title_placeholder': 'Scene QA',
'skills_manager.skill_description': 'Trigger description',
'skills_manager.skill_instructions': 'Instructions',
'skills_manager.create': 'Create Skill',
'skills_manager.skill_name_required': 'Skill name is required.',
'errors.refresh_failed': 'Refresh failed: {error}',
};
+295
View File
@@ -0,0 +1,295 @@
'use strict';
module.exports = {
language_code: 'zh',
title: 'Funplay Cocos MCP',
panel_server: 'MCP 服务',
panel_tool_exposure: '工具开放范围',
panel_settings: 'MCP 设置',
panel_project_skills: '项目 Skills',
panel_contact: '联系反馈',
menu_server: 'MCP 服务',
menu_tool_exposure: '工具开放范围',
menu_settings: 'MCP 设置',
menu_project_skills: '项目 Skills',
menu_contact: '联系反馈',
'common.dismiss': '关闭',
'common.action_completed': '操作已完成。',
'common.action_failed': '操作未完成。',
'common.copy_failed': '复制失败,请检查剪贴板权限后重试。',
'skills_manager.file_details': '位置与备份',
'common.unknown': '未知',
'common.clear': '清除',
'common.yes': '是',
'common.no': '否',
'common.enable': '启用',
'common.disable': '禁用',
'common.select': '选择',
'common.save': '保存',
'common.apply': '应用',
'common.delete': '删除',
'common.export': '导出',
'common.import': '导入',
'common.refresh': '刷新',
'common.copy_url': '复制地址',
'common.copy_health_curl': '复制健康检查命令',
'common.copy_tools_curl': '复制工具列表命令',
'common.configuration_saved': '配置已保存。',
'common.save_failed': '保存配置失败:{error}',
'common.error': '错误:{error}',
'common.nothing_to_copy': '没有可复制的内容。',
'dashboard.version': '版本 {version}',
'dashboard.running': '运行中',
'dashboard.stopped': '已停止',
'dashboard.project': '项目',
'dashboard.port_fallback': '端口回退:{requested} -> {actual}',
'dashboard.attached_listener': '已连接现有监听服务',
'dashboard.service': '服务',
'dashboard.server_port': '服务端口',
'dashboard.server_host': '监听地址',
'dashboard.apply_host': '应用地址',
'dashboard.host_hint': '填写本机拥有的地址;127.0.0.1 仅供本机使用。启用服务时,“应用地址”会重试启动。网络/通配地址可能开放未认证的编辑器访问,仅在可信网络使用。修改后请重新配置客户端。',
'dashboard.host_env_hint': 'COCOS_MCP_HOST 环境变量覆盖了项目监听地址。请修改该环境变量并重启 Cocos Creator;修改 JSON 文件无法覆盖它。',
'dashboard.start_error': 'MCP 无法监听 {host}:{port}:{error}。插件仍可使用。请检查监听地址(本机访问可用 127.0.0.1),再“应用地址”或“重启”。未自动回退到其他监听地址。',
'dashboard.derived_port_hint': '由当前项目路径生成稳定端口({port})。',
'dashboard.fixed_port_hint': '当前使用固定端口,可切换为项目独立端口。',
'dashboard.client_setup': '一键配置 MCP',
'dashboard.configure_short': '配置',
'dashboard.configure_skills': '配置 + Skills',
'client.status': '状态',
'client.needs_reconfigure': '需要改用项目专属地址',
'client.legacy_endpoint': '此客户端仍使用未绑定项目的旧地址。请重新配置 MCP,再重连或重启客户端;旧地址允许读取,写入需核对过的项目/编辑器标识。已有 Skills 和本地修改会保留。',
'client.legacy_unverified': '旧地址缺少可核实的归属记录。请先启动当前项目的 MCP 服务,或手动检查条目;不会覆盖未经核实的地址。',
'client.config_read_error': '客户端配置需要检查:{error}',
'client.reconfigure': '重新配置 MCP',
'client.reconfigure_skills': '重新配置 MCP + Skills',
'client.skills_setup_hint': '“配置 + Skills”会安装缺失的内置 Skill,已有内容保留。',
'client.trae_project_hint': '在 Trae 中打开此 Cocos 项目目录,并在“设置 > MCP”启用“项目级 MCP”以加载 .trae/mcp.json。项目 Skills 安装至 .trae/skills。',
'client.antigravity_project_hint': '在 Antigravity 中打开此 Cocos 项目目录,并重新加载 MCP 配置。项目配置位于 .agents/mcp_config.json,项目 Skills 安装至 .agents/skills。',
'client.pi_project_hint': '请在此 Cocos 项目目录启动 Pi 1.0 或更高版本,并按提示信任项目。Pi 会读取 .pi/mcp.json 和 .agents/skills。已信任的会话可执行 /reload,再用 /mcp 查看连接。',
'client.configuring': '正在配置…',
'client.configure_complete': '客户端配置已保存,重新连接客户端即可使用。',
'client.patch_generated': '配置文件已生成(需 --patch 加载)',
'client.patch_configure_complete': 'DSH 配置文件已保存,不会自动加载。',
'client.patch_setup_complete': 'DSH 配置文件已保存,安装了 {count} 个 Skill;配置需手动加载。',
'client.patch_launch_hint': '请在此 Cocos 项目目录启动 DSH(或给现有启动命令追加相同的 --patch 参数):\n{command}',
'client.setup_complete': '配置已保存,安装了 {count} 个 Skill。请重新连接客户端以加载变更。',
'client.setup_review': '配置已保存,安装了 {count} 个 Skill。需要检查的已有 Skill 保持不变,可到“项目 Skills”更新。',
'client.configure_failed': '配置失败:{error}',
'client.setup_partial': '客户端配置已保存,但 Skills 安装未完成:{error}',
'settings.updates': '扩展更新',
'settings.console_logs': '控制台日志',
'settings.print_mcp_logs': '打印 MCP 日志',
'settings.print_mcp_logs_hint': '立即控制 MCP 向 Cocos 控制台打印的信息、警告和错误;不影响最近活动、内部诊断记录或项目脚本日志。',
'installation.short_duplicate': '检测到项目与全局副本,详情见设置。',
'installation.short_error': '全局安装需要检查,详情见设置。',
'dashboard.use_project_port': '使用项目独立端口',
'dashboard.pin_current_port': '固定当前端口',
'client.fallback_blocked': '当前使用临时回退端口。请先“固定当前端口”或“使用项目独立端口”,再配置客户端。',
'dashboard.tool_exposure': '工具开放范围',
'dashboard.enable_server': '启用 MCP 服务',
'dashboard.restart': '重启',
'dashboard.check_updates': '检查更新',
'dashboard.open_release': '打开发布页',
'dashboard.install_update': '安装更新',
'dashboard.edit_tools': '编辑工具',
'dashboard.settings': '设置',
'dashboard.recent_activity': '最近活动',
'activity.tool_fallback': '工具',
'activity.no_calls': '暂无 MCP 调用。',
'activity.log_badge': '记录',
'activity.result_preview': '查看结果 JSON · 已限量并脱敏',
'activity.call_completed': '调用完成。',
'activity.execution_completed': '脚本执行完成。',
'activity.execution_failed': '脚本执行失败。',
'activity.execution_logs': '执行日志',
'activity.no_execution_logs': '本次调用没有 console 输出。',
'activity.return_value': '返回值',
'activity.result': '结果',
'activity.context_editor': '编辑器',
'activity.context_scene': '场景',
'activity.items_omitted': '另有 {count} 项未展示(预览上限)。',
'activity.logs_omitted': '另有 {count} 条日志未展示(采集上限)。',
'activity.field_message': '消息',
'activity.field_summary': '摘要',
'activity.field_sceneName': '场景',
'activity.field_projectName': '项目',
'activity.field_cocosVersion': 'Cocos 版本',
'activity.field_running': '运行中',
'activity.field_childCount': '子节点数',
'activity.field_nodeCount': '节点数',
'activity.field_count': '数量',
'activity.field_name': '名称',
'activity.field_toolProfile': '工具范围',
'activity.field_port': '端口',
'activity.field_path': '路径',
'activity.field_url': '地址',
'dashboard.project_skills': '项目 Skills',
'dashboard.mcp_client': 'MCP 客户端',
'dashboard.configure_client': '一键配置',
'dashboard.preview_config': '预览所选配置',
'updates.reload_scheduled': '将在 {delay} 毫秒后重新加载',
'updates.reload_not_scheduled': '未安排重新加载:{reason}',
'updates.installed': '已安装 {version}。{reload}。备份:{backup}',
'updates.check_failed': '检查更新失败:{error}',
'updates.published': ',发布于 {date}',
'updates.available': '发现新版本:{version}{published}。{status}',
'updates.ready': '可以安装。',
'updates.incomplete': '发布资源不完整,请手动安装。',
'updates.auto_check_failed': '自动检查更新失败:{error}',
'updates.none_installable': '当前没有可安装的更新。',
'updates.confirm_title': '现在安装 Funplay Cocos MCP {version} 吗?',
'updates.confirm_body': '更新程序将校验 SHA256SUMS.txt、备份当前扩展、替换插件文件,并在 Cocos 支持时重新加载扩展。',
'tools.title': '工具开放范围',
'tools.hint': '精确控制 MCP 客户端可以看到哪些工具。保存后会自动重启正在运行的服务。',
'tools.edit_list': '编辑工具列表',
'tools.profile_core': '核心',
'tools.profile_full': '全部',
'tools.profile_custom': '自定义',
'tools.tools': '工具',
'tools.select_all': '全部选择',
'tools.use_default': '使用默认值',
'tools.named_profiles': '命名配置',
'tools.profile_name': '配置名称',
'tools.raw_lists': '原始包含 / 排除列表',
'tools.enabled_categories': '启用的分类',
'tools.disabled_categories': '禁用的分类',
'tools.enabled_tools': '启用的工具',
'tools.disabled_tools': '禁用的工具',
'tools.saved_profile': '配置:{name}',
'tools.full_hint': 'full 会开放全部已注册工具。',
'tools.custom_hint': 'custom 使用自定义包含和排除规则。',
'tools.core_hint': 'core 让客户端工具列表保持精简。',
'tools.dashboard_summary': '当前:{profile}{saved} | {enabled}/{total} 个工具。{hint}',
'tools.exposure_summary': '当前:{profile}{saved} | {enabled}/{total} 个工具({source})',
'tools.with_overrides': '包含自定义规则',
'tools.default_list': '默认列表',
'tools.profile_name_required': '必须填写配置名称。',
'tools.no_saved_profiles': '没有已保存的配置',
'tools.no_profile_selected': '请先选择一个已保存的配置。',
'tools.profiles_copied': '工具配置已复制到剪贴板。',
'tools.no_profiles_found': '没有找到可导入的配置。',
'tools.import_failed': '导入配置失败:{error}',
'tools.exposure_saved': '工具开放范围已保存:{name} 已{state}。',
'tools.enabled': '启用',
'tools.disabled': '禁用',
'settings.title': 'MCP 设置',
'settings.hint': '管理当前项目的界面、传输、JavaScript 安全和本地诊断默认值。',
'settings.interface': '界面',
'settings.language': '语言',
'settings.language_auto': '跟随 Cocos Creator',
'settings.language_zh': '中文',
'settings.language_en': 'English',
'settings.language_auto_hint': '面板正在跟随 Cocos Creator 当前语言({language})。',
'settings.language_override_hint': '当前项目的面板语言已固定为{language}。',
'settings.language_name_en': '英文',
'settings.language_name_zh': '中文',
'settings.safety': '安全',
'settings.javascript_safety': '默认启用 JavaScript 安全检查',
'settings.javascript_safety_hint': 'execute_javascript 未传 safety_checks 时使用此默认值。可信本地调用仍可显式传 safety_checks=false 跳过检查。',
'settings.transport': '传输',
'settings.sessions': 'MCP 会话',
'settings.sessions_hint': '默认使用直接 HTTP。需要会话感知 Streamable HTTP 的客户端可启用 MCP-Session-Id 处理。',
'settings.diagnostics': '诊断',
'community.title': '联系反馈',
'community.hint': '欢迎交流使用经验、分享建议,或联系作者反馈问题。',
'community.author_email': '作者邮箱',
'community.copy_email': '复制邮箱',
'community.email_copied': '已复制作者邮箱。',
'community.qq_group': 'QQ 群',
'community.copy_group': '复制群号',
'community.group_copied': '已复制 QQ 群号:1108522331。',
'community.feedback_hint': '反馈问题时,请附上 Cocos Creator 版本、插件版本及复现步骤,方便排查。',
'installation.title': '所有项目',
'installation.hint': '为当前 Cocos Creator 版本安装一份经过校验的 Release,之后由该版本打开的项目都可以自动加载。',
'installation.install_all': '为所有项目安装',
'installation.update_global': '更新全局安装',
'installation.installed_all': '已对所有项目可用',
'installation.copy_path': '复制全局路径',
'installation.path_copied': '全局扩展路径已复制。',
'installation.path': '全局路径:{path}',
'installation.scope_global': '全局',
'installation.scope_project': '当前项目',
'installation.scope_external': '开发或外部目录',
'installation.current_scope': '当前安装范围:{scope}。',
'installation.global_missing': '尚未发现全局安装。',
'installation.global_ready': '全局版本 {version} 已对使用 Cocos Creator {editorVersion} 打开的项目可用。',
'installation.global_invalid': '全局路径被无效包占用:{error}',
'installation.duplicate': '当前项目仍有一份扩展:{path},在本项目保持打开时它可能优先。请先在干净项目中确认全局副本,再移除或禁用项目副本。',
'installation.restart_required': '请重新打开当前项目或重启 Cocos Creator,以启用全局副本。',
'installation.already_available': '扩展已经对使用当前 Creator 版本打开的项目可用。',
'installation.confirm_title': '为使用当前 Creator 版本的所有项目安装 Funplay Cocos MCP 吗?',
'installation.confirm_body': '将下载最新 Release,使用 SHA256SUMS.txt 校验后安装到 {path},并让 Cocos Creator 扫描和注册它。当前项目副本会继续运行;重新打开项目后切换到全局副本。',
'client.no_targets': '没有可用的客户端目标。',
'client.configured': '已配置',
'client.not_configured': '未配置',
'client.select_first': '请先选择一个客户端目标。',
'client.url_copied': '服务地址已复制到剪贴板。',
'client.health_copied': '健康检查 curl 命令已复制。',
'client.tools_copied': '工具列表 curl 命令已复制。',
'skills_manager.title': '项目 Skills',
'skills_manager.hint': '按所选客户端管理项目 Skills,并避免静默覆盖本地修改。',
'skills_manager.unsupported': '暂不支持为此客户端自动安装 Skills,请在上方选择已支持的客户端。',
'skills_manager.read_error': '无法读取此客户端的 Skills:{error}',
'skills_manager.legacy_path': '旧路径:{path}。更新时会备份并安装到新目录,原文件将保留。',
'skills_manager.recommended': 'Funplay 内置 Skills',
'skills_manager.installed': '已安装的项目 Skills',
'skills_manager.install': '安装 Skill',
'skills_manager.update': '备份并更新',
'skills_manager.current_action': '已是最新版',
'skills_manager.view_changes': '查看差异',
'skills_manager.restore_backup': '恢复最新备份',
'skills_manager.reveal': '在文件夹中显示',
'skills_manager.diff_preview': '差异预览',
'skills_manager.status_missing': '未安装',
'skills_manager.status_current': '已是最新版',
'skills_manager.status_update_available': '有可用更新',
'skills_manager.status_modified': '存在本地修改',
'skills_manager.detail_missing': '安装内置模板 v{latest},让 AI 客户端可以使用这套项目指引。',
'skills_manager.detail_current': '内置模板 v{latest} 已安装,且没有检测到本地修改。',
'skills_manager.detail_update_available': '模板可从 v{installed} 更新到 v{latest},更新前会先备份现有文件。',
'skills_manager.detail_modified': '检测到本地修改。用模板 v{latest} 替换前请先查看差异。',
'skills_manager.path': 'Skill 路径:{path}',
'skills_manager.latest_backup': '共 {count} 个备份,最新:{path}',
'skills_manager.no_backup': '暂无备份。',
'skills_manager.no_built_in_skills': '当前没有可用的内置项目 Skill。',
'skills_manager.no_skills': '当前项目尚未安装 Skill。',
'skills_manager.official_badge': '内置',
'skills_manager.invalid_format': '旧格式或 SKILL.md frontmatter 无效',
'skills_manager.notice_missing': '尚未安装推荐的项目 Skill,请打开“项目 Skills”进行安装。',
'skills_manager.notice_update': '项目 Skill 有可用更新(v{installed} -> v{latest}),请打开“项目 Skills”查看。',
'skills_manager.notice_modified': '推荐项目 Skill 存在本地修改,请打开“项目 Skills”比较差异或备份后更新。',
'skills_manager.notice_summary': '{total} 个内置项目 Skill 中有 {count} 个需要安装、检查或更新,请打开“项目 Skills”进行管理。',
'skills_manager.notice_missing_list': '未安装({count}):{names}',
'skills_manager.notice_update_list': '有可用更新({count}):{names}',
'skills_manager.notice_modified_list': '存在本地修改({count}):{names}',
'skills_manager.manage': '管理 Skills',
'skills_manager.diff_summary': '差异已生成:新增 {added} 行,删除 {removed} 行。',
'skills_manager.already_current': '这个内置项目 Skill 已是最新版。',
'skills_manager.confirm_update_title': '更新这个内置项目 Skill?',
'skills_manager.confirm_update_body': '更新前会备份 {path},然后用最新版模板替换。',
'skills_manager.confirm_modified_title': '替换这个存在本地修改的项目 Skill?',
'skills_manager.confirm_modified_body': '将先备份 {path} 的本地修改,再用最新版官方模板替换。如有需要,请先查看差异。',
'skills_manager.confirm_restore_title': '恢复最新的项目 Skill 备份?',
'skills_manager.confirm_restore_body': '将恢复 {path},当前 Skill 也会先备份。',
'skills_manager.create_custom': '创建自定义 Skill',
'skills_manager.skill_name': 'Skill 名称',
'skills_manager.skill_name_placeholder': 'scene-qa',
'skills_manager.skill_title': '标题',
'skills_manager.skill_title_placeholder': '场景质量检查',
'skills_manager.skill_description': '触发说明',
'skills_manager.skill_instructions': '操作指令',
'skills_manager.create': '创建 Skill',
'skills_manager.skill_name_required': '必须填写 Skill 名称。',
'errors.refresh_failed': '刷新失败:{error}',
};
@@ -0,0 +1,67 @@
'use strict';
const PRIVATE_FIELD = /password|passwd|secret|token|authorization|credential|cookie|apikey/i;
const BODY_FIELDS = new Set(['content', 'contents', 'text', 'code', 'script', 'source', 'stdout', 'stderr', 'html', 'raw', 'diff', 'datauri', 'imagedata', 'base64', 'buffer']);
const PREVIEW_LIMITS = { nodes: 200, depth: 6, keys: 24, items: 12, string: 800, characters: 16000 };
function sanitizeActivityText(value, limit = PREVIEW_LIMITS.string) {
const text = String(value)
.replace(/data:[^\s"']+/gi, '[omitted]')
.replace(/\bBearer\s+[^\s"',;]+/gi, 'Bearer [redacted]')
.replace(/(["']?(?:password|passwd|secret|access[_-]?token|api[_-]?key|token|credential|cookie|authorization)["']?\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^,\s;}]+)/gi, '$1[redacted]');
return text.length > limit ? text.slice(0, limit) + '…' : text;
}
// Snapshot the actual result in its original order and shape. Bound retained data,
// not a hand-picked set of fields, and never execute getters for the dashboard.
function createActivityPreview(value) {
const seen = new WeakSet();
let remaining = PREVIEW_LIMITS.nodes;
let characters = PREVIEW_LIMITS.characters;
function visit(input, depth) {
if (remaining-- <= 0 || characters <= 0) return '[truncated]';
if (typeof input === 'string') {
const text = sanitizeActivityText(input, Math.min(PREVIEW_LIMITS.string, characters));
characters -= text.length;
return text;
}
if (input === null || typeof input === 'boolean' || typeof input === 'number') return input;
if (typeof input === 'bigint') return String(input);
if (!input || typeof input !== 'object') return undefined;
if (seen.has(input)) return '[circular]';
if (depth > PREVIEW_LIMITS.depth) return '[truncated]';
seen.add(input);
try {
if (Array.isArray(input)) {
const preview = [];
let i = 0;
for (; i < Math.min(PREVIEW_LIMITS.items, input.length) && remaining > 0 && characters > 0; i++) {
const property = Object.getOwnPropertyDescriptor(input, String(i));
preview.push(property && 'value' in property ? visit(property.value, depth + 1) ?? null : null);
}
if (i < input.length) preview.push({ $remaining: input.length - i });
return preview;
}
const preview = Object.create(null);
const keys = Object.keys(input);
let i = 0;
for (; i < Math.min(PREVIEW_LIMITS.keys, keys.length) && remaining > 0 && characters > 0; i++) {
const key = keys[i];
const label = sanitizeActivityText(key, 160);
characters -= label.length;
const normalized = key.replace(/[^a-z0-9]/gi, '');
if (PRIVATE_FIELD.test(normalized)) { preview[label] = '[redacted]'; remaining--; continue; }
if (BODY_FIELDS.has(normalized.toLowerCase())) { preview[label] = '[omitted]'; remaining--; continue; }
const property = Object.getOwnPropertyDescriptor(input, key);
if (!property || !('value' in property)) continue;
const result = visit(property.value, depth + 1);
if (result !== undefined) preview[label] = result;
}
if (i < keys.length) preview.$remaining = keys.length - i;
return preview;
} finally { seen.delete(input); }
}
try { return visit(value, 0); } catch (error) { return undefined; }
}
module.exports = { createActivityPreview, sanitizeActivityText, PREVIEW_LIMITS };
+160
View File
@@ -0,0 +1,160 @@
'use strict';
// Readiness is deliberately narrower than importer/compilation/runtime completion.
// Only exact AssetDB identities are queried; this module never refreshes or retries writes.
function normalizeAssetTarget(value) {
if (value === undefined) return null;
if (typeof value !== 'string') throw new Error('target must be an asset UUID or exact db:// URL.');
const target = value.trim().replace(/\\/g, '/');
if (!target || target.length > 512 || /[\0*?#]/.test(target)) {
throw new Error('target must be an asset UUID or exact db:// URL.');
}
const url = target.startsWith('assets/') || target.startsWith('internal/') ? `db://${target}` : target;
if (url.startsWith('db://')) {
const segments = url.slice(5).split('/');
if (!['assets', 'internal'].includes(segments[0]) || segments.length < 2 ||
segments.some((segment) => !segment || segment === '.' || segment === '..')) {
throw new Error('target must be an exact db://assets/ or db://internal/ asset URL.');
}
return url;
}
// Compressed Cocos UUIDs may contain + or /; ordinary filesystem paths are not accepted.
if (!/^[A-Za-z0-9_-]+(?:@[A-Za-z0-9_-]+)?$/.test(target) &&
!/^[A-Za-z0-9+/]{22}(?:@[A-Za-z0-9_-]+)?$/.test(target)) {
throw new Error('target must be an asset UUID, not a filesystem path.');
}
return target;
}
function integerOption(value, fallback, name, minimum, maximum) {
const number = value === undefined ? fallback : value;
if (!Number.isInteger(number) || number < minimum || number > maximum) {
throw new Error(`${name} must be an integer between ${minimum} and ${maximum}.`);
}
return number;
}
function importedIdentity(info) {
if (!info || typeof info !== 'object' || typeof info.uuid !== 'string' || !info.uuid ||
typeof info.url !== 'string' || !info.url || typeof info.type !== 'string' || !info.type ||
info.imported !== true || info.invalid === true) return null;
return { uuid: info.uuid, url: info.url, type: info.type, importer: info.importer || null };
}
function editorRequest(method, ...args) {
if (!global.Editor || !Editor.Message || typeof Editor.Message.request !== 'function') {
throw new Error('AssetDB queries require the Cocos Creator extension host.');
}
return Editor.Message.request('asset-db', method, ...args);
}
async function observeAsset(request, target) {
const databaseState = await request('query-ready');
if (databaseState !== true) {
return { status: databaseState === false ? 'database_busy' : 'unknown', databaseReady: databaseState === false ? false : null, asset: null };
}
if (!target) return { status: 'observed', databaseReady: true, asset: null };
const info = await request('query-asset-info', target);
if (!info) return { status: 'missing', databaseReady: true, asset: null };
const asset = importedIdentity(info);
if (!asset) {
return { status: info.invalid === true ? 'invalid_asset' : 'importing', databaseReady: true, asset: {
uuid: info.uuid || null, url: info.url || null, imported: info.imported === true,
} };
}
if ((target.startsWith('db://') ? asset.url : asset.uuid) !== target) {
return { status: 'identity_mismatch', databaseReady: true, asset };
}
const uuid = await request('query-uuid', asset.url);
const url = await request('query-url', asset.uuid);
const readback = importedIdentity(await request('query-asset-info', asset.uuid));
if (uuid !== asset.uuid || url !== asset.url || JSON.stringify(readback) !== JSON.stringify(asset)) {
return { status: 'identity_mismatch', databaseReady: true, asset };
}
const readyAfterRead = await request('query-ready');
if (readyAfterRead !== true) {
return { status: readyAfterRead === false ? 'database_busy' : 'unknown', databaseReady: readyAfterRead === false ? false : null, asset };
}
return { status: 'observed', databaseReady: true, asset };
}
async function checkAssetReady(options = {}, dependencies = {}) {
const target = normalizeAssetTarget(options.target);
const waitMs = integerOption(options.waitMs, 1500, 'waitMs', 0, 10000);
const pollIntervalMs = integerOption(options.pollIntervalMs, 100, 'pollIntervalMs', 20, 2000);
const now = dependencies.now || Date.now;
const sleep = dependencies.sleep || ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
const nativeRequest = dependencies.request || editorRequest;
const started = now();
// A zero-wait request still bounds its single IPC observation, but cannot establish stability.
const deadline = started + (waitMs || 1000);
const request = (method, ...args) => new Promise((resolve, reject) => {
const budget = Math.min(1000, deadline - now());
if (budget <= 0) {
const error = new Error('AssetDB readiness deadline reached.');
error.code = 'READINESS_QUERY_TIMEOUT';
reject(error);
return;
}
const timer = setTimeout(() => {
const error = new Error(`AssetDB ${method} did not respond within the readiness deadline.`);
error.code = 'READINESS_QUERY_TIMEOUT';
reject(error);
}, budget);
Promise.resolve().then(() => nativeRequest(method, ...args)).then(
(value) => { clearTimeout(timer); resolve(value); },
(error) => { clearTimeout(timer); reject(error); }
);
});
let attempts = 0;
let stableObservations = 0;
let previous = null;
let sample = { status: 'unknown', databaseReady: null, asset: null };
let queryError = '';
while (attempts < 102) {
attempts += 1;
try {
sample = await observeAsset(request, target);
} catch (error) {
sample = { status: error.code === 'READINESS_QUERY_TIMEOUT' ? 'query_timeout' : 'unavailable', databaseReady: null, asset: null };
queryError = String(error.message || error).slice(0, 500);
stableObservations = 0;
break;
}
const identity = sample.status === 'observed' ? JSON.stringify(sample.asset || { databaseReady: true }) : null;
stableObservations = identity ? (identity === previous ? stableObservations + 1 : 1) : 0;
previous = identity;
if (stableObservations >= 2 || waitMs === 0 || now() >= deadline) break;
await sleep(Math.min(pollIntervalMs, deadline - now()));
if (now() >= deadline) break;
}
const ready = stableObservations >= 2;
return {
ready,
status: ready ? 'ready' : sample.status === 'observed' ? 'unconfirmed' : sample.status,
scope: target ? 'asset_db_record' : 'asset_db_query',
target,
databaseReady: sample.databaseReady,
asset: sample.asset,
stableObservations,
attempts,
elapsedMs: Math.max(0, now() - started),
timedOut: !ready && (sample.status === 'query_timeout' || waitMs > 0 && now() >= deadline),
error: queryError,
boundaries: {
importQueueVerified: false,
sourceBytesVerified: false,
scriptCompilationVerified: false,
runtimeLoadedVerified: false,
},
summary: ready
? target ? 'Stable imported AssetDB identity verified; compilation and runtime loading are not verified.'
: 'Stable AssetDB query readiness verified; individual assets and the importer queue are not verified.'
: `AssetDB readiness was not established (${sample.status === 'observed' ? 'unconfirmed' : sample.status}).`,
};
}
module.exports = { checkAssetReady, normalizeAssetTarget };
+210
View File
@@ -0,0 +1,210 @@
'use strict';
async function safeRequest(channel, method, ...args) {
if (!global.Editor || !Editor.Message || typeof Editor.Message.request !== 'function') {
throw new Error('Editor.Message.request is unavailable in the Cocos extension host.');
}
return await Editor.Message.request(channel, method, ...args);
}
function buildAssetTargetCandidates(uuidOrPath) {
const raw = String(uuidOrPath || '').trim().replace(/\\/g, '/');
const candidates = [];
const add = (value) => {
if (value && !candidates.includes(value)) {
candidates.push(value);
}
};
add(raw);
if (raw.startsWith('assets/')) {
add(`db://${raw}`);
} else if (raw.startsWith('/assets/')) {
add(`db://${raw.slice(1)}`);
}
if (raw.includes('/assets/')) {
add(`db://assets/${raw.split('/assets/').pop()}`);
}
if (raw.startsWith('db://assets/') && !raw.match(/\.[a-z0-9]+$/i)) {
add(`${raw}.scene`);
add(`${raw}.prefab`);
add(`${raw}.ts`);
}
return candidates;
}
async function requestFirst(method, uuidOrPath) {
const candidates = buildAssetTargetCandidates(uuidOrPath);
let lastError = null;
for (const candidate of candidates) {
try {
const result = await safeRequest('asset-db', method, candidate);
if (result != null) {
return result;
}
} catch (error) {
lastError = error;
}
}
if (lastError) {
throw lastError;
}
return null;
}
async function listAssets(options = {}) {
const payload = {};
if (options.pattern) {
payload.pattern = options.pattern;
}
if (options.ccType) {
payload.ccType = options.ccType;
}
const result = await safeRequest('asset-db', 'query-assets', payload);
return Array.isArray(result) ? result : [];
}
async function queryAssetInfo(uuidOrPath) {
if (!uuidOrPath) {
throw new Error('Asset uuid or path is required.');
}
const direct = await requestFirst('query-asset-info', uuidOrPath);
if (direct) {
return direct;
}
const url = await queryAssetUrl(uuidOrPath).catch(() => null);
if (url) {
const fromUrl = await safeRequest('asset-db', 'query-asset-info', url);
if (fromUrl) {
return fromUrl;
}
}
throw new Error(`Asset not found: ${uuidOrPath}`);
}
async function queryAssetMeta(uuidOrPath) {
if (!uuidOrPath) {
throw new Error('Asset uuid or path is required.');
}
const direct = await requestFirst('query-asset-meta', uuidOrPath);
if (direct) {
return direct;
}
const info = await queryAssetInfo(uuidOrPath);
return await safeRequest('asset-db', 'query-asset-meta', info.uuid || info.url || uuidOrPath);
}
async function queryAssetData(uuidOrPath) {
if (!uuidOrPath) {
throw new Error('Asset uuid or path is required.');
}
const direct = await requestFirst('query-asset-data', uuidOrPath);
if (direct) {
return direct;
}
const info = await queryAssetInfo(uuidOrPath);
return await safeRequest('asset-db', 'query-asset-data', info.uuid || info.url || uuidOrPath);
}
async function queryAssetUrl(uuidOrPath) {
if (!uuidOrPath) {
throw new Error('Asset uuid or path is required.');
}
const result = await requestFirst('query-url', uuidOrPath);
if (result) {
return result;
}
throw new Error(`Asset URL not found: ${uuidOrPath}`);
}
async function openAsset(uuidOrPath) {
const info = await queryAssetInfo(uuidOrPath);
await safeRequest('asset-db', 'open-asset', info.uuid || uuidOrPath);
return info;
}
async function deleteAsset(uuidOrPath) {
let url = String(uuidOrPath || '');
if (!url.startsWith('db://')) {
const info = await queryAssetInfo(uuidOrPath);
url = info.url || (await queryAssetUrl(info.uuid || uuidOrPath));
}
await safeRequest('asset-db', 'delete-asset', url);
return { deleted: true, url };
}
function selectAsset(uuid) {
if (!global.Editor || !Editor.Selection || typeof Editor.Selection.select !== 'function') {
throw new Error('Editor.Selection.select is unavailable in this Cocos environment.');
}
Editor.Selection.clear('asset');
Editor.Selection.select('asset', uuid);
return { selected: true, uuid };
}
function selectNode(uuid) {
if (!global.Editor || !Editor.Selection || typeof Editor.Selection.select !== 'function') {
throw new Error('Editor.Selection.select is unavailable in this Cocos environment.');
}
Editor.Selection.clear('node');
Editor.Selection.select('node', uuid);
return { selected: true, uuid };
}
function clearSelection(type) {
if (!global.Editor || !Editor.Selection || typeof Editor.Selection.clear !== 'function') {
throw new Error('Editor.Selection.clear is unavailable in this Cocos environment.');
}
const normalized = String(type || 'all').trim().toLowerCase();
if (normalized === 'asset' || normalized === 'node') {
Editor.Selection.clear(normalized);
return { cleared: true, type: normalized };
}
Editor.Selection.clear('asset');
Editor.Selection.clear('node');
return { cleared: true, type: 'all' };
}
function getCurrentSelection() {
if (!global.Editor || !Editor.Selection || typeof Editor.Selection.getSelected !== 'function') {
throw new Error('Editor.Selection API is unavailable in this Cocos environment.');
}
return {
asset: Editor.Selection.getSelected('asset') || '',
node: Editor.Selection.getSelected('node') || '',
type: typeof Editor.Selection.getLastSelectedType === 'function' ? Editor.Selection.getLastSelectedType() : '',
};
}
module.exports = {
clearSelection,
deleteAsset,
getCurrentSelection,
listAssets,
openAsset,
queryAssetData,
queryAssetInfo,
queryAssetMeta,
queryAssetUrl,
selectAsset,
selectNode,
};
+29
View File
@@ -0,0 +1,29 @@
'use strict';
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
function readOptionalText(filePath) {
try { return fs.readFileSync(filePath, 'utf8'); } catch (error) {
if (error.code === 'ENOENT') return null;
throw error;
}
}
function writeTextIfUnchanged(filePath, content, original) {
// Preserve symlinked config locations while replacing the real file atomically.
const destination = fs.existsSync(filePath) ? fs.realpathSync(filePath) : filePath;
fs.mkdirSync(path.dirname(destination), { recursive: true });
const temporary = `${destination}.funplay-${crypto.randomBytes(8).toString('hex')}.tmp`;
try {
const mode = fs.existsSync(destination) ? fs.statSync(destination).mode & 0o777 : 0o600;
fs.writeFileSync(temporary, content, { encoding: 'utf8', flag: 'wx', mode });
if (readOptionalText(filePath) !== original) throw new Error(`Configuration changed while editing: ${filePath}. Retry after reviewing it.`);
fs.renameSync(temporary, destination);
} finally {
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
}
}
module.exports = { readOptionalText, writeTextIfUnchanged };
+609
View File
@@ -0,0 +1,609 @@
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const { getProjectIdentity } = require('./config');
const { serverUrl } = require('./project-context');
const { readOptionalText, writeTextIfUnchanged } = require('./atomic-file');
const { findGitRootOrSelf } = require('./skill-platforms');
const { parseJsonc, updateJsonc } = require('./jsonc');
const { resolveProjectFilePath } = require('./path-safety');
const SERVER_NAME = 'funplay_cocos';
function getServerName(config) {
if (!config.projectPath) return SERVER_NAME; // Compatibility for callers without project context.
const identity = getProjectIdentity(config.projectPath);
const slug = path.basename(config.projectPath).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '').slice(0, 12).replace(/-$/, '') || 'project';
return `cocos-${slug}-${identity.slice(0, 6)}`;
}
function getPreviousEntry(config, targetId) {
const record = config.clientConfigEntries && config.clientConfigEntries[targetId];
// A copied project config is not proof of ownership of the source project's client entry.
if (!record || record.projectIdentity !== getProjectIdentity(config.projectPath)) return undefined;
const name = targetId === 'pi' ? String(record.serverName).replace(/_/g, '-') : record.serverName;
return record.serverName === SERVER_NAME || /^cocos-[a-z0-9-]+$/.test(name) ? record : undefined;
}
function isObject(value) { return Boolean(value && typeof value === 'object' && !Array.isArray(value)); }
// Claude Code keys `projects` by a forward-slash path even on Windows, where path.resolve
// yields backslashes. A backslash key is a distinct entry that Claude Code never reads.
function getClaudeScopePath(projectPath, platform = process.platform, resolveGitRoot = findGitRootOrSelf) {
const resolved = resolveGitRoot(projectPath);
return platform === 'win32' ? resolved.replace(/\\/g, '/') : resolved;
}
// Claude Code preserves whatever drive-letter case its cwd had, so the same directory can
// already be keyed as `D:/repo` or `d:/repo`. Reuse that key instead of adding a duplicate.
function resolveProjectKey(projects, scopePath, platform = process.platform) {
if (!isObject(projects) || projects[scopePath] !== undefined || platform !== 'win32') return scopePath;
const lowered = scopePath.toLowerCase();
return Object.keys(projects).find((key) => key.toLowerCase() === lowered) || scopePath;
}
function getServerKeys(root, target) {
if (target.scopePath) return ['projects', resolveProjectKey(root.projects, target.scopePath, target.platform), target.rootKey || 'mcpServers'];
if (target.id === 'opencode' && isObject(root) && isObject(root.mcp)) {
// V2 nests servers and timeouts under mcp; V1 puts server names directly
// under mcp. Keep the existing layout, including a V1 server named "servers".
const legacyEntry = (entry) => isObject(entry) && (typeof entry.type === 'string'
|| typeof entry.url === 'string' || Array.isArray(entry.command) || typeof entry.enabled === 'boolean');
const nested = (root.mcp.servers !== undefined && !legacyEntry(root.mcp.servers))
|| (root.mcp.timeout !== undefined && !legacyEntry(root.mcp.timeout));
if (nested) {
if (root.mcp.servers !== undefined && (!isObject(root.mcp.servers) || legacyEntry(root.mcp.servers))) {
throw new Error('OpenCode mcp.servers must be a server map; the file was left unchanged.');
}
const name = target.serverName || SERVER_NAME;
if (root.mcp[name] !== undefined) {
if (root.mcp.servers && root.mcp.servers[name] !== undefined) throw new Error('Duplicate OpenCode MCP entry in flat and nested maps; the file was left unchanged.');
return ['mcp']; // An existing flat registration remains authoritative.
}
return ['mcp', 'servers'];
}
}
// Flat OpenCode entries remain schema-supported in V2 and work with V1.
return [target.rootKey || 'mcpServers'];
}
function getServerContainer(root, target, create = false, keys) {
if (!isObject(root)) throw new Error('MCP configuration must be a JSON object.');
keys = keys || getServerKeys(root, target);
let current = root;
for (const key of keys) {
if (current[key] === undefined) {
if (!create) return null;
current[key] = {};
}
if (!isObject(current[key])) throw new Error(`MCP configuration field '${key}' must be an object; the file was left unchanged.`);
current = current[key];
}
return current;
}
function resolveJsonServerName(servers, target) {
const name = target.serverName || SERVER_NAME;
if (target.id !== 'pi' || !servers) return name;
// Pi treats hyphens and underscores as the same character in server namespaces.
const namespace = name.replace(/-/g, '_');
const matches = Object.keys(servers).filter((key) => key.replace(/-/g, '_') === namespace);
if (matches.length > 1) throw new Error(`Multiple Pi MCP entries share the namespace for '${name}'. Resolve the conflict in .pi/mcp.json first.`);
return matches[0] || name;
}
function formatTargetPreview(target) {
let name = target.serverName || SERVER_NAME;
if (target.isToml) return `[mcp_servers.${name}]\nurl = "${target.url}"\n`;
if (target.isDsh) return JSON.stringify(getDshPatch(target), null, 2) + '\n';
const root = {};
let keys = getServerKeys(root, target);
// Match the existing OpenCode layout or Pi server name without exposing unrelated settings.
// A malformed file is reported by inspectTarget and blocks setup.
if (target.id === 'opencode' || target.id === 'pi') {
try {
if (target.projectPath) resolveProjectFilePath(target.projectPath, target.configPath);
const existing = readJson(target.configPath, target.isJsonc);
keys = getServerKeys(existing, target);
name = resolveJsonServerName(getServerContainer(existing, target, false, keys), target);
} catch (error) { /* status reports the read error */ }
}
getServerContainer(root, target, true, keys)[name] = target.entry;
return JSON.stringify(root, null, 2);
}
function getTargetUrl(target) {
return target.url || target.entry[target.urlField || 'url'];
}
function getJsonEntryUrl(entry, urlField) {
return isObject(entry) ? entry[urlField] ?? entry.url : undefined;
}
function isGeneratedEntry(entry, url, urlField) {
return isObject(entry) && entry[urlField] === url && Object.keys(entry).every((key) => (
key === urlField || (key === 'type' && (entry.type === 'http' || entry.type === 'remote'))
));
}
function canReplaceEntry(target, name, url) {
const previous = target.previousEntry;
return url === getTargetUrl(target)
|| Boolean(target.migrateLegacy && name === target.serverName && url === target.legacyUrl)
|| Boolean(previous && previous.serverName === name && previous.url === url && previous.configPath === target.configPath);
}
function getUserHomePath() {
const home = os.homedir();
if (home) {
return home;
}
const homeDrive = process.env.HOMEDRIVE;
const homePath = process.env.HOMEPATH;
if (homeDrive && homePath) {
return `${homeDrive}${homePath}`;
}
return process.env.HOME || '';
}
function getVSCodeConfigPath(homePath, options = {}) {
const platform = options.platform || process.platform;
const env = options.env || process.env;
if (env.VSCODE_PORTABLE) return path.join(env.VSCODE_PORTABLE, 'user-data', 'User', 'mcp.json');
if (env.VSCODE_APPDATA) return path.join(env.VSCODE_APPDATA, 'Code', 'User', 'mcp.json');
switch (platform) {
case 'win32': {
const appData = env.APPDATA || path.join(homePath, 'AppData', 'Roaming');
return path.join(appData, 'Code', 'User', 'mcp.json');
}
case 'darwin':
return path.join(homePath, 'Library', 'Application Support', 'Code', 'User', 'mcp.json');
case 'linux':
return path.join(env.XDG_CONFIG_HOME || path.join(homePath, '.config'), 'Code', 'User', 'mcp.json');
default:
return path.join(homePath, '.vscode', 'mcp.json');
}
}
function getOpenCodeConfigPath(homePath, options = {}) {
const env = options.env || process.env;
const existsSync = options.existsSync || fs.existsSync;
// OpenCode resolves its global config dir cross-platform via xdg-basedir
// (packages/core/src/global.ts): XDG_CONFIG_HOME wins, else ~/.config.
// There is no APPDATA or macOS Application Support branch.
const xdgHome = String(env && env.XDG_CONFIG_HOME || '').trim();
const configDir = xdgHome || path.join(homePath, '.config');
const dir = path.join(configDir, 'opencode');
// globalConfigFile() prefers opencode.jsonc over opencode.json; write
// where the user already keeps the file, else the canonical .json.
const jsonc = path.join(dir, 'opencode.jsonc');
return existsSync(jsonc) ? jsonc : path.join(dir, 'opencode.json');
}
function getConfiguredDirectory(env, key, fallback) {
const configured = String(env && env[key] || '').trim();
return configured || fallback;
}
function ensureParent(filePath) {
const dir = path.dirname(filePath);
if (dir && !fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
}
function readJson(filePath, isJsonc = false) {
if (!fs.existsSync(filePath)) {
return {};
}
const text = fs.readFileSync(filePath, 'utf8');
if (!text) {
return {};
}
return parseConfigJson(text, isJsonc);
}
function parseConfigJson(text, isJsonc) {
if (!text || !text.trim()) return {};
if (!isJsonc) JSON.parse(text.replace(/^\uFEFF/, '')); // Reject comments/trailing commas for strict clients.
return parseJsonc(text); // Reject duplicate keys for both JSON and JSONC.
}
function assertRemoteEntry(entry, urlField) {
if (!isObject(entry)) return;
if (entry.command !== undefined) throw new Error('This MCP entry declares a local command. Review it manually before replacing it with HTTP; the file was left unchanged.');
if (entry.disabled === true || entry.enabled === false) throw new Error('This MCP entry is disabled in the client configuration. Enable it there before configuring; the file was left unchanged.');
if (urlField !== 'url' && entry[urlField] !== undefined && entry.url !== undefined && entry[urlField] !== entry.url) {
throw new Error(`This MCP entry has conflicting ${urlField} and url values. The file was left unchanged.`);
}
}
function matchesJsonTransport(entry, target) {
if (target.entry.type) return entry.type === target.entry.type;
return entry.type === undefined || entry.type === 'http' || (target.id === 'pi' && entry.type === 'streamable-http');
}
function configureJsonTarget(target) {
if (target.projectPath) resolveProjectFilePath(target.projectPath, target.configPath);
const original = readOptionalText(target.configPath);
const root = parseConfigJson(original, target.isJsonc);
const servers = getServerContainer(root, target, true);
const name = resolveJsonServerName(servers, target);
const urlField = target.urlField || 'url';
const existing = servers[name];
if (existing !== undefined && (!isObject(existing) || !canReplaceEntry(target, name, getJsonEntryUrl(existing, urlField)))) {
throw new Error(`MCP entry '${name}' already belongs to another endpoint. Existing configuration was left unchanged.`);
}
assertRemoteEntry(existing, urlField);
const previous = target.previousEntry;
if (previous && previous.configPath === target.configPath && previous.serverName !== name
&& isGeneratedEntry(servers[previous.serverName], previous.url, urlField)) {
delete servers[previous.serverName];
}
if (target.migrateLegacy && urlField === 'url' && target.id !== 'pi') {
if (name !== SERVER_NAME && isGeneratedEntry(servers[SERVER_NAME], target.entry.url, urlField)) delete servers[SERVER_NAME];
if (target.scopePath && isObject(root.mcpServers) && isGeneratedEntry(root.mcpServers[SERVER_NAME], target.entry.url, urlField)) {
delete root.mcpServers[SERVER_NAME];
}
}
servers[name] = { ...(existing || {}), ...target.entry };
if (urlField !== 'url') delete servers[name].url;
// URL-only clients auto-select HTTP. Pi also accepts an explicit HTTP transport.
if (!target.entry.type && (target.id !== 'pi' || !matchesJsonTransport(servers[name], target))) delete servers[name].type;
const content = target.isJsonc ? updateJsonc(original || '', root) : JSON.stringify(root, null, 2) + '\n';
if (content !== original) writeTextIfUnchanged(target.configPath, content, original);
return name;
}
// DSH accepts JSON as YAML for --patch. Keep a dedicated project overlay instead
// of parsing/replacing a user's Cordis YAML (which can contain executable !!js).
function getDshPatch(target, existing = {}) {
return [{ insert: [{
...existing,
id: target.serverName,
name: '@deepseek-ai/dsh-mcp-client',
config: { ...existing.config, ...target.entry },
}] }];
}
function readDshEntry(target, text) {
JSON.parse(text); // Reject JSONC, which is not valid YAML/JSON for DSH.
const patches = parseJsonc(text); // Also reject duplicate/ambiguous JSON keys.
const patch = Array.isArray(patches) && patches.length === 1 && patches[0];
const entry = isObject(patch) && Object.keys(patch).length === 1
&& Array.isArray(patch.insert) && patch.insert.length === 1 && patch.insert[0];
if (!isObject(entry) || Object.keys(entry).some((key) => !['id', 'name', 'config', 'disabled'].includes(key))
|| entry.id !== target.serverName || entry.name !== '@deepseek-ai/dsh-mcp-client'
|| !isObject(entry.config) || entry.config.serverName !== target.serverName
|| entry.config.transport !== 'streamable-http') {
throw new Error('The dedicated DSH overlay contains unrelated or ambiguous entries; the file was left unchanged.');
}
if (entry.disabled !== undefined && entry.disabled !== false) {
throw new Error('The DSH MCP entry is disabled; review it manually. The file was left unchanged.');
}
return entry;
}
function configureDshTarget(target) {
const original = readOptionalText(target.configPath);
const existing = original === null ? {} : readDshEntry(target, original);
if (existing.config && !canReplaceEntry(target, target.serverName, existing.config.url)) {
throw new Error(`MCP entry '${target.serverName}' already belongs to another endpoint. Existing configuration was left unchanged.`);
}
const content = JSON.stringify(getDshPatch(target, existing), null, 2) + '\n';
if (content !== original) writeTextIfUnchanged(target.configPath, content, original);
}
function getDshLaunchCommand(configPath, platform) {
// Single-quote paths for the host's POSIX shell or Windows PowerShell. Do not
// interpolate project names as executable shell syntax in the displayed hint.
const quoted = platform === 'win32' ? configPath.replace(/'/g, "''") : configPath.replace(/'/g, "'\\''");
return `dsh web --patch '${quoted}'`;
}
function configureTomlTarget(target) {
ensureParent(target.configPath);
const name = target.serverName || SERVER_NAME;
const sectionHeader = `[mcp_servers.${name}]`;
const section = `${sectionHeader}\nurl = "${target.url}"\n`;
const original = readOptionalText(target.configPath);
let content = original || '';
const blocks = getTomlBlocks(content);
const existing = blocks.find((block) => block.name === name);
if (existing) {
assertTomlRemoteBlock(existing);
if (!canReplaceEntry(target, name, existing.url)) throw new Error(`MCP entry '${name}' already belongs to another endpoint. Existing configuration was left unchanged.`);
const updated = existing.text.replace(/^[ \t]*url[ \t]*=[^\n]*/m, `url = "${target.url}"`);
content = content.slice(0, existing.start) + updated + content.slice(existing.end);
} else {
if (content.length > 0 && !content.endsWith('\n')) {
content += '\n';
}
if (content.length > 0) {
content += '\n';
}
content += section;
}
// Retire only exact generated URL-only blocks that this project can identify.
const previous = target.previousEntry;
const retired = getTomlBlocks(content).filter((block) => block.name !== name && (
(target.migrateLegacy && block.name === SERVER_NAME && block.url === target.url) ||
(previous && previous.configPath === target.configPath && block.name === previous.serverName && block.url === previous.url)
) && !block.hasChildren && block.text.trim().split('\n').length === 2);
for (const block of retired.reverse()) content = content.slice(0, block.start) + content.slice(block.end);
writeTextIfUnchanged(target.configPath, content, original);
}
function getTomlBlocks(content) {
// Do not guess at TOML forms that could hide table-looking text inside strings.
const first = content.replace(/^\uFEFF/, '').split(/\r?\n/).find((line) => line.trim() && !line.trim().startsWith('#'));
if (first && /^[ \t]*[{}=]/.test(first)) throw new Error('This is not a supported TOML configuration; review it manually. The file was left unchanged.');
if (/"""|'''|^[ \t]*mcp_servers[ \t]*=/m.test(content)) throw new Error('This TOML uses multiline strings or inline MCP tables. Configure it manually; the file was left unchanged.');
const headers = [...content.matchAll(/^[ \t]*\[(\[[^\]\r\n]+\]|[^\]\r\n]+)\][ \t]*(?:#[^\n]*)?\r?$/gm)];
const blocks = [];
let hasParent = false;
for (let index = 0; index < headers.length; index += 1) {
const header = headers[index];
if (header[1].trim() === 'mcp_servers') {
const end = index + 1 < headers.length ? headers[index + 1].index : content.length;
const body = content.slice(header.index + header[0].length, end);
if (hasParent || body.split(/\r?\n/).some((line) => line.trim() && !line.trim().startsWith('#'))) {
throw new Error('Duplicate or inline MCP parent table. Use explicit [mcp_servers.name] tables; the file was left unchanged.');
}
hasParent = true;
continue;
}
const match = header[1].trim().match(/^mcp_servers\s*\.\s*(?:([A-Za-z0-9_-]+)|"([A-Za-z0-9_-]+)"|'([A-Za-z0-9_-]+)')$/);
if (!match) continue;
const start = header.index;
const end = index + 1 < headers.length ? headers[index + 1].index : content.length;
const text = content.slice(start, end);
const urls = [...text.matchAll(/^[ \t]*url[ \t]*=[ \t]*["']([^"']+)["'][ \t]*(?:#[^\n]*)?\r?$/gm)];
const name = match[1] || match[2] || match[3];
if (blocks.some((block) => block.name === name) || urls.length > 1) throw new Error('Duplicate MCP table or URL; configuration was left unchanged.');
const hasChildren = headers.some((item) => [name, `"${name}"`, `'${name}'`].some((key) => item[1].trim().replace(/\s*\.\s*/g, '.').startsWith(`mcp_servers.${key}.`)));
blocks.push({ name, start, end, text, hasChildren, url: urls.length ? urls[0][1] : '' });
}
return blocks;
}
function assertTomlRemoteBlock(block) {
if (/^[ \t]*command[ \t]*=/m.test(block.text)) throw new Error('This MCP table declares a local command; the file was left unchanged.');
if (/^[ \t]*enabled[ \t]*=[ \t]*false[ \t]*(?:#[^\n]*)?\r?$/m.test(block.text)) throw new Error('This MCP table is disabled. Enable it in Codex before configuring; the file was left unchanged.');
}
function buildTargets(config, options = {}) {
const home = options.homePath || getUserHomePath();
const env = options.env || process.env;
const platform = options.platform || process.platform;
const resolveGitRoot = options.resolveGitRoot || findGitRootOrSelf;
const url = serverUrl(config);
return [
{
id: 'claude_code',
name: 'Claude Code',
configPath: path.join(home, '.claude.json'),
rootKey: 'mcpServers',
entry: { type: 'http', url },
},
{
id: 'cursor',
name: 'Cursor',
configPath: path.join(home, '.cursor', 'mcp.json'),
rootKey: 'mcpServers',
entry: { url },
},
{
id: 'vscode',
name: 'VS Code',
configPath: getVSCodeConfigPath(home, options),
rootKey: 'servers',
entry: { type: 'http', url },
isJsonc: true,
},
{
id: 'kiro',
name: 'Kiro',
configPath: path.join(home, '.kiro', 'settings', 'mcp.json'),
rootKey: 'mcpServers',
entry: { type: 'http', url },
},
{
id: 'qoder',
name: 'Qoder',
configPath: path.join(
getConfiguredDirectory(env, 'QODER_CONFIG_DIR', path.join(home, '.qoder')),
'settings.json'
),
rootKey: 'mcpServers',
entry: { type: 'http', url },
},
{
id: 'kimi',
name: 'Kimi Code',
configPath: path.join(
getConfiguredDirectory(env, 'KIMI_CODE_HOME', path.join(home, '.kimi-code')),
'mcp.json'
),
rootKey: 'mcpServers',
entry: { url },
},
{
id: 'codex',
name: 'Codex',
configPath: path.join(getConfiguredDirectory(env, 'CODEX_HOME', path.join(home, '.codex')), 'config.toml'),
isToml: true,
url,
},
{
id: 'opencode',
name: 'OpenCode',
configPath: getOpenCodeConfigPath(home, options),
rootKey: 'mcp',
entry: { type: 'remote', url },
isJsonc: true,
},
// These clients load their configuration from the current Cocos project.
...(config.projectPath ? [{
id: 'trae',
name: 'Trae',
configPath: path.resolve(config.projectPath, '.trae', 'mcp.json'),
rootKey: 'mcpServers',
entry: { url },
setupHintKey: 'client.trae_project_hint',
}, {
id: 'antigravity',
name: 'Antigravity',
configPath: path.resolve(config.projectPath, '.agents', 'mcp_config.json'),
projectPath: config.projectPath,
rootKey: 'mcpServers',
urlField: 'serverUrl',
entry: { serverUrl: url },
setupHintKey: 'client.antigravity_project_hint',
}, {
id: 'pi',
name: 'Pi',
configPath: path.resolve(config.projectPath, '.pi', 'mcp.json'),
projectPath: config.projectPath,
rootKey: 'mcpServers',
entry: { url },
setupHintKey: 'client.pi_project_hint',
}, {
// CodeBuddy IDE 4.0+ reads the workspace .mcp.json.
id: 'codebuddy',
name: 'CodeBuddy IDE',
configPath: path.resolve(config.projectPath, '.mcp.json'),
rootKey: 'mcpServers',
entry: { type: 'http', url },
isJsonc: true,
}, {
id: 'deepseek_harness',
name: 'DeepSeek Harness (DSH)',
configPath: path.resolve(config.projectPath, '.dsh', 'funplay-cocos-mcp.patch.json'),
isDsh: true,
entry: { serverName: getServerName(config), transport: 'streamable-http', url },
launchCommand: getDshLaunchCommand(path.resolve(config.projectPath, '.dsh', 'funplay-cocos-mcp.patch.json'), platform),
}] : []),
].map((target) => config.projectPath ? ({
...target,
serverName: getServerName(config),
...(target.id === 'claude_code'
? { scopePath: getClaudeScopePath(config.projectPath, platform, resolveGitRoot), platform }
: {}),
previousEntry: getPreviousEntry(config, target.id),
legacyUrl: serverUrl(config, config.port, ''),
migrateLegacy: config.migrateLegacy === true,
}) : target);
}
function getTomlServerUrl(target) {
if (!fs.existsSync(target.configPath)) {
return '';
}
const content = fs.readFileSync(target.configPath, 'utf8');
const block = getTomlBlocks(content).find((item) => item.name === (target.serverName || SERVER_NAME));
if (block) assertTomlRemoteBlock(block);
return block ? block.url : '';
}
function inspectTarget(target) {
try {
if (target.projectPath) resolveProjectFilePath(target.projectPath, target.configPath);
if (!fs.existsSync(target.configPath)) return { configured: false };
let url;
let configured;
let serverName = target.serverName || SERVER_NAME;
if (target.isToml) {
url = getTomlServerUrl(target);
configured = url === target.url;
} else if (target.isDsh) {
const entry = readDshEntry(target, fs.readFileSync(target.configPath, 'utf8'));
url = entry.config.url;
configured = Object.entries(target.entry).every(([key, value]) => entry.config[key] === value);
} else {
const root = readJson(target.configPath, target.isJsonc);
const servers = getServerContainer(root, target);
serverName = resolveJsonServerName(servers, target);
const entry = servers && servers[serverName];
const urlField = target.urlField || 'url';
assertRemoteEntry(entry, urlField);
url = getJsonEntryUrl(entry, urlField);
configured = isObject(entry) && url === getTargetUrl(target) && matchesJsonTransport(entry, target);
// Do not remove an old shared entry. Offer a separate project-bound entry.
if (!entry && target.legacyUrl && servers && getJsonEntryUrl(servers[SERVER_NAME], urlField) === target.legacyUrl) {
return { configured: false, needsReconfigure: true, canReconfigure: true };
}
}
const legacy = Boolean(target.legacyUrl && url === target.legacyUrl && url !== getTargetUrl(target));
return { configured, serverName, ...(legacy ? { needsReconfigure: true, canReconfigure: canReplaceEntry(target, serverName, url) } : {}) };
} catch (error) {
return { configured: false, readError: error.message.slice(0, 500) };
}
}
function getTargetStatuses(config, options = {}) {
return buildTargets(config, options).map((target) => ({
id: target.id,
name: target.name,
configPath: target.configPath,
serverName: target.serverName || SERVER_NAME,
...inspectTarget(target),
isToml: Boolean(target.isToml),
...(target.setupHintKey ? { setupHintKey: target.setupHintKey } : {}),
...(target.launchCommand ? { launchCommand: target.launchCommand } : {}),
}));
}
function configureTarget(config, targetId, options = {}) {
if (config.stablePort !== undefined && config.port !== config.stablePort) throw new Error('Server is using a temporary fallback port. Pin the current port or use the per-project port before configuring a client.');
const targets = buildTargets(config, options);
const target = targets.find((item) => item.id === targetId);
if (!target) {
throw new Error(`Unknown MCP client target: ${targetId}`);
}
let serverName = target.serverName || SERVER_NAME;
if (target.isToml) {
configureTomlTarget(target);
} else if (target.isDsh) {
configureDshTarget(target);
} else {
serverName = configureJsonTarget(target);
}
return {
id: target.id,
name: target.name,
configPath: target.configPath,
configured: true,
serverName,
url: getTargetUrl(target),
projectIdentity: config.projectPath ? getProjectIdentity(config.projectPath) : '',
...(target.launchCommand ? { launchCommand: target.launchCommand } : {}),
...(target.setupHintKey ? { setupHintKey: target.setupHintKey } : {}),
restartHint: target.launchCommand
? `From the Cocos project directory, start DSH with: ${target.launchCommand}. The overlay is not loaded automatically.`
: `Please restart ${target.name} for the MCP configuration to take effect.`,
};
}
module.exports = {
SERVER_NAME,
getServerName,
formatTargetPreview,
buildTargets,
configureTarget,
getTargetStatuses,
};
+208
View File
@@ -0,0 +1,208 @@
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const net = require('net');
const path = require('path');
const { normalizeLanguagePreference } = require('./i18n');
const { normalizeSavedToolProfiles } = require('./tool-profiles');
const DEFAULTS = {
host: '127.0.0.1',
port: 8765,
portMode: 'project',
toolProfile: 'core',
enabledTools: [],
disabledTools: [],
enabledToolCategories: [],
disabledToolCategories: [],
enableSessions: false,
enableConsoleLogging: true,
executeJavascriptSafetyChecks: true,
autostart: true,
maxInteractionLogEntries: 50,
lastClientTargetId: 'claude_code',
activeToolProfileName: '',
savedToolProfiles: [],
language: 'auto',
};
const RUNTIME_CONFIG_KEYS = [
'host',
'port',
'toolProfile',
'enabledTools',
'disabledTools',
'enabledToolCategories',
'disabledToolCategories',
'enableSessions',
'executeJavascriptSafetyChecks',
'maxInteractionLogEntries',
];
function getProjectPath() {
if (global.Editor && Editor.Project && typeof Editor.Project.path === 'string' && Editor.Project.path) {
return Editor.Project.path;
}
return process.cwd();
}
function getProjectName() {
return path.basename(getProjectPath());
}
function normalizeProjectIdentityPath(projectPath) {
const normalized = path.resolve(String(projectPath || process.cwd())).replace(/\\/g, '/');
return process.platform === 'win32' ? normalized.toLowerCase() : normalized;
}
function getProjectIdentity(projectPath = getProjectPath()) {
return crypto
.createHash('sha256')
.update(`funplay-cocos-mcp:${normalizeProjectIdentityPath(projectPath)}`)
.digest('hex')
.slice(0, 24);
}
function getProjectPort(projectPath = getProjectPath()) {
return 20000 + (parseInt(getProjectIdentity(projectPath).slice(0, 8), 16) % 10000);
}
function getCocosVersion() {
if (global.Editor && Editor.App) {
if (typeof Editor.App.version === 'string' && Editor.App.version) {
return Editor.App.version;
}
if (typeof Editor.App.ver === 'string' && Editor.App.ver) {
return Editor.App.ver;
}
}
return 'unknown';
}
function loadJson(filePath) {
if (!fs.existsSync(filePath)) {
return null;
}
try {
return JSON.parse(fs.readFileSync(filePath, 'utf8'));
} catch (error) {
return {
__error: `Failed to parse config file '${filePath}': ${error.message}`,
};
}
}
function clampPort(value) {
const port = Number(value);
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
return DEFAULTS.port;
}
return port;
}
function normalizeProfile(value) {
const normalized = String(value || DEFAULTS.toolProfile).toLowerCase();
if (normalized === 'full' || normalized === 'custom') {
return normalized;
}
return 'core';
}
function normalizeStringList(value) {
if (Array.isArray(value)) {
return value
.map((item) => String(item || '').trim())
.filter(Boolean);
}
if (typeof value === 'string') {
return value
.split(/[\n,]/)
.map((item) => item.trim())
.filter(Boolean);
}
return [];
}
function normalizeClientTargetId(value) {
const normalized = String(value || '').trim();
return normalized || DEFAULTS.lastClientTargetId;
}
function normalizeHost(value) {
const host = typeof value === 'string' ? value.trim() : '';
const hostname = host.length <= 253 && host.split('.').every((label) => (
/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(label)
));
if (!host || (!net.isIP(host) && !hostname)) {
throw new Error('Host must be an IP address or hostname, without a URL scheme, path, or port.');
}
return host;
}
function hasRuntimeConfigChanges(currentConfig = {}, nextConfig = {}) {
return RUNTIME_CONFIG_KEYS.some((key) => (
JSON.stringify(currentConfig[key]) !== JSON.stringify(nextConfig[key])
));
}
function loadConfig(options = {}) {
const projectPath = options.projectPath || getProjectPath();
const env = options.env || process.env;
const configPath = path.join(projectPath, 'funplay-cocos-mcp.config.json');
const fileConfig = loadJson(configPath) || {};
// Existing config files without a mode retain their old fixed endpoint.
const portMode = fileConfig.portMode === 'project' || (!fs.existsSync(configPath) && !env.COCOS_MCP_PORT)
? 'project' : 'fixed';
const port = clampPort(env.COCOS_MCP_PORT || (portMode === 'project' ? getProjectPort(projectPath) : fileConfig.port || DEFAULTS.port));
return {
...DEFAULTS,
...fileConfig,
host: env.COCOS_MCP_HOST || fileConfig.host || DEFAULTS.host,
hostSource: env.COCOS_MCP_HOST ? 'environment' : 'project',
port,
portMode: env.COCOS_MCP_PORT ? 'fixed' : portMode,
projectPath,
clientConfigEntries: fileConfig.clientConfigEntries && typeof fileConfig.clientConfigEntries === 'object' && !Array.isArray(fileConfig.clientConfigEntries)
? fileConfig.clientConfigEntries : {},
toolProfile: normalizeProfile(process.env.COCOS_MCP_PROFILE || fileConfig.toolProfile || DEFAULTS.toolProfile),
enabledTools: normalizeStringList(fileConfig.enabledTools),
disabledTools: normalizeStringList(fileConfig.disabledTools),
enabledToolCategories: normalizeStringList(fileConfig.enabledToolCategories).map((item) => item.toLowerCase()),
disabledToolCategories: normalizeStringList(fileConfig.disabledToolCategories).map((item) => item.toLowerCase()),
enableSessions: typeof fileConfig.enableSessions === 'boolean' ? fileConfig.enableSessions : DEFAULTS.enableSessions,
enableConsoleLogging: typeof fileConfig.enableConsoleLogging === 'boolean'
? fileConfig.enableConsoleLogging
: DEFAULTS.enableConsoleLogging,
executeJavascriptSafetyChecks: typeof fileConfig.executeJavascriptSafetyChecks === 'boolean'
? fileConfig.executeJavascriptSafetyChecks
: DEFAULTS.executeJavascriptSafetyChecks,
autostart: typeof fileConfig.autostart === 'boolean' ? fileConfig.autostart : DEFAULTS.autostart,
maxInteractionLogEntries: Number.isInteger(fileConfig.maxInteractionLogEntries)
? Math.max(10, Math.min(500, fileConfig.maxInteractionLogEntries))
: DEFAULTS.maxInteractionLogEntries,
lastClientTargetId: normalizeClientTargetId(fileConfig.lastClientTargetId),
activeToolProfileName: typeof fileConfig.activeToolProfileName === 'string' ? fileConfig.activeToolProfileName : '',
savedToolProfiles: normalizeSavedToolProfiles(fileConfig.savedToolProfiles),
language: normalizeLanguagePreference(fileConfig.language),
configPath,
configError: fileConfig.__error || '',
};
}
module.exports = {
DEFAULTS,
getProjectPath,
getProjectName,
getProjectIdentity,
getProjectPort,
getCocosVersion,
loadConfig,
hasRuntimeConfigChanges,
normalizeProfile,
normalizeHost,
normalizeStringList,
normalizeLanguagePreference,
};
+179
View File
@@ -0,0 +1,179 @@
'use strict';
const fs = require('fs');
const path = require('path');
const { execFile } = require('child_process');
function exists(filePath) {
try {
return fs.existsSync(filePath);
} catch (error) {
return false;
}
}
function findTypescriptCommand(projectPath, runtime = {}) {
const platform = runtime.platform || process.platform;
const nodeBinary = runtime.execPath || process.execPath;
const possibleRoots = [
runtime.editorPath || (global.Editor && Editor.App && Editor.App.path),
runtime.resourcesPath || process.resourcesPath,
global.Editor && Editor.App && Editor.App.path ? path.dirname(Editor.App.path) : '',
global.Editor && Editor.App && Editor.App.path ? path.resolve(Editor.App.path, '..') : '',
].filter(Boolean);
const editorBundledScripts = [];
for (const root of possibleRoots) {
editorBundledScripts.push(
path.join(root, 'resources', '3d', 'engine', 'node_modules', 'typescript', 'bin', 'tsc'),
path.join(root, 'resources', '3d', 'engine', 'node_modules', '@cocos', 'typescript', 'bin', 'tsc'),
path.join(root, 'app.asar.unpacked', 'node_modules', 'typescript', 'bin', 'tsc'),
path.join(root, 'Contents', 'Resources', 'resources', '3d', 'engine', 'node_modules', 'typescript', 'bin', 'tsc'),
path.join(root, 'Contents', 'Resources', 'resources', '3d', 'engine', 'node_modules', '@cocos', 'typescript', 'bin', 'tsc')
);
}
const scriptCandidates = [
path.join(projectPath, 'node_modules', 'typescript', 'bin', 'tsc'),
...editorBundledScripts,
];
for (const scriptPath of scriptCandidates) {
if (exists(scriptPath)) {
return {
binary: nodeBinary,
argsPrefix: [scriptPath],
compiler: scriptPath,
env: { ELECTRON_RUN_AS_NODE: '1' },
};
}
}
if (platform === 'win32') {
return null;
}
return {
binary: 'npx',
argsPrefix: ['tsc'],
compiler: 'npx tsc',
};
}
function findTsConfig(projectPath, explicitPath) {
if (explicitPath) {
return path.isAbsolute(explicitPath) ? explicitPath : path.join(projectPath, explicitPath);
}
const candidates = [
path.join(projectPath, 'tsconfig.json'),
path.join(projectPath, 'temp', 'tsconfig.cocos.json'),
];
return candidates.find((candidate) => exists(candidate)) || '';
}
function runExec(file, args, cwd, env = {}) {
return new Promise((resolve) => {
execFile(file, args, {
cwd,
env: { ...process.env, ...env },
maxBuffer: 8 * 1024 * 1024,
}, (error, stdout, stderr) => {
resolve({
code: error && typeof error.code === 'number' ? error.code : 0,
stdout: stdout || '',
stderr: stderr || '',
error: error ? error.message : '',
});
});
});
}
function parseTscOutput(output) {
const lines = String(output || '')
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean);
const diagnostics = [];
const regex = /^(.*)\((\d+),(\d+)\):\s+error\s+(TS\d+):\s+(.*)$/i;
for (const line of lines) {
const match = regex.exec(line);
if (!match) {
continue;
}
diagnostics.push({
file: match[1],
line: Number(match[2]),
column: Number(match[3]),
code: match[4],
message: match[5],
});
}
return diagnostics;
}
async function runScriptDiagnostics(projectPath, options = {}) {
const tsconfigPath = findTsConfig(projectPath, options.tsconfigPath);
if (!tsconfigPath || !exists(tsconfigPath)) {
return {
ok: false,
tool: 'typescript',
summary: 'No tsconfig.json was found in the Cocos project.',
diagnostics: [],
stdout: '',
stderr: '',
};
}
const command = findTypescriptCommand(projectPath);
if (!command) {
return {
ok: false,
tool: 'typescript',
summary: 'TypeScript compiler was not found in the Cocos project or editor installation.',
diagnostics: [],
stdout: '',
stderr: '',
};
}
const args = [
...command.argsPrefix,
'--noEmit',
'-p',
tsconfigPath,
'--pretty',
'false',
];
const result = await runExec(command.binary, args, projectPath, command.env);
const mergedOutput = [result.stdout, result.stderr, result.error].filter(Boolean).join('\n').trim();
const diagnostics = parseTscOutput(mergedOutput);
const ok = result.code === 0 && diagnostics.length === 0;
return {
ok,
tool: 'typescript',
binary: command.binary,
compiler: command.compiler,
tsconfigPath,
exitCode: result.code,
summary: ok
? 'TypeScript diagnostics completed successfully with no errors.'
: diagnostics.length
? `Found ${diagnostics.length} TypeScript error(s).`
: mergedOutput || 'TypeScript diagnostics reported a non-zero exit code.',
diagnostics,
stdout: result.stdout,
stderr: result.stderr,
};
}
module.exports = {
findTypescriptCommand,
runScriptDiagnostics,
};
+336
View File
@@ -0,0 +1,336 @@
'use strict';
function getElectron() {
try {
return require('electron');
} catch (error) {
throw new Error(`Electron APIs are unavailable: ${error.message}`);
}
}
function normalizeText(value) {
return String(value || '').trim().toLowerCase();
}
function getAllWindows() {
const electron = getElectron();
const BrowserWindow = electron.BrowserWindow;
if (!BrowserWindow || typeof BrowserWindow.getAllWindows !== 'function') {
throw new Error('Electron BrowserWindow API is unavailable.');
}
return BrowserWindow.getAllWindows().filter((window) => window && !window.isDestroyed());
}
function inferWindowKind(title) {
const normalized = normalizeText(title);
if (normalized.includes('simulator')) {
return 'simulator';
}
if (normalized.includes('preview')) {
return 'preview';
}
if (normalized.includes('cocos creator') || normalized.includes('cocos')) {
return 'editor';
}
return 'unknown';
}
function listWindows() {
return getAllWindows().map((window, index) => ({
index,
id: typeof window.id === 'number' ? window.id : index,
title: typeof window.getTitle === 'function' ? window.getTitle() : '',
bounds: typeof window.getBounds === 'function' ? window.getBounds() : null,
visible: typeof window.isVisible === 'function' ? window.isVisible() : true,
focused: typeof window.isFocused === 'function' ? window.isFocused() : false,
kind: inferWindowKind(typeof window.getTitle === 'function' ? window.getTitle() : ''),
}));
}
function pickWindow(options = {}) {
const electron = getElectron();
const BrowserWindow = electron.BrowserWindow;
const windows = getAllWindows();
if (!windows.length) {
throw new Error('No Electron windows are available.');
}
if (options.windowId !== undefined) {
if (!Number.isInteger(options.windowId)) throw new Error('windowId must be an integer returned by list_editor_windows or a screenshot.');
const target = windows.find((window) => window.id === options.windowId);
if (!target) throw new Error(`Electron window ${options.windowId} is unavailable.`);
return target;
}
const titleContains = normalizeText(options.titleContains);
const windowKind = normalizeText(options.windowKind || 'focused');
const focusedWindow = BrowserWindow.getFocusedWindow && BrowserWindow.getFocusedWindow();
const titleMatches = (window) => {
if (!titleContains) {
return true;
}
return normalizeText(window.getTitle && window.getTitle()).includes(titleContains);
};
const kindMatches = (window) => {
const kind = inferWindowKind(window.getTitle && window.getTitle());
switch (windowKind) {
case 'focused':
return true;
case 'editor':
case 'simulator':
case 'preview':
return kind === windowKind;
default:
return true;
}
};
const candidates = windows.filter((window) => kindMatches(window) && titleMatches(window));
const target = (focusedWindow && candidates.includes(focusedWindow) && focusedWindow)
|| candidates.find((window) => typeof window.isVisible === 'function' ? window.isVisible() : true)
|| candidates[0];
if (!target) {
throw new Error(`No BrowserWindow matched windowKind='${windowKind}' titleContains='${titleContains}'.`);
}
return target;
}
async function executeJavaScript(window, script) {
if (!window || !window.webContents || typeof window.webContents.executeJavaScript !== 'function') {
throw new Error('Target window does not support webContents.executeJavaScript.');
}
return await window.webContents.executeJavaScript(script, true);
}
function buildPanelBoundsScript(panelName) {
const panel = JSON.stringify(String(panelName || 'scene'));
return `
(() => {
try {
const panelName = ${panel}.toLowerCase();
const isVisible = (element) => {
if (!element || typeof element.getBoundingClientRect !== 'function') return false;
const style = window.getComputedStyle(element);
const rect = element.getBoundingClientRect();
return style && style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 4 && rect.height > 4;
};
const textOf = (element) => {
const parts = [
element.getAttribute && element.getAttribute('name'),
element.getAttribute && element.getAttribute('title'),
element.id,
element.className,
element.textContent,
];
return parts.filter(Boolean).join(' ').toLowerCase();
};
const collectAll = (root, bucket) => {
if (!root) return;
const nodes = root.querySelectorAll ? root.querySelectorAll('*') : [];
for (const node of nodes) {
if (bucket.length >= 15000) throw new Error('Panel discovery exceeded its DOM budget.');
bucket.push(node);
if (node.shadowRoot) {
collectAll(node.shadowRoot, bucket);
}
}
};
const all = [];
collectAll(document, all);
const viewportBounds = (element, label) => {
const rect = element.getBoundingClientRect();
return {
x: rect.left, y: rect.top, width: rect.width, height: rect.height,
elementTag: element.tagName, innerTag: element.tagName,
text: label, innerText: label,
};
};
// Creator 3.8 Game View lives inside the Scene panel's shadow DOM. Its
// toolbar contains "game" but is not the render surface; text scoring
// alone can crop just that 29px bar. Prefer the native engine WebView.
if (panelName === 'game' || panelName === 'scene') {
const gamePreload = '/preload/web/preview.js';
const scenePreload = '/preload/web/preload.js';
const engineViews = all.flatMap((element) => {
if (String(element.tagName).toLowerCase() !== 'webview') return [];
try {
const source = new URL(element.getAttribute('src') || '');
if (source.protocol !== 'packages:' || source.hostname !== 'scene') return [];
const scriptPath = (source.searchParams.get('url') || source.pathname).replace(/\\\\/g, '/');
if (scriptPath.endsWith(gamePreload)) return [{ element, panel: 'game' }];
if (scriptPath.endsWith(scenePreload)) return [{ element, panel: 'scene' }];
} catch (error) {
// A WebView without a parseable source cannot identify a native viewport.
}
return [];
});
const nativeViews = engineViews.filter((view) => view.panel === panelName && isVisible(view.element));
if (nativeViews.length > 1) throw new Error('Multiple visible native ' + panelName + ' viewports matched; choose an exact window.');
if (nativeViews.length === 1) return viewportBounds(nativeViews[0].element, 'native-' + panelName + '-viewport');
if (engineViews.length) throw new Error('The native ' + panelName + ' viewport is not visible or ready; activate it and capture again.');
}
if (panelName === 'game') {
const gameCanvases = all.filter((element) => (
String(element.tagName).toLowerCase() === 'canvas' && element.id === 'GameCanvas' && isVisible(element)
));
if (gameCanvases.length === 1) return viewportBounds(gameCanvases[0], 'game-canvas');
if (gameCanvases.length > 1) throw new Error('Multiple visible GameCanvas elements matched; choose an exact preview window.');
throw new Error('Could not locate a visible Cocos Game View or GameCanvas. Open Editor Preview or select the window containing the game preview.');
}
const scoreElement = (element) => {
const text = textOf(element);
let score = 0;
if (text.includes(panelName)) score += 100;
if (text.includes('panel-frame')) score += 5;
if (panelName === 'scene' && text.includes('game')) score -= 10;
return score;
};
const largestChildRect = (element) => {
const bucket = [element];
if (element.shadowRoot) collectAll(element.shadowRoot, bucket);
const children = bucket
.filter((node) => isVisible(node))
.map((node) => {
const rect = node.getBoundingClientRect();
const text = textOf(node);
let score = rect.width * rect.height;
if (node.tagName && node.tagName.toLowerCase() === 'canvas') score += 50000;
if (text.includes(panelName)) score += 20000;
if (text.includes('canvas') || text.includes('preview') || text.includes('viewport')) score += 10000;
return { rect, score, tag: node.tagName || '', text };
})
.sort((a, b) => b.score - a.score);
return children[0] || null;
};
const candidates = all
.filter((element) => isVisible(element))
.map((element) => {
const panelScore = scoreElement(element);
if (panelScore <= 0) return null;
const rectInfo = largestChildRect(element) || { rect: element.getBoundingClientRect(), score: 0, tag: element.tagName || '', text: textOf(element) };
return {
score: panelScore + rectInfo.score,
elementTag: element.tagName || '',
rect: rectInfo.rect,
text: textOf(element),
innerTag: rectInfo.tag,
innerText: rectInfo.text,
};
})
.filter(Boolean)
.sort((a, b) => b.score - a.score);
const fallbackCanvases = all
.filter((element) => isVisible(element) && element.tagName && element.tagName.toLowerCase() === 'canvas')
.map((element) => {
const rect = element.getBoundingClientRect();
const text = textOf(element);
let score = rect.width * rect.height;
if (text.includes(panelName)) score += 50000;
return { score, rect, elementTag: 'CANVAS', text, innerTag: 'CANVAS', innerText: text };
})
.sort((a, b) => b.score - a.score);
const target = candidates[0] || fallbackCanvases[0];
if (!target) return null;
return {
x: Math.max(0, Math.floor(target.rect.left)),
y: Math.max(0, Math.floor(target.rect.top)),
width: Math.max(1, Math.floor(target.rect.width)),
height: Math.max(1, Math.floor(target.rect.height)),
elementTag: target.elementTag,
innerTag: target.innerTag,
text: target.text,
innerText: target.innerText,
};
} catch (error) {
// Electron discards thrown renderer error messages. Return a bounded
// diagnostic so the host can report why this viewport was rejected.
return { panelDiscoveryError: String(error && error.message || error).slice(0, 500) };
}
})();
`;
}
async function getPanelBounds(window, panelName) {
const result = await executeJavaScript(window, buildPanelBoundsScript(panelName));
if (result && result.panelDiscoveryError) throw new Error(result.panelDiscoveryError);
if (!result || !result.width || !result.height) {
throw new Error(`Could not locate a visible '${panelName}' panel in the target window.`);
}
return result;
}
function buildPanelFocusScript(panelName, offsetX, offsetY) {
return `
(() => {
const panelName = ${JSON.stringify(String(panelName || 'scene').toLowerCase())};
const offsetX = ${Number(offsetX || 0)};
const offsetY = ${Number(offsetY || 0)};
const isVisible = (element) => {
if (!element || typeof element.getBoundingClientRect !== 'function') return false;
const style = window.getComputedStyle(element);
const rect = element.getBoundingClientRect();
return style && style.display !== 'none' && style.visibility !== 'hidden' && rect.width > 4 && rect.height > 4;
};
const textOf = (element) => [
element.getAttribute && element.getAttribute('name'),
element.getAttribute && element.getAttribute('title'),
element.id,
element.className,
element.textContent,
].filter(Boolean).join(' ').toLowerCase();
const collectAll = (root, bucket) => {
if (!root) return;
const nodes = root.querySelectorAll ? root.querySelectorAll('*') : [];
for (const node of nodes) {
bucket.push(node);
if (node.shadowRoot) collectAll(node.shadowRoot, bucket);
}
};
const all = [];
collectAll(document, all);
const target = all.find((element) => isVisible(element) && textOf(element).includes(panelName));
const rect = target ? target.getBoundingClientRect() : { left: 0, top: 0, width: window.innerWidth, height: window.innerHeight };
const x = Math.floor(rect.left + rect.width / 2 + offsetX);
const y = Math.floor(rect.top + rect.height / 2 + offsetY);
const focusable = document.elementFromPoint(x, y) || target || document.body;
if (focusable && typeof focusable.focus === 'function') focusable.focus();
return { x, y };
})();
`;
}
async function getPanelPoint(window, panelName, offsetX, offsetY) {
return await executeJavaScript(window, buildPanelFocusScript(panelName, offsetX, offsetY));
}
function sleep(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds));
}
module.exports = {
executeJavaScript,
getAllWindows,
getPanelBounds,
getPanelPoint,
inferWindowKind,
listWindows,
pickWindow,
sleep,
};
+351
View File
@@ -0,0 +1,351 @@
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const { compareVersions, normalizeVersion } = require('./update-checker');
const { installLatestUpdate } = require('./updater');
const PACKAGE_NAME = 'funplay-cocos-mcp';
function normalizePathForComparison(value) {
const resolved = path.resolve(String(value || ''));
return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
}
function realPathOrResolved(value) {
const resolved = path.resolve(String(value || ''));
try {
const realPath = fs.realpathSync.native
? fs.realpathSync.native(resolved)
: fs.realpathSync(resolved);
return normalizePathForComparison(realPath);
} catch (error) {
return normalizePathForComparison(resolved);
}
}
function isSameLocation(left, right) {
if (!left || !right) {
return false;
}
return realPathOrResolved(left) === realPathOrResolved(right);
}
function getGlobalExtensionsDirectory(options = {}) {
const editorHomePath = String(options.editorHomePath || '').trim();
const editorVersion = String(options.editorVersion || '').trim().replace(/^v/i, '');
if (editorHomePath && editorVersion) {
return path.resolve(editorHomePath, 'builtin-extensions', editorVersion);
}
const homePath = String(options.homePath || os.homedir() || '').trim();
if (!homePath) {
throw new Error('Unable to resolve the current user home directory for the Cocos global extension install.');
}
return path.resolve(homePath, '.CocosCreator', 'extensions');
}
function readPackageInstallation(packagePath) {
const resolvedPath = path.resolve(String(packagePath || ''));
let stat;
try {
stat = fs.lstatSync(resolvedPath);
} catch (error) {
if (error && error.code === 'ENOENT') {
return {
path: resolvedPath,
realPath: realPathOrResolved(resolvedPath),
exists: false,
valid: false,
name: '',
version: '',
isSymlink: false,
error: '',
};
}
return {
path: resolvedPath,
realPath: realPathOrResolved(resolvedPath),
exists: true,
valid: false,
name: '',
version: '',
isSymlink: false,
error: error.message,
};
}
const installation = {
path: resolvedPath,
realPath: realPathOrResolved(resolvedPath),
exists: true,
valid: false,
name: '',
version: '',
isSymlink: stat.isSymbolicLink(),
error: '',
};
if (!stat.isDirectory() && !stat.isSymbolicLink()) {
installation.error = 'The extension path exists but is not a directory.';
return installation;
}
const manifestPath = path.join(resolvedPath, 'package.json');
if (!fs.existsSync(manifestPath)) {
installation.error = 'package.json is missing.';
return installation;
}
try {
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
installation.name = String(manifest.name || '');
installation.version = normalizeVersion(manifest.version || '');
installation.valid = installation.name === PACKAGE_NAME && Boolean(installation.version);
if (!installation.valid) {
installation.error = installation.name !== PACKAGE_NAME
? `Unexpected extension package name: ${installation.name || 'unknown'}.`
: 'The extension package version is missing.';
}
} catch (error) {
installation.error = `Failed to read package.json: ${error.message}`;
}
return installation;
}
function getGlobalInstallationState(options = {}) {
const currentPackagePath = path.resolve(options.packagePath || path.join(__dirname, '..'));
const projectPath = path.resolve(options.projectPath || process.cwd());
const globalExtensionsPath = path.resolve(
options.globalExtensionsPath || getGlobalExtensionsDirectory(options)
);
const globalPackagePath = path.join(globalExtensionsPath, PACKAGE_NAME);
const projectPackagePath = path.join(projectPath, 'extensions', PACKAGE_NAME);
const current = readPackageInstallation(currentPackagePath);
const global = readPackageInstallation(globalPackagePath);
const project = readPackageInstallation(projectPackagePath);
const currentVersion = normalizeVersion(options.currentVersion || current.version || '');
const targetVersion = normalizeVersion(options.availableVersion || currentVersion);
let scope = 'external';
if (isSameLocation(currentPackagePath, globalPackagePath)) {
scope = 'global';
} else if (isSameLocation(currentPackagePath, projectPackagePath)) {
scope = 'project';
}
const globalInvalid = global.exists && !global.valid;
const duplicateInstall = Boolean(
global.valid &&
project.valid &&
!isSameLocation(globalPackagePath, projectPackagePath)
);
let action = 'installed';
if (globalInvalid) {
action = 'blocked';
} else if (!global.valid) {
action = 'install';
} else if (targetVersion && compareVersions(targetVersion, global.version) > 0) {
action = 'update';
} else if (scope === 'global') {
action = 'active';
}
return {
packageName: PACKAGE_NAME,
editorVersion: String(options.editorVersion || '').trim().replace(/^v/i, ''),
scope,
currentPackagePath,
currentVersion,
targetVersion,
globalExtensionsPath,
globalPackagePath,
globalPathExists: global.exists,
globalInstalled: global.valid,
globalVersion: global.version,
globalInstallError: globalInvalid ? global.error : '',
projectPackagePath,
projectInstalled: project.valid,
projectVersion: project.version,
duplicateInstall,
action,
canInstallGlobally: action === 'install' || action === 'update',
automaticForNewProjects: global.valid,
};
}
function getMatchingEditorPackages(editor, filter = {}) {
if (!editor || !editor.Package || typeof editor.Package.getPackages !== 'function') {
return [];
}
try {
const packages = editor.Package.getPackages(filter);
return Array.isArray(packages) ? packages : [];
} catch (error) {
return [];
}
}
function findEditorPackageByPath(editor, packagePath) {
const resolvedPath = path.resolve(String(packagePath || ''));
return getMatchingEditorPackages(editor, { path: resolvedPath })
.find((item) => item && isSameLocation(item.path, resolvedPath)) || null;
}
async function activateGlobalExtension(options = {}) {
const editor = options.editor;
const globalPackagePath = path.resolve(String(options.globalPackagePath || ''));
const result = {
available: Boolean(editor && editor.Package),
scanned: false,
registered: false,
enabled: false,
activePath: '',
shadowedBy: '',
errors: [],
};
if (!result.available) {
result.errors.push('Cocos package APIs are unavailable; reopen the project to activate the global extension.');
return result;
}
if (editor.Message && typeof editor.Message.request === 'function') {
try {
await editor.Message.request('extension', 'scanning', 'global');
result.scanned = true;
} catch (error) {
result.errors.push(`Cocos global extension scan failed: ${error.message}`);
}
}
let packageInfo = findEditorPackageByPath(editor, globalPackagePath);
if (!packageInfo && typeof editor.Package.register === 'function') {
try {
await editor.Package.register(globalPackagePath);
packageInfo = findEditorPackageByPath(editor, globalPackagePath);
} catch (error) {
result.errors.push(`Cocos extension registration failed: ${error.message}`);
}
}
result.registered = Boolean(packageInfo);
const activePackageBeforeEnable = getMatchingEditorPackages(editor, { name: PACKAGE_NAME })
.find((item) => item && item.enable);
if (
activePackageBeforeEnable &&
activePackageBeforeEnable.path &&
!isSameLocation(activePackageBeforeEnable.path, globalPackagePath)
) {
result.activePath = path.resolve(activePackageBeforeEnable.path);
result.shadowedBy = result.activePath;
return result;
}
if (result.registered) {
try {
if (editor.Message && typeof editor.Message.request === 'function') {
await editor.Message.request(
'extension',
'enable',
globalPackagePath,
true,
{ addNotification: false, showInExtensionManager: false }
);
} else if (typeof editor.Package.enable === 'function') {
await editor.Package.enable(globalPackagePath);
}
} catch (error) {
result.errors.push(`Cocos extension enable failed: ${error.message}`);
}
}
packageInfo = findEditorPackageByPath(editor, globalPackagePath);
result.registered = Boolean(packageInfo);
result.enabled = Boolean(packageInfo && packageInfo.enable);
const activePackage = getMatchingEditorPackages(editor, { name: PACKAGE_NAME })
.find((item) => item && item.enable);
if (activePackage && activePackage.path) {
result.activePath = path.resolve(activePackage.path);
if (!isSameLocation(activePackage.path, globalPackagePath)) {
result.shadowedBy = result.activePath;
}
}
return result;
}
async function installGlobalExtension(options = {}) {
const state = getGlobalInstallationState(options);
if (state.globalPathExists && !state.globalInstalled) {
throw new Error(
`Global extension path is occupied by an invalid package: ${state.globalPackagePath}. ` +
`${state.globalInstallError || 'Remove or rename it before installing.'}`
);
}
const releaseInfo = options.releaseInfo || {};
const latestVersion = normalizeVersion(releaseInfo.latestVersion || releaseInfo.tagName || '');
if (!latestVersion) {
throw new Error('Latest release version is unknown.');
}
if (state.globalInstalled) {
const comparison = compareVersions(latestVersion, state.globalVersion);
if (comparison < 0 && !options.allowDowngrade) {
throw new Error(
`Refusing to replace newer global version ${state.globalVersion} with ${latestVersion}.`
);
}
if (comparison === 0 && !options.force) {
return {
ok: true,
installed: false,
alreadyInstalled: true,
installedVersion: state.globalVersion,
packagePath: state.globalPackagePath,
globalPackagePath: state.globalPackagePath,
restartRequired: false,
duplicateInstall: state.duplicateInstall,
projectPackagePath: state.projectPackagePath,
automaticForNewProjects: true,
};
}
}
const installer = options.installer || installLatestUpdate;
const result = await installer({
releaseInfo,
currentVersion: state.globalVersion || '0.0.0',
packagePath: state.globalPackagePath,
timeoutMs: options.timeoutMs,
maxDownloadBytes: options.maxDownloadBytes,
log: options.log,
force: Boolean(options.force || options.allowDowngrade),
});
const after = getGlobalInstallationState(options);
return {
...result,
globalPackagePath: after.globalPackagePath,
restartRequired: true,
duplicateInstall: after.duplicateInstall,
projectPackagePath: after.projectPackagePath,
automaticForNewProjects: after.automaticForNewProjects,
};
}
module.exports = {
PACKAGE_NAME,
activateGlobalExtension,
getGlobalExtensionsDirectory,
getGlobalInstallationState,
installGlobalExtension,
isSameLocation,
readPackageInstallation,
};
+71
View File
@@ -0,0 +1,71 @@
'use strict';
const DEFAULT_LANGUAGE = 'en';
const LANGUAGE_PREFERENCES = new Set(['auto', 'en', 'zh']);
const TRANSLATION_KEY = 'funplay-cocos-mcp.language_code';
function normalizeLanguagePreference(value) {
const normalized = String(value || '').trim().toLowerCase();
return LANGUAGE_PREFERENCES.has(normalized) ? normalized : 'auto';
}
function normalizeLocale(value) {
const normalized = String(value || '').trim().toLowerCase().replace(/_/g, '-');
return normalized === 'zh' || normalized.startsWith('zh-') ? 'zh' : DEFAULT_LANGUAGE;
}
function detectEditorLanguage(editor = global.Editor) {
if (editor && editor.I18n && typeof editor.I18n.t === 'function') {
try {
const translated = String(editor.I18n.t(TRANSLATION_KEY) || '').trim().toLowerCase();
if (translated === 'en' || translated === 'zh') {
return translated;
}
} catch (error) {
// Fall back to exposed locale properties and the host locale.
}
}
const candidates = [
editor && editor.I18n && editor.I18n.locale,
editor && editor.I18n && editor.I18n.language,
editor && editor.App && editor.App.language,
process.env.LC_ALL,
process.env.LC_MESSAGES,
process.env.LANG,
];
const explicit = candidates.find((value) => typeof value === 'string' && value.trim());
if (explicit) {
return normalizeLocale(explicit);
}
try {
return normalizeLocale(Intl.DateTimeFormat().resolvedOptions().locale);
} catch (error) {
return DEFAULT_LANGUAGE;
}
}
function resolveLanguage(preference, detectedLanguage) {
const normalized = normalizeLanguagePreference(preference);
return normalized === 'auto' ? normalizeLocale(detectedLanguage) : normalized;
}
function translate(dictionaries, language, key, replacements = {}) {
const dictionary = dictionaries[normalizeLocale(language)] || dictionaries[DEFAULT_LANGUAGE] || {};
const fallback = dictionaries[DEFAULT_LANGUAGE] || {};
const template = dictionary[key] !== undefined ? dictionary[key] : fallback[key];
const text = template === undefined ? key : String(template);
return text.replace(/\{([A-Za-z0-9_]+)\}/g, (match, name) => (
replacements[name] === undefined ? match : String(replacements[name])
));
}
module.exports = {
DEFAULT_LANGUAGE,
detectEditorLanguage,
normalizeLanguagePreference,
normalizeLocale,
resolveLanguage,
translate,
};
+289
View File
@@ -0,0 +1,289 @@
'use strict';
const crypto = require('crypto');
const { performance } = require('perf_hooks');
const electronTools = require('./electron-tools');
const { getCaptureWindow, resolveImagePoints, acquireInputWindow } = require('./visual-coordinates');
const { controlPreviewToolbar } = require('./preview-runtime');
const MAX_RECEIPTS = 32;
const MAX_SAMPLES = 64;
const jobs = new Map();
// Serialized into the exact captured BrowserWindow. A renderer animation frame
// is NOT evidence of the native Game View's engine Update or game acceptance.
function nextRendererFrame() {
return new Promise((resolve, reject) => {
if (typeof requestAnimationFrame !== 'function' || typeof cancelAnimationFrame !== 'function') {
reject(new Error('Renderer animation frames are unavailable.'));
return;
}
let id;
const timer = setTimeout(() => { cancelAnimationFrame(id); reject(new Error('Target renderer frame stalled.')); }, 1000);
id = requestAnimationFrame((timestamp) => {
clearTimeout(timer);
try {
resolve({ timestamp, epoch: performance.timeOrigin, focused: document.hasFocus(),
source: 'target-renderer-animation-frame' });
} catch (error) { reject(error); }
});
});
}
function fail(code, message) {
const error = new Error(`${code}: ${message}`);
error.code = code;
return error;
}
function numberOption(options, name, fallback, min, max) {
const value = options[name] === undefined ? fallback : options[name];
if (!Number.isFinite(value) || value < min || value > max) throw fail('INVALID_INPUT_TIMING', `${name} must be ${min}..${max}.`);
return value;
}
function ownerKey(options) {
if (!options.inputOwner || !options.projectPath || !options.originatingTool) throw fail('INPUT_CONTEXT_REQUIRED', 'Input owner, project and originating tool are required.');
return JSON.stringify([options.inputOwner, options.projectPath, options.originatingTool]);
}
function snapshot(job) {
return { jobId: job.id, requestKey: job.requestKey, status: job.status, phase: job.phase,
sent: job.status === 'completed', inputSent: job.status === 'completed' ? true : job.attempted ? null : false,
eventsSubmitted: job.events, releaseSubmitted: job.releaseSubmitted, cleanup: job.cleanup,
error: job.error ? { ...job.error } : null, windowId: job.window && job.window.id,
captureId: job.options.captureId, coordinateSpace: 'image-pixels',
durationMs: job.options.durationMs, pressHoldMs: job.options.pressHoldMs, endHoldMs: job.options.endHoldMs,
elapsedMs: Math.round((job.finishedAt || performance.now()) - job.createdAt),
observedRendererFrames: job.frameCount, samples: job.samples.map((item) => ({ ...item })),
samplesOmitted: Math.max(0, job.frameCount - job.samples.length),
frameEvidenceScope: 'target-renderer-animation-frame', nativeGameUpdateVerified: false, businessOutcomeVerified: false,
projectContext: job.options.projectContext ? { ...job.options.projectContext } : null, originatingTool: job.options.originatingTool,
};
}
async function bounded(job, operation) {
if (job.abort.signal.aborted) throw fail('INPUT_CANCELLED', 'Gesture cancelled.');
let timer;
let abort;
try {
return await Promise.race([
Promise.resolve().then(operation),
new Promise((resolve, reject) => {
abort = () => reject(fail('INPUT_CANCELLED', 'Gesture cancelled.'));
job.abort.signal.addEventListener('abort', abort, { once: true });
timer = setTimeout(() => reject(fail('INPUT_FRAME_TIMEOUT', 'Renderer or geometry observation timed out.')), Math.max(1, Math.min(1500, job.deadline - performance.now())));
}),
]);
} finally {
clearTimeout(timer);
if (abort) job.abort.signal.removeEventListener('abort', abort);
}
}
async function cleanup(job) {
if (job.pressed) {
try {
if (!job.window.isDestroyed || !job.window.isDestroyed()) {
job.emit({ type: 'mouseUp', ...job.lastPoint, button: job.options.button, clickCount: 1, modifiers: job.options.modifiers }, true);
job.events++;
job.releaseSubmitted = true;
}
job.pressed = false;
} catch (error) {
job.cleanup = 'failed';
return;
}
}
job.cleanup = 'complete';
if (job.releaseLock) { job.releaseLock(); job.releaseLock = null; }
}
async function run(job, nativeMouseEvent) {
const options = job.options;
const pixels = [{ x: options.startX, y: options.startY }, { x: options.endX, y: options.endY }];
job.emit = (event, held) => {
job.attempted = true;
job.window.webContents.sendInputEvent(nativeMouseEvent(job.window, event, held));
};
const submit = (type, point) => {
if (job.abort.signal.aborted) throw fail('INPUT_CANCELLED', 'Gesture cancelled.');
if (type === 'mouseDown') job.pressed = true; // May have arrived even if dispatch throws.
job.lastPoint = point;
job.emit({ type, ...point, button: options.button, clickCount: 1, modifiers: options.modifiers }, type !== 'mouseMove' || job.pressed);
job.events++;
if (type === 'mouseUp') { job.pressed = false; job.releaseSubmitted = true; }
};
const sample = async () => {
if (performance.now() > job.deadline) throw fail('INPUT_DEADLINE_EXCEEDED', 'Gesture deadline exceeded.');
const frame = await bounded(job, () => electronTools.executeJavaScript(job.window, `(${nextRendererFrame.toString()})()`));
// Creator's native Game View can own focus inside the captured window
// while its host document reports false. Require the OS window's focus
// for native input; web targets still require their document's focus too.
// After Up no further input is sent, so a focus handoff can be observed
// without turning an otherwise finished gesture into failed delivery.
const windowFocused = typeof job.window.isFocused === 'function'
? job.window.isFocused() === true : Boolean(frame && frame.focused === true);
const inputFocused = windowFocused && Boolean(frame && (frame.focused === true || job.gameView));
if (!frame || !Number.isFinite(frame.timestamp) || !Number.isFinite(frame.epoch)
|| (job.phase !== 'released' && !inputFocused)) {
throw fail('INPUT_FRAME_UNAVAILABLE', 'A focused target window with advancing renderer frames is required. No background/focus policy was changed.');
}
if (job.lastFrame && (frame.epoch !== job.lastFrame.epoch || frame.timestamp <= job.lastFrame.timestamp)) {
throw fail('INPUT_RENDERER_CHANGED', 'Renderer reloaded or its frame clock stopped advancing.');
}
await bounded(job, () => resolveImagePoints(options, pixels));
if (job.gameView) {
const preview = await bounded(job, () => controlPreviewToolbar({ action: 'state' }));
if (!preview.running || preview.paused || !preview.toolbarSynchronized) throw fail('INPUT_PREVIEW_INTERRUPTED', 'Game View stopped, paused or changed state.');
}
job.lastFrame = frame;
job.frameCount++;
const evidence = { phase: job.phase, rendererTime: frame.timestamp, focused: frame.focused === true, windowFocused,
elapsedMs: Math.round(performance.now() - job.createdAt), ...job.lastPoint };
if (job.samples.length >= MAX_SAMPLES) {
// Keep each phase's first/last witness even during long movements.
const index = job.samples.findIndex((item, i, all) => i > 0 && i < all.length - 1
&& item.phase === all[i - 1].phase && item.phase === all[i + 1].phase);
job.samples.splice(index < 0 ? 1 : index, 1);
}
job.samples.push(evidence);
return frame;
};
const hold = async (ms, frames = 2) => {
const began = performance.now();
let count = 0;
do { await sample(); count++; } while (count < frames || performance.now() - began < ms);
};
try {
job.window = getCaptureWindow(options);
job.releaseLock = acquireInputWindow(job.window);
await bounded(job, () => resolveImagePoints(options, pixels));
if (typeof job.window.focus === 'function') job.window.focus();
// A native Game View can own keyboard focus inside the same window.
// Focus the exact captured host once before input, never on later frames.
if (typeof job.window.webContents.focus === 'function') job.window.webContents.focus();
const resolved = await bounded(job, () => resolveImagePoints(options, pixels));
const [start, end] = resolved.points;
job.lastPoint = start;
const url = typeof job.window.webContents.getURL === 'function' ? job.window.webContents.getURL() : '';
job.gameView = resolved.panel === 'game' && /\/windows\/main\.html(?:[?#]|$)/i.test(url);
job.phase = 'preflight';
await sample(); // No input before frame, focus, geometry and preview checks pass.
submit('mouseMove', start);
submit('mouseDown', start);
job.phase = 'pressed';
await hold(options.pressHoldMs);
job.phase = 'moving';
const began = performance.now();
let fraction;
do {
await sample();
fraction = Math.min(1, (performance.now() - began) / options.durationMs);
submit('mouseMove', { x: Math.round(start.x + (end.x - start.x) * fraction), y: Math.round(start.y + (end.y - start.y) * fraction) });
} while (fraction < 1);
job.phase = 'target-hold';
await hold(options.endHoldMs);
submit('mouseUp', end);
job.phase = 'released';
await hold(0);
job.status = 'completed';
} catch (error) {
job.status = job.abort.signal.aborted ? 'cancelled' : 'failed';
job.error = { code: error.code || 'INPUT_OUTCOME_UNKNOWN', message: error.message };
} finally {
await cleanup(job);
if (job.cleanup === 'failed') {
job.status = 'failed';
job.error = { code: 'INPUT_CLEANUP_FAILED', message: 'Release could not be submitted. Cancel this job to retry cleanup; its window stays locked.' };
}
job.finishedAt = performance.now();
}
}
async function waitReceipt(job, waitMs) {
let timer;
try {
if (job.status === 'running' && waitMs > 0) await Promise.race([job.done, new Promise((resolve) => { timer = setTimeout(resolve, waitMs); })]);
return snapshot(job);
} finally { clearTimeout(timer); }
}
async function frameDrag(options, nativeMouseEvent) {
const owner = ownerKey(options);
const action = options.action || 'start';
if (!['start', 'status', 'cancel'].includes(action)) throw fail('INVALID_INPUT_ACTION', 'Use start, status or cancel.');
let job;
if (options.jobId !== undefined) job = jobs.get(options.jobId);
else if (options.requestKey) job = [...jobs.values()].find((item) => item.owner === owner && item.requestKey === options.requestKey);
if (job && job.owner !== owner) throw fail('INPUT_OWNER_MISMATCH', 'This receipt belongs to another project, Editor session or originating tool.');
if (action !== 'start') {
if (!job) throw fail('INPUT_RECEIPT_NOT_FOUND', 'Receipt expired or belongs to another input tool/project. Do not replay a lost gesture.');
if (action === 'cancel') {
job.abort.abort();
await job.done;
if (job.cleanup === 'failed') await cleanup(job);
if (job.cleanup === 'failed') {
const error = fail('INPUT_CLEANUP_FAILED', 'Release still could not be submitted. The owned window remains locked.');
error.inputOutcome = { ...snapshot(job), retrySafe: false };
throw error;
}
}
return snapshot(job);
}
if (options.jobId !== undefined) throw fail('INVALID_INPUT_ACTION', 'Use status or cancel with a jobId.');
if (options.coordinateSpace !== 'image-pixels' || typeof options.captureId !== 'string' || !options.captureId || options.captureId.length > 128) throw fail('INPUT_CAPTURE_REQUIRED', 'Frame-paced dragging requires a fresh calibrated screenshot and image-pixels coordinates. Legacy coordinates remain available with legacy timing.');
if (typeof options.requestKey !== 'string' || !/^[A-Za-z0-9_.:-]{1,128}$/.test(options.requestKey)) throw fail('INPUT_REQUEST_KEY_REQUIRED', 'Provide a unique requestKey (1..128 ASCII letters, digits, dot, colon, underscore or hyphen).');
if (options.steps !== undefined || options.stepDelayMs !== undefined) throw fail('INVALID_INPUT_TIMING', 'Frame-paced timing uses durationMs/pressHoldMs/endHoldMs, not legacy steps or stepDelayMs.');
const normalized = { projectPath: options.projectPath, inputOwner: options.inputOwner, originatingTool: options.originatingTool,
projectContext: options.projectContext || null,
captureId: options.captureId, coordinateSpace: 'image-pixels', windowId: options.windowId,
windowKind: options.windowKind, titleContains: options.titleContains, panel: options.panel,
startX: options.startX, startY: options.startY, endX: options.endX, endY: options.endY,
durationMs: numberOption(options, 'durationMs', 600, 50, 10000),
pressHoldMs: numberOption(options, 'pressHoldMs', 100, 0, 2000), endHoldMs: numberOption(options, 'endHoldMs', 100, 0, 2000),
button: options.button || 'left', modifiers: options.modifiers || [] };
if (!['left', 'right', 'middle'].includes(normalized.button) || !Array.isArray(normalized.modifiers)
|| normalized.modifiers.length > 16 || normalized.modifiers.some((item) => typeof item !== 'string' || item.length > 64)
|| ['panel', 'titleContains', 'windowKind'].some((key) => options[key] !== undefined && (typeof options[key] !== 'string' || options[key].length > 200))) throw fail('INVALID_INPUT_ARGUMENTS', 'Invalid mouse button, modifiers or target description.');
normalized.modifiers = normalized.modifiers.slice();
normalized.projectContext = normalized.projectContext ? { ...normalized.projectContext } : null;
if (![options.startX, options.startY, options.endX, options.endY].every(Number.isFinite)) throw fail('INVALID_INPUT_ARGUMENTS', 'Finite start/end image coordinates are required.');
const waitMs = numberOption(options, 'waitMs', 1200, 0, 15000);
const fingerprint = JSON.stringify([options.captureId, options.windowId, options.windowKind, options.titleContains, options.panel,
options.startX, options.startY, options.endX, options.endY, normalized.button, normalized.modifiers, normalized.durationMs, normalized.pressHoldMs, normalized.endHoldMs]);
if (job) {
if (job.fingerprint !== fingerprint) throw fail('INPUT_REQUEST_KEY_CONFLICT', 'The same requestKey cannot name different gesture arguments.');
} else {
if (jobs.size >= MAX_RECEIPTS) {
const retired = [...jobs.values()].find((item) => item.status !== 'running' && item.cleanup !== 'failed');
if (!retired) throw fail('INPUT_RECEIPTS_BUSY', 'All retained receipts are active or need cleanup.');
jobs.delete(retired.id);
}
const createdAt = performance.now();
job = { id: `input_${crypto.randomBytes(12).toString('hex')}`, owner, requestKey: options.requestKey, fingerprint,
options: normalized, status: 'running', phase: 'queued', createdAt,
deadline: createdAt + normalized.durationMs + normalized.pressHoldMs + normalized.endHoldMs + 5000,
events: 0, attempted: false, pressed: false, releaseSubmitted: false, cleanup: 'pending', samples: [], frameCount: 0,
abort: new AbortController() };
jobs.set(job.id, job);
job.done = run(job, nativeMouseEvent);
}
const receipt = await waitReceipt(job, waitMs);
if (receipt.status === 'failed' || receipt.status === 'cancelled') {
const error = new Error(receipt.error && receipt.error.message || 'Gesture cancelled.');
error.code = receipt.error && receipt.error.code || 'INPUT_CANCELLED';
error.inputOutcome = { ...receipt, retrySafe: !job.attempted };
throw error;
}
return receipt;
}
async function cancelFrameDrags(owner) {
const owned = [...jobs.values()].filter((job) => job.options.inputOwner === owner);
for (const job of owned) job.abort.abort();
await Promise.all(owned.map((job) => job.done));
if (owned.some((job) => job.cleanup === 'failed')) throw fail('INPUT_CLEANUP_FAILED', 'An owned input job still needs release cleanup.');
}
module.exports = { frameDrag, cancelFrameDrags, nextRendererFrame, MAX_RECEIPTS };
+287
View File
@@ -0,0 +1,287 @@
'use strict';
const electronTools = require('./electron-tools');
const { acquireInputWindow, getCaptureWindow, resolveImagePoints } = require('./visual-coordinates');
const { frameDrag, cancelFrameDrags: cancelFrameJobs } = require('./input-frames');
// Keep ownership while a release is uncertain. Stop/restart retries only the
// owned release; it must never replay the original press or gesture.
const mouseGestures = new Set();
function normalizeButton(button) {
const value = String(button || 'left').toLowerCase();
return ['left', 'right', 'middle'].includes(value) ? value : 'left';
}
function normalizeModifiers(modifiers) {
return Array.isArray(modifiers) ? modifiers.map((item) => String(item)) : [];
}
function nativeMouseEvent(window, event, held) {
// Blink does not infer the pressed-button flags from `button`. Keep keyboard
// modifiers, but derive mouse state from this gesture (including mouseUp's
// changed button so Creator receives the correct `which` value).
const modifiers = event.modifiers.filter((value) => !/^(left|middle|right)buttondown$/i.test(value));
if (held) modifiers.push(`${event.button}buttondown`);
const result = { ...event, modifiers };
// Creator's Game View filters/forwards movement using screen coordinates.
// Electron otherwise defaults these to (0, 0), dropping drag movement even
// when the local client coordinates and button flags are correct.
if (typeof window.getContentBounds === 'function') {
const bounds = window.getContentBounds();
if (!bounds || !Number.isFinite(bounds.x) || !Number.isFinite(bounds.y)) {
throw new Error('The target window has unavailable screen bounds.');
}
result.globalX = Math.round(bounds.x + event.x);
result.globalY = Math.round(bounds.y + event.y);
}
return result;
}
async function focusTarget(window, panel, x, y) {
if (typeof window.focus === 'function') {
window.focus();
}
if (panel) {
return await electronTools.getPanelPoint(window, panel, x, y);
}
return { x: Math.floor(x || 0), y: Math.floor(y || 0) };
}
async function resolvePoint(window, panel, x, y) {
if (panel) {
return await electronTools.getPanelPoint(window, panel, x, y);
}
return { x: Math.floor(x || 0), y: Math.floor(y || 0) };
}
function mouseGesture(window, options) {
const gesture = {
window, inputOwner: options.inputOwner || '', releaseLock: acquireInputWindow(window),
button: normalizeButton(options.button), modifiers: normalizeModifiers(options.modifiers),
attempted: false, pressed: false, eventsSubmitted: 0, releaseSubmitted: false, cancelled: false,
};
mouseGestures.add(gesture);
return gesture;
}
function submitMouse(gesture, event) {
if (gesture.cancelled) throw new Error('INPUT_CANCELLED: Gesture cancelled during MCP shutdown.');
const nativeEvent = nativeMouseEvent(gesture.window, event, event.type !== 'mouseMove' || gesture.pressed);
gesture.attempted = true;
gesture.lastPoint = { x: event.x, y: event.y };
// Dispatch can throw after delivery; ownership starts before the attempt.
if (event.type === 'mouseDown') gesture.pressed = true;
gesture.window.webContents.sendInputEvent(nativeEvent);
gesture.eventsSubmitted++;
if (event.type === 'mouseUp') {
gesture.pressed = false;
gesture.releaseSubmitted = true;
}
}
function unlockMouse(gesture) {
if (!gesture || gesture.pressed) return;
if (gesture.releaseLock) { gesture.releaseLock(); gesture.releaseLock = null; }
mouseGestures.delete(gesture);
}
function releaseMouse(gesture) {
if (gesture.pressed) {
const window = gesture.window;
if (!window.isDestroyed || !window.isDestroyed()) {
window.webContents.sendInputEvent(nativeMouseEvent(window, {
type: 'mouseUp', ...gesture.lastPoint, button: gesture.button, clickCount: 1, modifiers: gesture.modifiers,
}, true));
gesture.releaseSubmitted = true;
}
gesture.pressed = false;
}
unlockMouse(gesture);
}
function mouseFailure(error, gesture) {
if (gesture) {
try { releaseMouse(gesture); } catch (cleanupError) { /* Retain the window lock until owned cleanup succeeds. */ }
}
const attempted = Boolean(gesture && gesture.attempted);
const locked = Boolean(gesture && gesture.pressed);
error.inputOutcome = {
code: attempted ? 'INPUT_OUTCOME_UNKNOWN' : 'INPUT_NOT_SENT',
inputSent: attempted ? null : false,
eventsSubmitted: gesture ? gesture.eventsSubmitted : 0,
releaseSubmitted: Boolean(gesture && gesture.releaseSubmitted),
cleanup: locked ? 'failed' : 'complete', windowLocked: locked,
retrySafe: !attempted, businessOutcomeVerified: false,
};
if (locked) error.message += ' Release could not be submitted; the window stays locked. Stop/restart MCP to retry owned cleanup.';
return error;
}
async function sendMouseClick(options = {}) {
if (calibratedInput(options)) return await sendCalibratedMouse(options, false);
return await sendLegacyMouse(options, false);
}
async function sendMouseDrag(options = {}) {
if (options.timing === 'frame-paced' || options.action !== undefined) return await frameDrag(options, nativeMouseEvent);
if (options.timing !== undefined && options.timing !== 'legacy') throw new Error('timing must be legacy or frame-paced.');
if (calibratedInput(options)) return await sendCalibratedMouse(options, true);
return await sendLegacyMouse(options, true);
}
async function sendLegacyMouse(options, drag) {
let gesture;
try {
const window = electronTools.pickWindow(options);
gesture = mouseGesture(window, options);
const start = await focusTarget(window, options.panel, drag ? options.startX : options.x, drag ? options.startY : options.y);
const end = drag ? await resolvePoint(window, options.panel, options.endX ?? 0, options.endY ?? 0) : start;
const steps = Number.isFinite(options.steps) ? Math.max(1, Math.min(60, options.steps)) : 10;
const clickCount = drag ? 1 : Number.isFinite(options.clickCount) ? Math.max(1, options.clickCount) : 1;
const { button, modifiers } = gesture;
submitMouse(gesture, { type: 'mouseMove', ...start, button, modifiers });
submitMouse(gesture, { type: 'mouseDown', ...start, button, clickCount, modifiers });
if (drag) {
for (let step = 1; step <= steps; step += 1) {
const x = Math.round(start.x + ((end.x - start.x) * step) / steps);
const y = Math.round(start.y + ((end.y - start.y) * step) / steps);
submitMouse(gesture, { type: 'mouseMove', x, y, button, modifiers });
if (options.stepDelayMs) await electronTools.sleep(options.stepDelayMs);
}
}
submitMouse(gesture, { type: 'mouseUp', ...end, button, clickCount, modifiers });
return {
sent: true, type: drag ? 'mouse_drag' : 'mouse_click',
...(drag ? { from: start, to: end, steps } : { point: start, button, clickCount }),
windowTitle: typeof window.getTitle === 'function' ? window.getTitle() : '',
};
} catch (error) {
throw mouseFailure(error, gesture);
} finally { unlockMouse(gesture); }
}
async function sendKeyPress(options = {}) {
if (options.coordinateSpace === 'image-pixels' || options.captureId) throw new Error('Screenshot calibration applies to mouse input, not key input.');
const window = electronTools.pickWindow(options);
if (typeof window.focus === 'function') {
window.focus();
}
if (options.panel) {
await electronTools.getPanelPoint(window, options.panel, 0, 0);
}
const keyCode = String(options.keyCode || '').trim();
if (!keyCode) {
throw new Error('keyCode is required.');
}
const modifiers = normalizeModifiers(options.modifiers);
window.webContents.sendInputEvent({ type: 'keyDown', keyCode, modifiers });
if (options.text) {
window.webContents.sendInputEvent({ type: 'char', keyCode: String(options.text), modifiers });
}
window.webContents.sendInputEvent({ type: 'keyUp', keyCode, modifiers });
return {
sent: true,
type: 'key_press',
keyCode,
modifiers,
windowTitle: typeof window.getTitle === 'function' ? window.getTitle() : '',
};
}
async function sendKeyCombo(options = {}) {
const modifiers = normalizeModifiers(options.modifiers);
const keyCode = String(options.keyCode || '').trim();
if (!keyCode) {
throw new Error('keyCode is required.');
}
return await sendKeyPress({
...options,
keyCode,
modifiers,
});
}
function calibratedInput(options) {
const space = options.coordinateSpace || 'legacy';
if (!['legacy', 'image-pixels'].includes(space)) throw new Error('coordinateSpace must be legacy or image-pixels.');
if (space === 'legacy' && options.captureId) throw new Error('captureId requires coordinateSpace="image-pixels"; legacy offsets are not screenshot pixels.');
return space === 'image-pixels';
}
async function sendCalibratedMouse(options, drag) {
let window;
let gesture;
const button = normalizeButton(options.button);
const modifiers = normalizeModifiers(options.modifiers);
const submit = (event) => submitMouse(gesture, event);
try {
const steps = options.steps === undefined ? 10 : options.steps;
const delay = options.stepDelayMs === undefined ? 0 : options.stepDelayMs;
const clickCount = options.clickCount === undefined ? 1 : options.clickCount;
if (!Number.isInteger(steps) || steps < 1 || steps > 60 || !Number.isInteger(delay) || delay < 0 || delay > 100 ||
!Number.isInteger(clickCount) || clickCount < 1 || clickCount > 3) {
throw new Error('Calibrated input requires steps 1..60, stepDelayMs 0..100, and clickCount 1..3.');
}
const pixels = drag ? [{ x: options.startX, y: options.startY }, { x: options.endX, y: options.endY }]
: [{ x: options.x, y: options.y }];
window = getCaptureWindow(options);
gesture = mouseGesture(window, options);
await resolveImagePoints(options, pixels); // Validate before moving focus.
if (typeof window.focus === 'function') window.focus();
const resolved = await resolveImagePoints(options, pixels); // Focus can resize/change the viewport.
const start = resolved.points[0];
const end = drag ? resolved.points[1] : start;
submit({ type: 'mouseMove', ...start, button, modifiers });
submit({ type: 'mouseDown', ...start, button, clickCount, modifiers });
if (drag) {
for (let step = 1; step <= steps; step += 1) {
if (delay) {
await electronTools.sleep(delay);
await resolveImagePoints(options, pixels);
}
submit({ type: 'mouseMove', x: Math.round(start.x + (end.x - start.x) * step / steps),
y: Math.round(start.y + (end.y - start.y) * step / steps), button, modifiers });
}
}
submit({ type: 'mouseUp', ...end, button, clickCount, modifiers });
return {
sent: true, inputSent: true, outcome: 'events_submitted',
type: drag ? 'mouse_drag' : 'mouse_click', captureId: resolved.captureId, coordinateSpace: 'image-pixels',
...(drag ? { from: start, to: end, steps } : { point: start, clickCount }),
button, eventsSubmitted: gesture.eventsSubmitted,
windowId: window.id, windowTitle: typeof window.getTitle === 'function' ? window.getTitle() : '',
businessOutcomeVerified: false,
};
} catch (error) {
throw mouseFailure(error, gesture);
} finally {
unlockMouse(gesture);
}
}
async function cancelFrameDrags(owner) {
let failure;
try { await cancelFrameJobs(owner); } catch (error) { failure = error; }
for (const gesture of [...mouseGestures]) {
if (gesture.inputOwner !== owner) continue;
gesture.cancelled = true;
try { releaseMouse(gesture); } catch (error) {
failure = new Error('INPUT_CLEANUP_FAILED: Release could not be submitted. The owned window stays locked; retry MCP stop/restart to clean up.');
failure.code = 'INPUT_CLEANUP_FAILED';
}
}
if (failure) throw failure;
}
module.exports = {
listWindows: electronTools.listWindows,
sendKeyCombo,
sendKeyPress,
sendMouseClick,
sendMouseDrag,
cancelFrameDrags,
};
+59
View File
@@ -0,0 +1,59 @@
'use strict';
const { createActivityPreview, sanitizeActivityText } = require('./activity-preview');
class InteractionLog {
constructor(limit = 200) {
this.limit = limit;
this.entries = [];
}
add(toolName, status, summary, result, execution) {
const preview = createActivityPreview(result);
// Execution logs have their own bounded capture budget; do not run them
// through the result array preview limit or silently turn them into a count.
const script = execution && {
context: execution.context,
durationMs: execution.durationMs,
logs: execution.logs.map((entry) => ({ level: entry.level, message: entry.message })),
logsOmitted: execution.logsOmitted,
};
this.entries.unshift({
toolName,
status,
summary: sanitizeActivityText(summary || '', 500),
timestamp: new Date().toISOString(),
...(preview === undefined ? {} : { preview }),
...(script ? { execution: script } : {}),
});
if (this.entries.length > this.limit) {
this.entries.length = this.limit;
}
}
list(limit = 20) {
return this.entries.slice(0, Math.max(1, limit));
}
clear() {
const count = this.entries.length;
this.entries.length = 0;
return count;
}
summary(limit = 20) {
const items = this.list(limit);
if (!items.length) {
return 'No MCP interactions recorded yet.';
}
return items
.map((entry) => `[${entry.timestamp}] ${entry.status.toUpperCase()} ${entry.toolName}: ${entry.summary}`)
.join('\n');
}
}
module.exports = {
InteractionLog,
};
@@ -0,0 +1,114 @@
'use strict';
const path = require('path');
const { isPathInside } = require('./path-safety');
const DELETE_METHOD_PATTERN = /\bfs(?:\s*\.\s*promises)?\s*\.\s*(rm|rmdir|unlink|truncate|rmSync|rmdirSync|unlinkSync|truncateSync)\s*\(/;
const WRITE_STREAM_PATTERN = /\bfs\s*\.\s*(createWriteStream|openSync)\s*\(/;
const SHELL_PATTERN = /require\s*\(\s*['"]child_process['"]\s*\)|\bchild_process\s*\.|\b(exec|execFile|spawn|fork|execSync|execFileSync|spawnSync)\s*\(/;
const WRITE_METHOD_PATTERN = /\bfs(?:\s*\.\s*promises)?\s*\.\s*(writeFile|appendFile|copyFile|cp|rename|mkdir|writeFileSync|appendFileSync|copyFileSync|cpSync|renameSync|mkdirSync)\s*\(/;
const HOME_PATH_PATTERN = /(?:^~(?:\/|\\|$)|\$HOME|%USERPROFILE%|%HOMEPATH%)/i;
const TRAVERSAL_PATTERN = /(^|[\\/])\.\.([\\/]|$)/;
function extractStringLiterals(code) {
const literals = [];
const pattern = /(['"`])((?:\\[\s\S]|(?!\1)[\s\S])*?)\1/g;
let match;
while ((match = pattern.exec(String(code || '')))) {
literals.push(match[2]);
}
return literals;
}
function isAbsoluteLiteral(value) {
return path.isAbsolute(value)
|| path.win32.isAbsolute(value)
|| /^\\\\/.test(value);
}
function isAbsoluteLiteralInsideProject(projectPath, value) {
if (!projectPath) {
return false;
}
if (path.win32.isAbsolute(value)) {
const root = projectPath.replace(/\//g, '\\');
const relative = path.win32.relative(root, value);
return relative === '' || (relative && !relative.startsWith('..') && !path.win32.isAbsolute(relative));
}
if (path.isAbsolute(value)) {
return isPathInside(projectPath, path.resolve(value));
}
return false;
}
function inspectJavascriptSafety(code, options = {}) {
const source = String(code || '');
const projectPath = options.projectPath ? path.resolve(String(options.projectPath)) : '';
const violations = [];
if (DELETE_METHOD_PATTERN.test(source)) {
violations.push('direct fs delete/truncate calls are blocked by default');
}
if (WRITE_STREAM_PATTERN.test(source)) {
violations.push('raw writable file streams are blocked by default');
}
if (SHELL_PATTERN.test(source)) {
violations.push('child_process execution is blocked by default');
}
const hasFileMutation = DELETE_METHOD_PATTERN.test(source)
|| WRITE_METHOD_PATTERN.test(source)
|| WRITE_STREAM_PATTERN.test(source);
if (hasFileMutation && /\bos\s*\.\s*homedir\s*\(/.test(source)) {
violations.push('file mutations derived from os.homedir() are blocked by default');
}
if (hasFileMutation && /\bprocess\s*\.\s*env\s*\.\s*(HOME|USERPROFILE|HOMEPATH|APPDATA|LOCALAPPDATA|TMP|TEMP)\b/.test(source)) {
violations.push('file mutations derived from user/system environment paths are blocked by default');
}
for (const literal of extractStringLiterals(source)) {
if (HOME_PATH_PATTERN.test(literal)) {
violations.push(`user-home path literal is blocked: ${literal}`);
continue;
}
if (TRAVERSAL_PATTERN.test(literal)) {
violations.push(`path traversal literal is blocked: ${literal}`);
continue;
}
if (isAbsoluteLiteral(literal)) {
if (!isAbsoluteLiteralInsideProject(projectPath, literal)) {
violations.push(`absolute path outside the Cocos project is blocked: ${literal}`);
}
}
}
return {
ok: violations.length === 0,
violations: Array.from(new Set(violations)),
};
}
function assertJavascriptSafety(code, options = {}) {
const result = inspectJavascriptSafety(code, options);
if (result.ok) {
return result;
}
throw new Error(
'JavaScript safety checks blocked this code: ' +
`${result.violations.join('; ')}. ` +
'Use project-relative helper/file tools, or pass safety_checks=false only after reviewing the risk.'
);
}
module.exports = {
assertJavascriptSafety,
inspectJavascriptSafety,
};
+148
View File
@@ -0,0 +1,148 @@
'use strict';
const { isDeepStrictEqual } = require('util');
// Keep source ranges so config edits do not discard comments or reformat
// unrelated settings. No runtime dependency is needed in the Cocos ZIP.
function parseDocument(source) {
let offset = source.charCodeAt(0) === 0xFEFF ? 1 : 0;
const fail = (message) => { throw new SyntaxError(`Invalid JSONC at offset ${offset}: ${message}. File was left unchanged.`); };
function trivia() {
while (offset < source.length) {
if (/[ \t\r\n]/.test(source[offset])) { offset += 1; continue; }
if (source.startsWith('//', offset)) {
offset += 2;
while (offset < source.length && !/[\r\n]/.test(source[offset])) offset += 1;
} else if (source.startsWith('/*', offset)) {
const end = source.indexOf('*/', offset + 2);
if (end < 0) fail('unterminated comment');
offset = end + 2;
} else break;
}
}
function string() {
const start = offset++;
while (offset < source.length) {
const character = source[offset++];
if (character === '"') {
try { return { start, end: offset, value: JSON.parse(source.slice(start, offset)) }; }
catch (error) { fail('invalid string'); }
}
if (character === '\\') offset += 1;
}
fail('unterminated string');
}
function value(depth = 0) {
if (depth > 128) fail('configuration nesting is too deep');
trivia();
const start = offset;
const character = source[offset];
if (character === '"') return string();
if (character !== '{' && character !== '[') {
const literal = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(source.slice(offset));
if (!literal) fail('expected a JSON value');
offset += literal[0].length;
return { start, end: offset, value: JSON.parse(literal[0]) };
}
const object = character === '{';
const closing = object ? '}' : ']';
const result = object ? {} : [];
const properties = [];
offset += 1;
trivia();
while (source[offset] !== closing) {
let key;
if (object) {
if (source[offset] !== '"') fail('expected an object key');
key = string();
if (Object.prototype.hasOwnProperty.call(result, key.value)) fail('duplicate object key');
trivia();
if (source[offset++] !== ':') fail('expected a colon');
}
const child = value(depth + 1);
const property = object ? { key: key.value, start: key.start, node: child, comma: null } : null;
if (object) {
// Treat __proto__ like a normal JSON key, never as a prototype setter.
Object.defineProperty(result, key.value, { value: child.value, enumerable: true, writable: true, configurable: true });
properties.push(property);
} else result.push(child.value);
trivia();
if (source[offset] === closing) break;
if (source[offset] !== ',') fail('expected a comma or closing delimiter');
if (property) property.comma = offset;
offset += 1;
trivia(); // A single trailing comma is allowed, but not holes or doubled commas.
}
offset += 1;
return { start, end: offset, value: result, properties: object ? properties : undefined };
}
trivia();
if (offset === source.length) return null;
const root = value();
trivia();
if (offset !== source.length) fail('unexpected content after the root value');
return root;
}
function parseJsonc(source) {
const document = parseDocument(source);
return document ? document.value : {};
}
function updateJsonc(source, desired) {
const root = parseDocument(source);
const newline = source.includes('\r\n') ? '\r\n' : '\n';
const indent = (/\r?\n([ \t]+)"/.exec(source) || [null, ' '])[1];
const lineIndent = (position) => /^[ \t]*/.exec(source.slice(source.lastIndexOf('\n', position - 1) + 1))[0];
const serialize = (value, prefix) => JSON.stringify(value, null, indent).replace(/\n/g, newline + prefix);
if (!root) {
const separator = source && !/[\r\n]$/.test(source) ? newline : '';
return source + separator + serialize(desired, '') + newline;
}
const edits = [];
const edit = (start, end, text) => edits.push({ start, end, text, order: edits.length });
function visit(node, next) {
if (isDeepStrictEqual(node.value, next)) return;
if (!node.properties || !next || typeof next !== 'object' || Array.isArray(next)) {
edit(node.start, node.end, serialize(next, lineIndent(node.start)));
return;
}
const retained = [];
const existing = new Set();
for (const property of node.properties) {
existing.add(property.key);
if (Object.prototype.hasOwnProperty.call(next, property.key)) {
retained.push(property);
visit(property.node, next[property.key]);
} else {
edit(property.start, property.node.end, '');
// Leave surrounding comments intact. A previous separator may become
// a valid trailing comma when removing the final property.
if (property.comma !== null) edit(property.comma, property.comma + 1, '');
}
}
const added = Object.keys(next).filter((key) => !existing.has(key));
if (!added.length) return;
const last = retained[retained.length - 1];
if (last && last.comma === null) edit(last.node.end, last.node.end, ',');
const base = lineIndent(node.start);
const prefix = base + indent;
const closing = node.end - 1;
const closingLine = source.lastIndexOf('\n', closing - 1) + 1;
const onOwnLine = /^[ \t]*$/.test(source.slice(closingLine, closing));
const trailingComma = node.properties.length && node.properties[node.properties.length - 1].comma !== null;
const fields = added.map((key) => `${prefix}${JSON.stringify(key)}: ${serialize(next[key], prefix)}`).join(',' + newline);
const text = (onOwnLine ? '' : newline) + fields + (trailingComma ? ',' : '') + newline + (onOwnLine ? '' : base);
edit(onOwnLine ? closingLine : closing, onOwnLine ? closingLine : closing, text);
}
visit(root, desired);
let result = source;
for (const change of edits.sort((a, b) => b.start - a.start || b.end - a.end || b.order - a.order)) {
result = result.slice(0, change.start) + change.text + result.slice(change.end);
}
// Fail closed before the caller performs its atomic write.
if (!isDeepStrictEqual(parseJsonc(result), desired)) throw new Error('JSONC edit could not be verified; the file was left unchanged.');
return result;
}
module.exports = { parseJsonc, updateJsonc };
+206
View File
@@ -0,0 +1,206 @@
'use strict';
const fs = require('fs');
const path = require('path');
const { resolveProjectPath } = require('./path-safety');
const DEFAULT_LOG_DIRS = [
'temp/logs',
'temp',
'logs',
'local/logs',
'local',
];
const LOG_EXTENSIONS = new Set(['.log', '.txt']);
const MAX_READ_BYTES = 2 * 1024 * 1024;
function normalizeLimit(value, fallback, min, max) {
const number = Number(value);
if (!Number.isFinite(number)) {
return fallback;
}
return Math.max(min, Math.min(max, Math.floor(number)));
}
function shouldSkipDirectory(name) {
return name === '.git' || name === 'node_modules' || name === 'library';
}
function isLogFile(fileName) {
return LOG_EXTENSIONS.has(path.extname(fileName).toLowerCase());
}
function safeStat(filePath) {
try {
return fs.statSync(filePath);
} catch (error) {
return null;
}
}
function collectLogFiles(rootDir, maxDepth, limit) {
const files = [];
const stack = [{ dir: rootDir, depth: 0 }];
while (stack.length && files.length < limit) {
const current = stack.pop();
let entries;
try {
entries = fs.readdirSync(current.dir, { withFileTypes: true });
} catch (error) {
continue;
}
for (const entry of entries) {
const fullPath = path.join(current.dir, entry.name);
if (entry.isDirectory()) {
if (current.depth < maxDepth && !shouldSkipDirectory(entry.name)) {
stack.push({ dir: fullPath, depth: current.depth + 1 });
}
continue;
}
if (!entry.isFile() || !isLogFile(entry.name)) {
continue;
}
const stat = safeStat(fullPath);
if (stat) {
files.push({ fullPath, size: stat.size, mtimeMs: stat.mtimeMs });
}
if (files.length >= limit) {
break;
}
}
}
return files;
}
function findProjectLogFiles(projectPath, options = {}) {
const limit = normalizeLimit(options.limit, 20, 1, 200);
const maxDepth = normalizeLimit(options.maxDepth, 2, 0, 5);
const directories = options.directory
? [options.directory]
: DEFAULT_LOG_DIRS;
const seen = new Set();
const files = [];
for (const directory of directories) {
let rootDir;
try {
rootDir = resolveProjectPath(projectPath, directory);
} catch (error) {
continue;
}
if (!fs.existsSync(rootDir) || !fs.statSync(rootDir).isDirectory()) {
continue;
}
for (const file of collectLogFiles(rootDir, maxDepth, limit)) {
if (seen.has(file.fullPath)) {
continue;
}
seen.add(file.fullPath);
files.push(file);
if (files.length >= limit) {
break;
}
}
if (files.length >= limit) {
break;
}
}
return files
.sort((left, right) => right.mtimeMs - left.mtimeMs)
.slice(0, limit);
}
function readTail(filePath, maxLines = 80) {
const stat = safeStat(filePath);
if (!stat) {
return '';
}
const size = Math.min(stat.size, MAX_READ_BYTES);
const buffer = Buffer.alloc(size);
const fd = fs.openSync(filePath, 'r');
try {
fs.readSync(fd, buffer, 0, size, stat.size - size);
} finally {
fs.closeSync(fd);
}
return buffer
.toString('utf8')
.replace(/\s+$/g, '')
.split(/\r?\n/)
.slice(-normalizeLimit(maxLines, 80, 1, 1000))
.join('\n')
.trim();
}
function getRecentProjectLogs(projectPath, options = {}) {
const maxLines = normalizeLimit(options.lines, 80, 1, 1000);
return findProjectLogFiles(projectPath, options).map((file) => ({
path: path.relative(projectPath, file.fullPath).replace(/\\/g, '/'),
size: file.size,
mtime: new Date(file.mtimeMs).toISOString(),
text: readTail(file.fullPath, maxLines),
}));
}
function searchProjectLogs(projectPath, options = {}) {
const query = String(options.query || '').trim();
if (!query) {
throw new Error('query is required.');
}
const limit = normalizeLimit(options.limit, 50, 1, 500);
const flags = options.caseSensitive ? '' : 'i';
const pattern = options.regex ? new RegExp(query, flags) : null;
const lowerQuery = query.toLowerCase();
const results = [];
for (const file of findProjectLogFiles(projectPath, { ...options, limit: normalizeLimit(options.fileLimit, 40, 1, 200) })) {
const text = readTail(file.fullPath, normalizeLimit(options.linesPerFile, 2000, 1, 10000));
const lines = text.split(/\r?\n/);
for (let index = 0; index < lines.length; index += 1) {
const line = lines[index];
const matched = pattern
? pattern.test(line)
: (options.caseSensitive ? line.includes(query) : line.toLowerCase().includes(lowerQuery));
if (!matched) {
continue;
}
results.push({
path: path.relative(projectPath, file.fullPath).replace(/\\/g, '/'),
line: index + 1,
text: line,
});
if (results.length >= limit) {
return { query, count: results.length, matches: results };
}
}
}
return { query, count: results.length, matches: results };
}
function clearProjectLogFiles(projectPath, options = {}) {
const cleared = [];
for (const file of findProjectLogFiles(projectPath, options)) {
fs.truncateSync(file.fullPath, 0);
cleared.push(path.relative(projectPath, file.fullPath).replace(/\\/g, '/'));
}
return cleared;
}
module.exports = {
findProjectLogFiles,
getRecentProjectLogs,
searchProjectLogs,
clearProjectLogFiles,
};
+57
View File
@@ -0,0 +1,57 @@
'use strict';
const path = require('path');
const fs = require('fs');
function normalizeRoot(projectPath) {
return path.resolve(String(projectPath || process.cwd()));
}
function isPathInside(rootPath, targetPath) {
const root = normalizeRoot(rootPath);
const target = path.resolve(String(targetPath || ''));
const relative = path.relative(root, target);
return relative === '' || (relative && !relative.startsWith('..') && !path.isAbsolute(relative));
}
function resolveProjectPath(projectPath, rawPath) {
if (!rawPath || typeof rawPath !== 'string') {
throw new Error('path is required.');
}
const root = normalizeRoot(projectPath);
const targetPath = path.isAbsolute(rawPath)
? path.resolve(rawPath)
: path.resolve(root, rawPath);
if (!isPathInside(root, targetPath)) {
throw new Error(`Path is outside the Cocos project: ${rawPath}`);
}
return targetPath;
}
// For managed configuration/instruction files, lexical containment alone is not enough:
// a project-local directory may be a symlink to another project's or the user's files.
function resolveProjectFilePath(projectPath, rawPath) {
const resolved = resolveProjectPath(projectPath, rawPath);
const root = normalizeRoot(projectPath);
const realRoot = fs.existsSync(root) ? fs.realpathSync(root) : root;
let existing = resolved;
while (!fs.existsSync(existing)) {
try {
if (fs.lstatSync(existing).isSymbolicLink()) throw new Error(`Dangling symbolic link in project path: ${rawPath}`);
} catch (error) { if (error.code !== 'ENOENT') throw error; }
const parent = path.dirname(existing);
if (parent === existing) break;
existing = parent;
}
if (fs.existsSync(root) && !isPathInside(realRoot, fs.realpathSync(existing))) throw new Error(`Path resolves outside the Cocos project: ${rawPath}`);
return resolved;
}
module.exports = {
isPathInside,
resolveProjectPath,
resolveProjectFilePath,
};
+228
View File
@@ -0,0 +1,228 @@
'use strict';
const crypto = require('crypto');
const UI_2D_LAYER = 33554432;
function createPrefabFileId() {
return crypto.randomBytes(16).toString('base64').replace(/=+$/, '');
}
function normalizePrefabNodeLayers(root, layer = UI_2D_LAYER) {
if (!root || typeof root !== 'object') {
throw new Error('Prefab root node is required.');
}
if (!Number.isSafeInteger(layer) || layer < 0) {
throw new Error('Prefab node layer must be a non-negative integer.');
}
const visitedNodes = new Set();
let nodeCount = 0;
function visit(node) {
if (!node || typeof node !== 'object' || visitedNodes.has(node)) {
return;
}
visitedNodes.add(node);
node.layer = layer;
nodeCount += 1;
const children = Array.isArray(node.children) ? node.children : [];
for (const child of children) {
visit(child);
}
}
visit(root);
return { nodeCount, layer };
}
function attachPrefabMetadata(root, prefab, options = {}) {
if (!root || typeof root !== 'object') {
throw new Error('Prefab root node is required.');
}
if (!prefab || typeof prefab !== 'object') {
throw new Error('Prefab asset is required.');
}
const prefabUtils = options.prefabUtils;
const PrefabInfo = prefabUtils && prefabUtils.PrefabInfo;
const CompPrefabInfo = prefabUtils && prefabUtils.CompPrefabInfo;
if (typeof PrefabInfo !== 'function' || typeof CompPrefabInfo !== 'function') {
throw new Error('Cocos PrefabInfo constructors are unavailable.');
}
const generateFileId = typeof options.createFileId === 'function'
? options.createFileId
: createPrefabFileId;
const usedFileIds = new Set();
const visitedNodes = new Set();
let nodeCount = 0;
let componentCount = 0;
function nextFileId() {
for (let attempt = 0; attempt < 32; attempt += 1) {
const fileId = String(generateFileId() || '').trim();
if (fileId && !usedFileIds.has(fileId)) {
usedFileIds.add(fileId);
return fileId;
}
}
throw new Error('Unable to generate a unique prefab fileId.');
}
function visit(node) {
if (!node || typeof node !== 'object' || visitedNodes.has(node)) {
return;
}
visitedNodes.add(node);
const nodeInfo = new PrefabInfo();
nodeInfo.root = root;
nodeInfo.asset = prefab;
nodeInfo.fileId = nextFileId();
node._prefab = nodeInfo;
nodeCount += 1;
const components = Array.isArray(node.components) ? node.components : [];
for (const component of components) {
if (!component || typeof component !== 'object') {
continue;
}
const componentInfo = new CompPrefabInfo();
componentInfo.fileId = nextFileId();
component.__prefab = componentInfo;
componentCount += 1;
}
const children = Array.isArray(node.children) ? node.children : [];
for (const child of children) {
visit(child);
}
}
visit(root);
return {
nodeCount,
componentCount,
fileIdCount: usedFileIds.size,
};
}
function invalidMetadata(message) {
throw new Error(`Invalid serialized prefab metadata: ${message}`);
}
function referenceId(value, label) {
if (!value || typeof value !== 'object' || !Number.isInteger(value.__id__)) {
invalidMetadata(`${label} is not an object reference.`);
}
return value.__id__;
}
function referencedObject(objects, reference, label) {
const id = referenceId(reference, label);
if (id < 0 || id >= objects.length || !objects[id] || typeof objects[id] !== 'object') {
invalidMetadata(`${label} points to missing object ${id}.`);
}
return { id, value: objects[id] };
}
function assertFileId(info, label, fileIds) {
const fileId = String(info.fileId || '').trim();
if (!fileId) {
invalidMetadata(`${label} has an empty fileId.`);
}
if (fileIds.has(fileId)) {
invalidMetadata(`${label} reuses fileId '${fileId}'.`);
}
fileIds.add(fileId);
}
function assertSerializedPrefabMetadata(serialized, options = {}) {
let objects;
try {
objects = typeof serialized === 'string' ? JSON.parse(serialized) : serialized;
} catch (error) {
invalidMetadata(`content is not valid JSON: ${error.message}`);
}
if (!Array.isArray(objects)) {
invalidMetadata('root value must be an object array.');
}
const prefabIndex = objects.findIndex((value) => value && value.__type__ === 'cc.Prefab');
if (prefabIndex < 0) {
invalidMetadata('cc.Prefab object is missing.');
}
const prefab = objects[prefabIndex];
const rootRef = referencedObject(objects, prefab.data, 'cc.Prefab.data');
if (rootRef.value.__type__ !== 'cc.Node') {
invalidMetadata(`cc.Prefab.data points to ${rootRef.value.__type__ || 'an unknown type'}, not cc.Node.`);
}
const nodes = objects
.map((value, index) => ({ value, index }))
.filter(({ value }) => value && value.__type__ === 'cc.Node');
if (!nodes.length) {
invalidMetadata('cc.Node objects are missing.');
}
const fileIds = new Set();
let componentCount = 0;
for (const { value: node, index: nodeIndex } of nodes) {
if (options.expectedLayer !== undefined && node._layer !== options.expectedLayer) {
invalidMetadata(
`cc.Node at index ${nodeIndex}._layer is ${String(node._layer)}, expected ${String(options.expectedLayer)}.`
);
}
const nodeInfoRef = referencedObject(objects, node._prefab, `cc.Node at index ${nodeIndex}._prefab`);
const nodeInfo = nodeInfoRef.value;
if (nodeInfo.__type__ !== 'cc.PrefabInfo') {
invalidMetadata(`cc.Node at index ${nodeIndex}._prefab does not reference cc.PrefabInfo.`);
}
if (referenceId(nodeInfo.root, `cc.PrefabInfo at index ${nodeInfoRef.id}.root`) !== rootRef.id) {
invalidMetadata(`cc.PrefabInfo at index ${nodeInfoRef.id}.root does not reference the prefab root.`);
}
if (referenceId(nodeInfo.asset, `cc.PrefabInfo at index ${nodeInfoRef.id}.asset`) !== prefabIndex) {
invalidMetadata(`cc.PrefabInfo at index ${nodeInfoRef.id}.asset does not reference the prefab asset.`);
}
assertFileId(nodeInfo, `cc.PrefabInfo at index ${nodeInfoRef.id}`, fileIds);
const componentRefs = Array.isArray(node._components) ? node._components : [];
for (let componentOffset = 0; componentOffset < componentRefs.length; componentOffset += 1) {
const componentRef = referencedObject(
objects,
componentRefs[componentOffset],
`cc.Node at index ${nodeIndex}._components[${componentOffset}]`
);
const componentInfoRef = referencedObject(
objects,
componentRef.value.__prefab,
`component at index ${componentRef.id}.__prefab`
);
const componentInfo = componentInfoRef.value;
if (componentInfo.__type__ !== 'cc.CompPrefabInfo') {
invalidMetadata(`component at index ${componentRef.id}.__prefab does not reference cc.CompPrefabInfo.`);
}
assertFileId(componentInfo, `cc.CompPrefabInfo at index ${componentInfoRef.id}`, fileIds);
componentCount += 1;
}
}
return {
valid: true,
prefabIndex,
rootIndex: rootRef.id,
nodeCount: nodes.length,
componentCount,
fileIdCount: fileIds.size,
};
}
module.exports = {
UI_2D_LAYER,
assertSerializedPrefabMetadata,
attachPrefabMetadata,
createPrefabFileId,
normalizePrefabNodeLayers,
};
+376
View File
@@ -0,0 +1,376 @@
'use strict';
const fs = require('fs');
const path = require('path');
const { listAssets, queryAssetData, queryAssetInfo, queryAssetMeta } = require('./assets');
const { resolveProjectPath } = require('./path-safety');
function requestEditorMessage(channel, method, ...args) {
if (!global.Editor || !Editor.Message || typeof Editor.Message.request !== 'function') {
throw new Error('Editor.Message.request is unavailable in the Cocos extension host.');
}
return Editor.Message.request(channel, method, ...args);
}
function assetUrlToPath(projectPath, url) {
if (!url || !String(url).startsWith('db://assets/')) {
return '';
}
return path.join(projectPath, String(url).slice('db://'.length));
}
function assetFilePath(projectPath, info) {
const candidates = [
info && info.file,
info && info.path,
info && info.source,
info && info.url ? assetUrlToPath(projectPath, info.url) : '',
].filter(Boolean);
for (const candidate of candidates) {
const fullPath = path.isAbsolute(candidate)
? resolveProjectPath(projectPath, candidate)
: resolveProjectPath(projectPath, candidate);
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
return fullPath;
}
}
return '';
}
function normalizePrefabTarget(projectPath, target) {
const raw = String(target || '').trim().replace(/\\/g, '/');
if (!raw) {
throw new Error('target is required.');
}
let relative = raw;
if (relative.startsWith('db://assets/')) {
relative = relative.slice('db://'.length);
} else if (relative.startsWith('/assets/')) {
relative = relative.slice(1);
} else if (!relative.startsWith('assets/')) {
relative = `assets/${relative}`;
}
if (!relative.endsWith('.prefab')) {
relative = `${relative}.prefab`;
}
const filePath = resolveProjectPath(projectPath, relative);
const assetsRoot = path.join(projectPath, 'assets');
const relativeToAssets = path.relative(assetsRoot, filePath);
if (relativeToAssets.startsWith('..') || path.isAbsolute(relativeToAssets)) {
throw new Error('target must be inside the Cocos assets directory.');
}
const projectRelative = path.relative(projectPath, filePath).replace(/\\/g, '/');
return {
filePath,
projectRelative,
dbUrl: `db://${projectRelative}`,
};
}
async function queryAssetInfoOptional(target) {
try {
return await queryAssetInfo(target);
} catch (error) {
return null;
}
}
async function savePrefabContent(projectPath, options = {}) {
const target = normalizePrefabTarget(projectPath, options.target);
const content = String(options.content || '');
if (!content) {
throw new Error('content is required.');
}
JSON.parse(content);
const exists = fs.existsSync(target.filePath);
if (exists && options.overwrite !== true) {
throw new Error(`Target prefab already exists: ${target.projectRelative}`);
}
fs.mkdirSync(path.dirname(target.filePath), { recursive: true });
let method = 'fs-write';
let result;
if (global.Editor && Editor.Message && typeof Editor.Message.request === 'function') {
if (exists && options.overwrite === true) {
try {
result = await requestEditorMessage('asset-db', 'save-asset', target.dbUrl, content);
method = 'asset-db:save-asset';
if (!fs.existsSync(target.filePath) || fs.readFileSync(target.filePath, 'utf8') !== content) {
fs.writeFileSync(target.filePath, content.endsWith('\n') ? content : `${content}\n`, 'utf8');
}
} catch (error) {
fs.writeFileSync(target.filePath, content.endsWith('\n') ? content : `${content}\n`, 'utf8');
result = { fallbackReason: error.message };
}
} else {
try {
result = await requestEditorMessage('asset-db', 'create-asset', target.dbUrl, content);
method = 'asset-db:create-asset';
} catch (error) {
if (fs.existsSync(target.filePath)) {
result = { fallbackReason: error.message, fileCreated: true };
} else {
throw error;
}
}
}
} else {
fs.writeFileSync(target.filePath, content.endsWith('\n') ? content : `${content}\n`, 'utf8');
}
const fileExists = fs.existsSync(target.filePath);
const info = await queryAssetInfoOptional(target.dbUrl);
if (!fileExists && !info) {
throw new Error(`Prefab was not created: ${target.projectRelative}`);
}
return {
created: !exists,
overwritten: exists && options.overwrite === true,
method,
result,
dbUrl: target.dbUrl,
path: target.projectRelative,
fileExists,
info,
};
}
function collectUuidReferences(value, refs = [], pointer = '') {
if (!value || typeof value !== 'object') {
return refs;
}
if (Array.isArray(value)) {
value.forEach((item, index) => collectUuidReferences(item, refs, `${pointer}/${index}`));
return refs;
}
for (const [key, child] of Object.entries(value)) {
const childPointer = `${pointer}/${key}`;
if (
typeof child === 'string' &&
(key.toLowerCase().includes('uuid') || key === '__uuid__' || key === 'assetUuid' || key === 'prefabUuid')
) {
refs.push({ uuid: child, path: childPointer, key });
} else {
collectUuidReferences(child, refs, childPointer);
}
}
return refs;
}
function getByJsonPath(target, jsonPath) {
const segments = String(jsonPath || '')
.replace(/^\//, '')
.split(/[/.]/)
.map((segment) => segment.trim())
.filter(Boolean);
let current = target;
for (const segment of segments) {
if (current == null) {
return undefined;
}
current = current[segment];
}
return current;
}
function setByJsonPath(target, jsonPath, value) {
const segments = String(jsonPath || '')
.replace(/^\//, '')
.split(/[/.]/)
.map((segment) => segment.trim())
.filter(Boolean);
if (!segments.length) {
throw new Error('jsonPath is required.');
}
let current = target;
for (let index = 0; index < segments.length - 1; index += 1) {
const segment = segments[index];
if (current[segment] == null || typeof current[segment] !== 'object') {
current[segment] = {};
}
current = current[segment];
}
current[segments[segments.length - 1]] = value;
}
async function inspectPrefab(projectPath, target) {
const info = await queryAssetInfo(target);
const meta = await queryAssetMeta(target).catch(() => null);
const data = await queryAssetData(target).catch(() => null);
const filePath = assetFilePath(projectPath, info);
const content = filePath ? fs.readFileSync(filePath, 'utf8') : '';
const parsed = content ? JSON.parse(content) : data;
const references = collectUuidReferences(parsed).slice(0, 500);
return {
info,
meta,
filePath: filePath ? path.relative(projectPath, filePath).replace(/\\/g, '/') : '',
referenceCount: references.length,
references,
};
}
async function validatePrefabReferences(projectPath, options = {}) {
const targets = options.target
? [options.target]
: (await listAssets({ pattern: options.pattern || 'db://assets/**', ccType: 'cc.Prefab' }))
.slice(0, Number.isFinite(options.limit) ? Math.max(1, Math.min(200, options.limit)) : 50)
.map((asset) => asset.uuid || asset.url)
.filter(Boolean);
const prefabs = [];
for (const target of targets) {
const prefab = await inspectPrefab(projectPath, target);
const checked = [];
const missing = [];
for (const ref of prefab.references) {
try {
const info = await queryAssetInfo(ref.uuid);
checked.push({ ...ref, exists: true, asset: { uuid: info.uuid, url: info.url, type: info.type } });
} catch (error) {
missing.push({ ...ref, exists: false, error: error.message });
}
}
prefabs.push({
target,
filePath: prefab.filePath,
referenceCount: prefab.referenceCount,
checkedCount: checked.length + missing.length,
missingCount: missing.length,
missing,
});
}
const missingCount = prefabs.reduce((sum, prefab) => sum + prefab.missingCount, 0);
return {
ok: missingCount === 0,
prefabCount: prefabs.length,
missingCount,
prefabs,
};
}
async function duplicatePrefab(projectPath, options = {}) {
const source = String(options.source || '').trim();
const target = String(options.target || '').trim();
if (!source || !target) {
throw new Error('source and target are required.');
}
const info = await queryAssetInfo(source);
const sourcePath = assetFilePath(projectPath, info);
if (!sourcePath) {
throw new Error(`Prefab source file was not found: ${source}`);
}
const targetPath = resolveProjectPath(projectPath, target.endsWith('.prefab') ? target : `${target}.prefab`);
const assetsRoot = path.join(projectPath, 'assets');
const relativeToAssets = path.relative(assetsRoot, targetPath);
if (relativeToAssets.startsWith('..') || path.isAbsolute(relativeToAssets)) {
throw new Error('target must be inside the Cocos assets directory.');
}
if (fs.existsSync(targetPath) && options.overwrite !== true) {
throw new Error(`Target prefab already exists: ${target}`);
}
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
fs.copyFileSync(sourcePath, targetPath);
return {
duplicated: true,
source: path.relative(projectPath, sourcePath).replace(/\\/g, '/'),
target: path.relative(projectPath, targetPath).replace(/\\/g, '/'),
};
}
async function editPrefabJson(projectPath, options = {}) {
const target = String(options.target || '').trim();
if (!target) {
throw new Error('target is required.');
}
const info = await queryAssetInfo(target);
const filePath = assetFilePath(projectPath, info);
if (!filePath) {
throw new Error(`Prefab file was not found: ${target}`);
}
const original = fs.readFileSync(filePath, 'utf8');
let updated = original;
if (options.search !== undefined) {
const search = String(options.search);
if (!search) {
throw new Error('search must not be empty.');
}
if (!original.includes(search)) {
throw new Error('search text was not found in prefab file.');
}
updated = options.replaceAll
? original.split(search).join(String(options.replace || ''))
: original.replace(search, String(options.replace || ''));
} else {
const json = JSON.parse(original);
const value = JSON.parse(String(options.valueJson || 'null'));
setByJsonPath(json, options.jsonPath, value);
updated = JSON.stringify(json, null, 2) + '\n';
}
JSON.parse(updated);
if (options.createBackup) {
fs.writeFileSync(`${filePath}.bak`, original, 'utf8');
}
fs.writeFileSync(filePath, updated, 'utf8');
return {
edited: true,
path: path.relative(projectPath, filePath).replace(/\\/g, '/'),
oldValue: options.jsonPath ? getByJsonPath(JSON.parse(original), options.jsonPath) : undefined,
validation: await validatePrefabReferences(projectPath, { target }),
};
}
async function applyPrefabInstance(nodeUuid) {
const uuid = String(nodeUuid || '').trim();
if (!uuid) {
throw new Error('node uuid is required.');
}
const result = await requestEditorMessage('scene', 'apply-prefab', uuid);
return { applied: true, uuid, result };
}
async function revertPrefabInstance(nodeUuid) {
const uuid = String(nodeUuid || '').trim();
if (!uuid) {
throw new Error('node uuid is required.');
}
const candidates = ['revert-prefab', 'restore-prefab'];
let lastError = null;
for (const method of candidates) {
try {
const result = await requestEditorMessage('scene', method, uuid);
return { reverted: true, uuid, method, result };
} catch (error) {
lastError = error;
}
}
throw lastError || new Error('No prefab revert editor message was available.');
}
module.exports = {
applyPrefabInstance,
duplicatePrefab,
editPrefabJson,
inspectPrefab,
normalizePrefabTarget,
revertPrefabInstance,
savePrefabContent,
validatePrefabReferences,
};
+133
View File
@@ -0,0 +1,133 @@
'use strict';
const electronTools = require('./electron-tools');
// This function is serialized into Creator's main renderer. Keep it self-contained.
async function previewToolbarCommand(command) {
const toolbar = document.querySelector('#toolbar');
const panels = toolbar ? Array.from(toolbar.querySelectorAll('ui-panel')) : [];
const candidates = panels.filter((panel) => /\/builtin\/preview\/static\/toolbar\/middle\.js$/.test(
String(panel.getAttribute('src') || '').replace(/\\/g, '/')
));
const panel = candidates.length === 1 ? candidates[0] : null;
const root = panel && (panel.shadowRoot || panel);
const element = root && root.querySelector('.preview-info-wrap');
const vm = element && element.__vue__;
if (!vm || !vm.gameView || typeof vm.gameView.isPlay !== 'boolean'
|| typeof vm.gameView.isPaused !== 'boolean'
|| !['play', 'changePlatform', 'gameViewPause'].every((key) => typeof vm[key] === 'function')) {
throw new Error('Compatible Cocos Creator preview toolbar is unavailable. Open the main editor window and retry; Game View cannot be controlled safely without its toolbar.');
}
if (!['state', 'start', 'set-mode', 'pause', 'resume'].includes(command.action)
|| (command.action === 'set-mode' && !['browser', 'gameView', 'simulator'].includes(command.mode))) {
throw new Error('Unsupported preview toolbar command.');
}
const lock = Symbol.for('funplay-cocos-mcp.preview-operation');
const busy = () => Boolean(vm[lock] || vm.isPlaying || vm.isLoading || vm.gameView.isStep);
const readPreview = async () => {
// Creator 3.8 returns undefined/null (depending on IPC context) when there
// is no preview, otherwise the PreviewPlay manager's boolean pause state
// (not the edit-scene director).
const paused = await Editor.Message.request('scene', 'editor-preview-call-method', 'isPause');
if (paused != null && typeof paused !== 'boolean') {
throw new Error('Cocos Creator returned an unsupported Game View preview state.');
}
return { running: typeof paused === 'boolean', paused: paused === true };
};
const snapshot = (state) => ({
scope: 'gameView',
source: 'scene.editor-preview-call-method',
mode: vm.currPlatform,
...state,
busy: busy(),
toolbarSynchronized: vm.gameView.isPlay === state.running
&& vm.gameView.isPaused === state.paused
&& (!state.running || vm.currPlatform === 'gameView'),
});
if (command.action === 'state') return snapshot(await readPreview());
if (busy()) throw new Error('Cocos Creator preview toolbar is busy. Wait for the current preview operation to finish and retry.');
vm[lock] = true;
try {
const previousMode = vm.currPlatform;
const before = await readPreview();
if (['pause', 'resume'].includes(command.action) && !before.running) {
throw new Error('Game View preview is not running. Start run_project_preview with mode="gameView" first; browser and simulator previews are not controlled by this tool.');
}
const changeMode = async (mode) => {
await vm.changePlatform(mode);
// Creator's changePlatform starts this write without awaiting it. Wait
// for persistence as well so subsequent MCP calls see the same mode.
await Editor.Profile.setConfig('preview', 'preview.current.platform', mode, 'local');
if (vm.currPlatform !== mode) throw new Error(`Cocos Creator did not select preview mode '${mode}'.`);
};
// Repair previews started by older MCP versions/direct scene messages.
// Normal starts and pause changes below always use the native toolbar.
if (before.running && vm.currPlatform !== 'gameView') await changeMode('gameView');
vm.gameView.isPlay = before.running;
vm.gameView.isPaused = before.paused;
if (command.action === 'set-mode') {
if (before.running && command.mode !== 'gameView') {
await vm.play();
if ((await readPreview()).running) {
throw new Error('Cocos Creator rejected the Game View stop request; preview mode was not changed.');
}
vm.gameView.isPlay = false;
vm.gameView.isPaused = false;
}
await changeMode(command.mode);
} else if (command.action === 'start') {
if (vm.currPlatform !== 'gameView') await changeMode('gameView');
// play() is a toggle; never invoke it for an already running preview.
if (!before.running) await vm.play();
} else {
const paused = command.action === 'pause';
// gameViewPause() toggles the preview manager and its toolbar together.
if (before.paused !== paused) await vm.gameViewPause();
}
const after = await readPreview();
if (command.action === 'start' && !after.running) {
throw new Error('Cocos Creator rejected the Game View start request.');
}
if (['pause', 'resume'].includes(command.action)
&& (!after.running || after.paused !== (command.action === 'pause'))) {
throw new Error(`Cocos Creator did not ${command.action} the Game View preview.`);
}
const result = snapshot(after);
if (!result.toolbarSynchronized) {
throw new Error('Game View preview and toolbar state changed during the operation. Query get_runtime_state and retry.');
}
return {
...result,
busy: Boolean(vm.isPlaying || vm.isLoading || vm.gameView.isStep),
changed: previousMode !== vm.currPlatform || before.running !== after.running || before.paused !== after.paused,
};
} finally {
delete vm[lock];
}
}
function buildPreviewToolbarScript(command) {
return `(${previewToolbarCommand.toString()})(${JSON.stringify(command)})`;
}
async function controlPreviewToolbar(command) {
// Never fall back to the focused window: it may be a preview, inspector,
// another panel, or DevTools rather than the project's main toolbar.
const windows = electronTools.getAllWindows().filter((window) => {
const url = window.webContents && typeof window.webContents.getURL === 'function'
? window.webContents.getURL() : '';
return /^file:\/\/.*\/windows\/main\.html(?:[?#]|$)/i.test(url);
});
if (windows.length !== 1) {
throw new Error('A unique Cocos Creator main editor window is required to control Game View preview.');
}
return await electronTools.executeJavaScript(windows[0], buildPreviewToolbarScript(command));
}
module.exports = { buildPreviewToolbarScript, controlPreviewToolbar };
+66
View File
@@ -0,0 +1,66 @@
'use strict';
const path = require('path');
const { getProjectIdentity } = require('./config');
const CONTEXT_META_KEY = 'io.funplay.cocos/context';
function projectEndpoint(projectIdentity) {
return projectIdentity ? `/mcp/project/${encodeURIComponent(projectIdentity)}/` : '/';
}
function serverUrl(config, port = config.port, identity) {
const host = String(config.host || '127.0.0.1');
const authority = host.includes(':') && !host.startsWith('[') ? `[${host}]` : host;
const project = identity === undefined ? (config.projectPath ? getProjectIdentity(config.projectPath) : '') : identity;
return `http://${authority}:${port}${projectEndpoint(project)}`;
}
function projectContext({ projectIdentity, projectPath, instanceId }) {
return {
project_id: projectIdentity || '',
project_path: projectPath ? path.resolve(projectPath) : '',
instance_id: instanceId,
expected_context: `${projectIdentity || ''}:${instanceId}`,
};
}
function requestRoute(pathname, identity) {
const legacy = { '/': 'rpc', '/mcp': 'rpc', '/mcp/': 'rpc', '/health': 'health', '/tools': 'tools' };
if (Object.prototype.hasOwnProperty.call(legacy, pathname)) return { kind: legacy[pathname], scoped: false };
const match = /^\/mcp\/project\/([^/]+)(?:\/(health|tools))?\/?$/.exec(pathname);
if (!match) return { error: 'ENDPOINT_NOT_FOUND', status: 404 };
let project;
try { project = decodeURIComponent(match[1]); } catch (error) { return { error: 'ENDPOINT_NOT_FOUND', status: 404 }; }
if (!identity || project !== identity) return { error: 'PROJECT_CONTEXT_MISMATCH', status: 409 };
return { kind: match[2] || 'rpc', scoped: true, project };
}
function expectedContext(params = {}) {
const fromMeta = params._meta && params._meta.expected_context;
const fromArgs = params.arguments && params.arguments.expected_context;
if (fromMeta !== undefined && fromArgs !== undefined && fromMeta !== fromArgs) {
return { error: 'PROJECT_CONTEXT_MISMATCH' };
}
const token = fromMeta === undefined ? fromArgs : fromMeta;
if (token !== undefined && (typeof token !== 'string' || !token)) return { error: 'PROJECT_CONTEXT_MISMATCH' };
return { token };
}
function contextError(context, params, { scoped = false, readOnly = false } = {}) {
const expected = expectedContext(params);
if (expected.error) return expected.error;
if (expected.token !== undefined && expected.token !== context.expected_context) {
return expected.token.split(':')[0] === context.project_id ? 'EDITOR_INSTANCE_CHANGED' : 'PROJECT_CONTEXT_MISMATCH';
}
return !scoped && !readOnly && !expected.token ? 'PROJECT_CONTEXT_REQUIRED' : null;
}
function withContextSchema(tool) {
return { ...tool, inputSchema: { ...tool.inputSchema, properties: {
...tool.inputSchema && tool.inputSchema.properties,
expected_context: { type: 'string', description: 'Optional Editor-session pin from initialize.funplay.context after independently verifying the intended project. Required for mutating calls through legacy unscoped URLs.' },
} } };
}
module.exports = { CONTEXT_META_KEY, projectEndpoint, serverUrl, projectContext, requestRoute, contextError, withContextSchema };
@@ -0,0 +1,419 @@
'use strict';
const fs = require('fs');
const path = require('path');
const { resolveProjectFilePath: resolveProjectPath } = require('./path-safety');
const { readOptionalText, writeTextIfUnchanged } = require('./atomic-file');
const { getSkillsDirectory, getSkillProjectPath } = require('./skill-platforms');
const KNOWN_INSTRUCTION_PATHS = [
'AGENTS.md',
'CLAUDE.md',
'GEMINI.md',
'.cursorrules',
'.windsurfrules',
'.github/copilot-instructions.md',
];
const COCOS_MCP_SKILL_NAME = 'funplay-cocos-mcp-workflow';
const COCOS_MCP_SKILL_TITLE = 'Funplay Cocos MCP Workflow';
const LEGACY_COCOS_MCP_SKILL_DESCRIPTION =
'Use this skill when editing, validating, or debugging this Cocos Creator project through Funplay Cocos MCP.';
const COCOS_MCP_SKILL_DESCRIPTION =
'Edit, inspect, validate, preview, and debug Cocos Creator projects through Funplay Cocos MCP. Use when working with scenes, nodes, prefabs, assets, TypeScript, logs, screenshots, preview behavior, runtime state, or MCP connectivity.';
const COCOS_MCP_SKILL_INSTRUCTIONS = [
'## Operating Loop',
'',
'1. Establish context.',
' - Before writes, independently match the intended project to initialize.funplay.context; do not adopt whichever server answered. For old endpoints, reconnects, or frame-paced gestures, read [project identity and input](references/project-identity-and-input.md).',
' - Read `cocos://project/context` or call `get_editor_state` before assuming the project, active scene, MCP URL, selection, visible windows, or tool profile.',
' - Inspect the active scene with `get_scene_info` and `get_hierarchy`; use `get_selection`, `list_scenes`, `list_assets`, or `list_prefabs` when identity or ownership is unclear.',
' - Treat user-provided node and asset names as hints. Resolve the real hierarchy path, node UUID, asset UUID, or `db://assets/...` URL before editing.',
' - Call `get_tool_catalog` when a required tool may be hidden by the `core`, `full`, or custom exposure profile.',
'2. Choose the edit surface.',
' - Edit TypeScript and ordinary project files with repository tools or the MCP file tools, then refresh the affected asset and run diagnostics.',
' - Edit live scene nodes with focused scene/component tools or `execute_javascript` using `context="scene"`; save the scene when the change must persist.',
' - Use `execute_javascript` with `context="editor"` for asset-db, Editor messages, project orchestration, and filesystem work that belongs in the editor process.',
' - Inspect prefab ownership and references before mutation. Prefer focused prefab tools, or edit a verified linked instance and apply it back through the editor workflow.',
' - Preserve an existing UI or gameplay prefab hierarchy and change only the necessary nodes, components, and serialized fields; do not rebuild the entire prefab unless explicitly requested.',
'3. Execute the smallest coherent change.',
' - Prefer one guarded `execute_javascript` operation for tightly related editor work, but use focused tools when they provide clearer validation or safer arguments.',
' - Keep JavaScript safety checks enabled unless the code and its paths were reviewed explicitly.',
' - Null-check every scene, node, component, asset, and filesystem lookup. Return concise structured before/after values, including stable UUIDs or asset URLs where useful.',
' - Save or refresh only the assets and scenes intentionally changed.',
' - Do not guess alternate paths, silently create replacement objects, or run self-healing fallback loops after a missing reference or unsupported editor message.',
'4. Read back and validate.',
' - Re-inspect the exact node, component, prefab instance, or asset after mutation; a successful command response alone is not proof of the final editor state.',
' - Run `run_script_diagnostics` or `get_script_diagnostic_context` after TypeScript changes, then use `validate_scene` and project logs before claiming success.',
' - For visual or runtime work, run the appropriate browser, Game View, or simulator preview and verify with runtime state, input, logs, and screenshots.',
' - State exactly what was verified and what still requires a native build, device, network, store, or manual check.',
'',
'## Scene, Prefab, and Asset Safety',
'',
'- Do not treat Cocos `.scene`, `.prefab`, or `.meta` files as ordinary text. Prefer scene-process, prefab, and asset-db operations that preserve UUID references and editor import state.',
'- If `edit_prefab_json` is used, target a verified prefab path and the smallest exact JSON path or literal replacement, then run `validate_prefab_references` and inspect the result.',
'- Before structural prefab work, call `inspect_prefab`; for scene instances, call `inspect_prefab_instance` and choose deliberately between apply and revert.',
'- Replacing a prefab at the same path can keep the asset UUID while changing internal object IDs and breaking serialized references, animation tracks, nested prefab links, and scene overrides.',
'- Inspect dependencies with `inspect_asset_dependencies` and validate them with `validate_asset_dependencies` before and after sensitive asset changes.',
'- Never copy a `.meta` file when duplicating an asset. Use `duplicate_prefab` or asset-db operations so the new asset receives its own UUID.',
'',
'## Tool Exposure and Execution Contexts',
'',
'- The default `core` profile exposes the main inspection, diagnostics, logs, screenshots, scene, asset, and unified JavaScript workflow.',
'- The `full` profile adds focused mutation tools for nodes, components, prefabs, UI, runtime control, input simulation, files, and project preview.',
'- If a named tool is unavailable under a custom profile, adapt to the exposed catalog and report the missing capability instead of pretending it ran.',
'- In scene context, use the Cocos runtime and scene APIs for live hierarchy and component work. In editor context, use `Editor` APIs and messages for asset-db and extension orchestration.',
'- Use `execute_scene_script` and `execute_editor_script` only as compatibility entrypoints; prefer `execute_javascript` with an explicit context for new workflows.',
'',
'## Readiness and Preview Evidence',
'',
'- For imports, scripts, preview startup, calibrated input, or persistence checks, read [project readiness](references/project-readiness.md). Do not load this conditional reference for an unrelated inspection.',
'- `check_asset_ready` checks stable AssetDB identity, not script compilation or runtime loading. Discover its exposure before use.',
'- `get_runtime_state` describes the editor Game View and toolbar, not browser/simulator runtime or edit-scene counters.',
'- Read `get_recent_logs` or `search_project_logs` for relevant errors. Do not clear persistent logs without explicit confirmation.',
'',
'## Failure Handling',
'',
'- If MCP is unreachable, limit claims to safe filesystem inspection or code edits; do not claim scene, prefab, editor, preview, or runtime verification.',
'- If a node lookup is ambiguous, return the matching paths and UUIDs and choose only after identifying the user-visible or prefab-owned target.',
'- If editor readback and serialized text disagree, trust editor and asset-db readback first and investigate whether the wrong asset, scene instance, or stale import was inspected.',
'- Fix diagnostics or new error logs caused by the change before visual or runtime validation.',
].join('\n');
const COCOS_UI_SKILL_NAME = 'funplay-cocos-ui-composition';
const COCOS_UI_SKILL_TITLE = 'Funplay Cocos UI Composition';
const COCOS_UI_SKILL_DESCRIPTION =
'Build and revise responsive Cocos Creator UI, and turn full-page design images into editable prefabs with reusable sprites, layout adaptation, and visual fidelity checks. Use for Canvas layout, prefabs, scrolling, text, input, and UI validation.';
const COCOS_UI_SKILL_INSTRUCTIONS = [
'For MCP writes, reconnects, or interactive drag tests, read [project identity and input](references/project-identity-and-input.md). Renderer frames are not native Game View engine updates or gameplay acceptance.',
'',
"## UI Workflow",
"",
"1. Inspect the active scene, Canvas, design resolution, target viewports, `UITransform`, `Widget`, `Layout`, existing `SafeArea` policy, prefab ownership and serialized references.",
"2. Preserve the user's design requirements and established project baseline. A full-page reference may define a new screen's baseline; clarify cropped or conflicting references instead of imposing a fixed resolution.",
"3. Preserve existing roots, node/component identities, event bindings, animation targets and nested prefabs. Change only what the request requires; do not rebuild the entire prefab unless explicitly requested.",
"4. Choose one owner for each position/size property. Avoid conflicting Widget, Layout, animation and manual writes. Use supported Cocos scene/prefab/AssetDB workflows for authored assets.",
"5. Read back exact dimensions, anchors, constraints, SpriteFrame/font references and event bindings. Save/reopen when persistence matters; use preview input and screenshots for visual or interaction claims.",
"",
"## Design Fidelity",
"",
"- Preserve authored spacing and the project's adaptation. Do not proactively add SafeArea containers, adaptation scripts or extra insets. New adaptation requires an explicit request or a demonstrated overlap confirmed with the user.",
"- Keep complete UI pages in saved prefabs when that fits the project; runtime hierarchy creation is not a substitute for requested authored UI.",
"- A tool response, hierarchy, edit-scene performance counter and screenshot prove different things. Report unverified runtime, device, glyph or business behavior explicitly.",
"",
"## Read Only the Relevant References",
"",
"- For a complete design image or screenshot to editable UI, including asset splitting, shared controls, and fidelity acceptance, start with [image to prefab](references/image-to-prefab.md).",
"- For resolution, orientation, SafeArea, Widget/Layout, scrolling or masks: [layout and adaptation](references/layout-and-adaptation.md).",
"- For SpriteFrames, nine-slice, atlas or importer edits: [sprites and importers](references/sprites-and-importers.md).",
"- For fonts, text overflow, glyph coverage or requested localization: [text and localization](references/text-and-localization.md).",
"- For event bindings, real input, animation, screenshots or performance evidence: [input and validation](references/input-and-validation.md).",
"",
"These references are conditional; do not load every file for a focused edit.",
].join('\n');
function normalizeSkillName(value) {
const normalized = String(value || '')
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 63)
.replace(/-+$/g, '');
if (!normalized) {
throw new Error('skillName is required.');
}
return normalized;
}
function statFile(filePath) {
try {
return fs.statSync(filePath);
} catch (error) {
return null;
}
}
function decodeYamlScalar(value) {
const text = String(value || '').trim();
if (!text) {
return '';
}
if (text.startsWith('"')) {
try {
return JSON.parse(text);
} catch (error) {
return text.slice(1, text.endsWith('"') ? -1 : undefined);
}
}
if (text.startsWith("'") && text.endsWith("'")) {
return text.slice(1, -1).replace(/''/g, "'");
}
return text;
}
function parseSkillMetadata(content) {
const text = String(content || '');
const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text);
if (frontmatter) {
const values = {};
for (const line of frontmatter[1].split(/\r?\n/)) {
const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line);
if (match) {
values[match[1]] = decodeYamlScalar(match[2]);
}
}
const name = String(values.name || '').trim();
const description = String(values.description || '').trim();
const validName = /^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name) && name.length <= 63;
const validDescription = Boolean(
description && description.length <= 1024 && !/[<>]/.test(description)
);
return {
name,
description,
format: 'frontmatter',
valid: validName && validDescription,
};
}
const title = /^#\s+(.+)$/m.exec(text);
const description = /^Description:\s*(.+)$/m.exec(text);
return {
name: '',
description: description ? description[1].trim() : '',
title: title ? title[1].trim() : '',
format: title || description ? 'legacy' : 'unknown',
valid: false,
};
}
function buildProjectSkillContent(options = {}) {
const skillName = normalizeSkillName(options.skillName);
const title = String(options.title || '').trim() || skillName;
const description = String(options.description || '').trim() || `Project-specific workflow for ${title}.`;
if (description.length > 1024) {
throw new Error('Skill description must be 1024 characters or fewer.');
}
if (/[<>]/.test(description)) {
throw new Error('Skill description cannot contain angle brackets.');
}
const body = String(options.instructions || '').trim() || [
`Use this skill for ${title} work in this Cocos project.`,
'',
'- Inspect the active scene and project context before editing.',
'- Prefer focused MCP tools before broad manual file edits.',
'- Run relevant validation tools after changes.',
].join('\n');
return [
'---',
`name: ${skillName}`,
`description: ${JSON.stringify(description)}`,
'---',
'',
`# ${title}`,
'',
'## Instructions',
'',
body,
'',
].join('\n');
}
function buildCocosMcpProjectSkillContent(options = {}) {
return buildProjectSkillContent({
skillName: options.skillName || COCOS_MCP_SKILL_NAME,
title: options.title || COCOS_MCP_SKILL_TITLE,
description: options.description || COCOS_MCP_SKILL_DESCRIPTION,
instructions: String(options.instructions || '').trim() || COCOS_MCP_SKILL_INSTRUCTIONS,
});
}
function buildCocosUiProjectSkillContent(options = {}) {
return buildProjectSkillContent({
skillName: options.skillName || COCOS_UI_SKILL_NAME,
title: options.title || COCOS_UI_SKILL_TITLE,
description: options.description || COCOS_UI_SKILL_DESCRIPTION,
instructions: String(options.instructions || '').trim() || COCOS_UI_SKILL_INSTRUCTIONS,
});
}
function buildLegacyCocosMcpProjectSkillContent(options = {}) {
const instructions = [
'- Start by reading `cocos://project/context` or calling `get_editor_state` to confirm the active project, scene, server URL, and tool profile.',
'- Prefer `execute_javascript` for high-level scene/editor orchestration, but keep safety checks enabled unless the code was reviewed.',
'- Use focused tools when they are better primitives: `list_assets`, `inspect_asset_dependencies`, `validate_asset_dependencies`, `run_script_diagnostics`, `get_script_diagnostic_context`, and screenshot tools.',
'- For UI work, inspect the active Canvas/hierarchy first, mutate the smallest necessary node/component set, then verify with `validate_scene` and a screenshot.',
...(options.includePrefabPreservationRule ? [
'- When modifying a UI or gameplay-object prefab, preserve the existing prefab and edit only the necessary nodes/components; do not rebuild the entire prefab unless explicitly requested.',
] : []),
'- For prefab or asset edits, inspect dependencies/references before mutation and refresh assets afterward.',
'- When changing tool exposure, save a named tool profile so the same client setup can be restored later.',
].join('\n');
return [
`# ${COCOS_MCP_SKILL_TITLE}`,
'',
`Description: ${LEGACY_COCOS_MCP_SKILL_DESCRIPTION}`,
'',
'## Instructions',
instructions,
'',
].join('\n');
}
function listSkillFiles(projectPath, options = {}) {
projectPath = getSkillProjectPath(projectPath, options);
const skillRoot = resolveProjectPath(projectPath, getSkillsDirectory(options));
if (!fs.existsSync(skillRoot)) {
return [];
}
const skills = [];
const stack = [skillRoot];
while (stack.length) {
const current = stack.pop();
for (const entry of fs.readdirSync(current, { withFileTypes: true })) {
const fullPath = resolveProjectPath(projectPath, path.join(current, entry.name));
if (entry.isDirectory()) {
stack.push(fullPath);
continue;
}
if (entry.name === 'SKILL.md') {
const stat = statFile(fullPath);
const metadata = parseSkillMetadata(fs.readFileSync(fullPath, 'utf8'));
skills.push({
path: path.relative(projectPath, fullPath).replace(/\\/g, '/'),
size: stat ? stat.size : 0,
mtime: stat ? stat.mtime.toISOString() : '',
name: metadata.name || path.basename(path.dirname(fullPath)),
title: metadata.title || '',
description: metadata.description,
format: metadata.format,
valid: metadata.valid,
});
}
}
}
return skills.sort((left, right) => left.path.localeCompare(right.path));
}
function listProjectInstructions(projectPath, options = {}) {
projectPath = getSkillProjectPath(projectPath, options);
const files = [];
for (const relativePath of KNOWN_INSTRUCTION_PATHS) {
const fullPath = resolveProjectPath(projectPath, relativePath);
const stat = statFile(fullPath);
if (stat && stat.isFile()) {
files.push({
path: relativePath,
size: stat.size,
mtime: stat.mtime.toISOString(),
});
}
}
return {
files,
skills: listSkillFiles(projectPath, options),
};
}
function readProjectInstruction(projectPath, target) {
const relativePath = String(target || '').trim();
if (!relativePath) {
throw new Error('target is required.');
}
const fullPath = resolveProjectPath(projectPath, relativePath);
if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile()) {
throw new Error(`Instruction file not found: ${relativePath}`);
}
return {
path: relativePath,
content: fs.readFileSync(fullPath, 'utf8'),
};
}
function writeProjectInstruction(projectPath, options = {}) {
const relativePath = String(options.target || '').trim();
if (!relativePath) {
throw new Error('target is required.');
}
const content = String(options.content || '');
const fullPath = resolveProjectPath(projectPath, relativePath);
const original = Object.prototype.hasOwnProperty.call(options, 'expectedContent') ? options.expectedContent : readOptionalText(fullPath);
if (original !== null && options.overwrite === false) {
throw new Error(`Instruction file already exists: ${relativePath}`);
}
writeTextIfUnchanged(fullPath, content, original);
const stat = fs.statSync(fullPath);
return {
written: true,
path: relativePath,
size: stat.size,
mtime: stat.mtime.toISOString(),
};
}
function createProjectSkill(projectPath, options = {}) {
projectPath = getSkillProjectPath(projectPath, options);
const skillName = normalizeSkillName(options.skillName);
const relativePath = `${getSkillsDirectory(options)}/${skillName}/SKILL.md`;
const content = buildProjectSkillContent({ ...options, skillName });
return writeProjectInstruction(projectPath, {
target: relativePath,
content,
overwrite: options.overwrite !== false,
});
}
function createCocosMcpProjectSkill(projectPath, options = {}) {
return createManagedProjectSkill(projectPath, COCOS_MCP_SKILL_NAME, options);
}
function createCocosUiProjectSkill(projectPath, options = {}) {
return createManagedProjectSkill(projectPath, COCOS_UI_SKILL_NAME, options);
}
function createManagedProjectSkill(projectPath, templateSkillName, options) {
projectPath = getSkillProjectPath(projectPath, options);
const skillName = normalizeSkillName(options.skillName || templateSkillName);
const target = `${getSkillsDirectory(options)}/${skillName}/SKILL.md`;
if (options.overwrite === false && fs.existsSync(resolveProjectPath(projectPath, target))) {
throw new Error(`Instruction file already exists: ${target}`);
}
// Lazy import avoids a cycle: the manager uses the pure content builders above.
const result = require('./project-skills').updateBuiltInProjectSkill(projectPath, {
...options, skillName, templateSkillName, allowModified: options.overwrite !== false,
});
return {
...(result.write || { written: false, path: result.state.path }),
manifest: result.manifest || result.state.manifest.path,
references: result.references || result.state.references.map((file) => file.path),
backup: result.backup || null,
};
}
module.exports = {
COCOS_MCP_SKILL_DESCRIPTION,
COCOS_MCP_SKILL_INSTRUCTIONS,
COCOS_MCP_SKILL_NAME,
COCOS_MCP_SKILL_TITLE,
COCOS_UI_SKILL_DESCRIPTION,
COCOS_UI_SKILL_INSTRUCTIONS,
COCOS_UI_SKILL_NAME,
COCOS_UI_SKILL_TITLE,
KNOWN_INSTRUCTION_PATHS,
buildCocosMcpProjectSkillContent,
buildCocosUiProjectSkillContent,
buildLegacyCocosMcpProjectSkillContent,
buildProjectSkillContent,
createCocosMcpProjectSkill,
createCocosUiProjectSkill,
createProjectSkill,
listProjectInstructions,
normalizeSkillName,
parseSkillMetadata,
readProjectInstruction,
writeProjectInstruction,
};
+77
View File
@@ -0,0 +1,77 @@
'use strict';
const fs = require('fs');
const { resolveProjectFilePath: resolveProjectPath } = require('./path-safety');
const PROMPT_DIRECTORY = 'mcp-prompts';
const MAX_PROMPT_FILES = 100;
const MAX_PROMPT_BYTES = 256 * 1024;
const IDENTIFIER = /^[a-z][a-z0-9_-]{0,63}$/;
function parseProjectPrompt(content) {
const match = String(content).replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n')
.match(/^---[ \t]*\n([\s\S]*?)\n---[ \t]*\n([\s\S]*)$/);
if (!match) throw new Error('Expected a --- frontmatter block followed by a prompt body.');
const fields = Object.create(null);
for (const line of match[1].split('\n')) {
if (!line.trim() || line.trim().startsWith('#')) continue;
const field = line.match(/^([a-z]+):[ \t]*(.*)$/);
if (!field || !['name', 'description', 'arguments'].includes(field[1])) throw new Error(`Unsupported frontmatter line: ${line}`);
if (Object.prototype.hasOwnProperty.call(fields, field[1])) throw new Error(`Duplicate field: ${field[1]}`);
fields[field[1]] = field[2].trim();
}
if (!IDENTIFIER.test(fields.name || '')) throw new Error('Invalid prompt name. Use lowercase letters, digits, hyphens or underscores (1–64 characters).');
if ((fields.description || '').length > 512) throw new Error('Description exceeds 512 characters.');
const body = match[2].trim();
if (!body) throw new Error('Prompt body is empty.');
const names = new Set();
const args = fields.arguments ? fields.arguments.split(',').map((value) => {
const arg = value.trim().match(/^([a-z][a-z0-9_-]{0,63})(\(required\))?$/);
if (!arg) throw new Error(`Invalid argument declaration: ${value}`);
if (names.has(arg[1])) throw new Error(`Duplicate argument: ${arg[1]}`);
names.add(arg[1]);
return { name: arg[1], description: arg[1], required: Boolean(arg[2]) };
}) : [];
return { name: fields.name, description: fields.description || fields.name, arguments: args, body };
}
function loadProjectPrompts(projectPath, reservedNames = []) {
const prompts = [];
const warnings = [];
if (!projectPath) return { prompts, warnings };
try {
const directory = resolveProjectPath(projectPath, PROMPT_DIRECTORY);
if (!fs.existsSync(directory)) return { prompts, warnings };
if (fs.lstatSync(directory).isSymbolicLink()) throw new Error('The mcp-prompts directory must not be a symbolic link.');
const files = fs.readdirSync(directory, { withFileTypes: true })
.filter((entry) => entry.name.endsWith('.md')).sort((a, b) => a.name.localeCompare(b.name));
if (files.length > MAX_PROMPT_FILES) warnings.push(`Only the first ${MAX_PROMPT_FILES} Markdown files are loaded.`);
const seen = new Set(reservedNames.map((name) => name.toLowerCase()));
for (const entry of files.slice(0, MAX_PROMPT_FILES)) {
try {
if (!entry.isFile()) throw new Error('Only regular files are supported; symbolic links are skipped.');
const filePath = resolveProjectPath(projectPath, `${PROMPT_DIRECTORY}/${entry.name}`);
if (fs.statSync(filePath).size > MAX_PROMPT_BYTES) throw new Error(`File exceeds ${MAX_PROMPT_BYTES} bytes.`);
const prompt = parseProjectPrompt(fs.readFileSync(filePath, 'utf8'));
if (seen.has(prompt.name.toLowerCase())) throw new Error(`Duplicate or reserved prompt name: ${prompt.name}`);
seen.add(prompt.name.toLowerCase());
prompts.push(prompt);
} catch (error) {
warnings.push(`${entry.name}: ${error.message}`);
}
}
} catch (error) {
warnings.push(error.message);
}
return { prompts, warnings };
}
function interpolatePrompt(body, args, declarations) {
const allowed = new Set(declarations.map((arg) => arg.name));
// One pass: placeholders inside argument values are data, not more template syntax.
return body.replace(/\{([a-z][a-z0-9_-]{0,63})\}/g, (original, name) => (
allowed.has(name) ? (Object.prototype.hasOwnProperty.call(args, name) ? args[name] : '') : original
));
}
module.exports = { PROMPT_DIRECTORY, MAX_PROMPT_FILES, MAX_PROMPT_BYTES, parseProjectPrompt, loadProjectPrompts, interpolatePrompt };
@@ -0,0 +1,161 @@
'use strict';
// Original Cocos-specific guidance, exported beside each client's SKILL.md.
// Entrypoints route here only when the corresponding kind of work is requested.
const WORKFLOW_REFERENCES = Object.freeze({
'references/project-readiness.md': `# Project, import, and preview readiness
## Asset and script changes
- Resolve the exact AssetDB UUID or db:// URL. Refresh only the changed source assets; do not guess an extension or silently substitute another asset.
- Import is asynchronous. If exposed, use \`check_asset_ready\` with the exact target after refresh/import and before assigning the asset or attaching its script. A stable imported UUID/URL identity is not proof that the importer queue is empty, TypeScript compiled, or the preview loaded those bytes.
- \`check_asset_ready\` is a Full-profile read-only tool. Discover exposure with \`get_tool_catalog\`; do not change a custom allowlist without authorization. If unavailable, query exact asset info and report the narrower evidence instead of claiming full readiness.
- After TypeScript edits, run \`run_script_diagnostics\` and inspect import/preview errors. Its no-emit compiler result is separate from Creator's compilation and preview loading.
- A zero-wait readiness query is one observation, not stable readiness. Busy, missing, importing, timeout, unavailable, and unknown results are not success. Wait within a bounded budget or report the unresolved state; never repeat a mutation to obtain a cleaner response.
- Check APIs against the actual Creator version and loaded project components, not only a package.json declaration. Preserve existing dependencies and project conventions.
## Preview evidence
- Query \`get_preview_mode\` before choosing browser, editor Game View, or simulator. Browser \`localUrl\` is same-host; \`networkUrl\` is Creator's LAN address.
- \`get_runtime_state\`, pause, and resume address the editor Game View and its native toolbar. They do not inspect external browser/simulator runtime state. Edit-scene director counters and time scale are not Game View state.
- A listening MCP server, opened window, non-empty screenshot, current scene drawing, and correct business behavior are different claims. Verify only the layers relevant to the user's request and identify missing evidence.
- Use \`capture_scene_screenshot\` for editor Scene composition and Game/preview capture for game output. For real pointer testing, bind \`simulate_mouse_click\` or drag to the returned \`captureId\` with \`coordinateSpace="image-pixels"\`; use coordinates from that exact image.
- Recapture after a resize, zoom, reload, scene change, or stale-capture rejection. Do not scale coordinates from an unrelated/resized reference image yourself. Button event emission tests handlers but does not prove hit testing, clipping, focus, or occlusion.
- If an input reports an unknown outcome, inspect the resulting state before deciding on another action. Do not automatically resend it. Restore only temporary state owned by this task; preserve user changes.
## Persistence
- Prefer scene-process, prefab, and AssetDB tools for .scene/.prefab/.meta changes. A successful native message alone does not prove saved content or preserved UUID links.
- Reinspect the exact object and relevant serialized references, save only the requested changes, and reopen when persistence matters. Keep incomplete checks explicit.
Sources: [Creator messages](https://docs.cocos.com/creator/3.8/manual/en/editor/extension/messages.html) and [asset workflow](https://docs.cocos.com/creator/3.8/manual/en/asset/asset-workflow.html).\n`,
});
const UI_REFERENCES = Object.freeze({
'references/layout-and-adaptation.md': `# Layout and design fidelity
## Resolution and safe area
- User requirements and explicit design specifications take priority. Preserve an established project's design resolution and Fit Width/Fit Height policy unless a change is requested. For a new screen without a baseline, a full-page design image may define the baseline; a crop, conflicting images, or unclear intended dimensions need clarification. Do not impose a fixed phone resolution.
- Keep authored spacing and full-bleed composition. Inspect existing SafeArea components and runtime adaptation before changing them. Do not proactively add SafeArea containers, adaptation scripts, extra margins, or a second inset; new adaptation needs an explicit request or a demonstrated overlap confirmed with the user.
- If safe-area adaptation is requested, distinguish full-bleed art from critical controls and apply it once. Cocos SafeArea uses sys.getSafeAreaRect and Widget; preserve the project's existing ownership of position/size.
- Separate Canvas adaptation from gameplay camera composition. Correct Widget constraints do not prove that the world camera shows the desired area.
## Property ownership
- UITransform owns contentSize and anchor point. Keep ordinary layout scale at one; change dimensions or constraints rather than stretching transforms to approximate a design.
- Widget owns selected edges/centers and may overwrite position or size. Choose ONCE, ON_WINDOW_RESIZE, or ALWAYS from actual behavior; do not animate a property continuously rewritten by Widget.
- Layout drives children or container according to ResizeMode. Putting Layout and Widget on the same node can create competing ownership. Read back driven sizes after layout settles; call updateLayout only when same-frame measurement is required.
- Verify grid cell/constraint policy, padding, spacing, axis and growth direction. Keep nested layout chains shallow and batch repeated content changes.
- Responsive region patterns are options, not permission to reorganize existing prefabs. Reposition only the regions needed by the requested aspect-ratio change; retain roots, identities, references and animation tracks.
## Scrolling and clipping
- Use a ScrollView root, masked view and content node. Verify the actual content reference, enabled axes, inertia/brake/bounce, child-button cancellation and nested scrolling.
- Respect Mask renderer constraints and clipping boundaries. Do not add Sprite/Label renderers to a Mask node where its renderer is owned by the mask implementation.
- Pool large repeated lists. Test first/last items, resize, overflow and dynamic content in preview; dimensions alone do not prove visibility or input.
Sources: [Widget](https://docs.cocos.com/creator/3.8/manual/en/ui-system/components/editor/widget.html), [Layout](https://docs.cocos.com/creator/3.8/manual/en/ui-system/components/editor/layout.html), [SafeArea](https://docs.cocos.com/creator/3.8/manual/en/ui-system/components/editor/safearea.html), [multi-resolution adaptation](https://docs.cocos.com/creator/3.8/manual/en/ui-system/components/engine/multi-resolution.html).\n`,
'references/sprites-and-importers.md': `# SpriteFrames, nine-slice, and importer edits
- Resolve the source image, its .meta ownership and exact SpriteFrame subasset UUID before assignment or importer edits. Texture, ImageAsset and SpriteFrame are different asset types; never fabricate a subasset UUID.
- Inspect source dimensions, rect/trim/rotation, cap insets, Sprite type, sizeMode and UITransform dimensions. Set CUSTOM sizeMode before assigning a SpriteFrame when authored dimensions must remain fixed, then read back the final size after assignment.
- For sliced borders, retain source-coordinate insets and surviving SpriteFrame identities. Check that left+right and top+bottom fit the source rect and that corners/borders remain intact at the intended sizes. Do not derive importer coordinates from a downscaled screenshot.
- Use focused importer/AssetDB operations when available. If a narrowly scoped .meta edit is necessary, preserve unrelated importer settings, UUIDs, submeta mappings and atlas references, refresh the exact source, and verify imported state. Do not recreate metadata or copy a .meta file to duplicate an asset.
- Changing atlas membership, trimming or slicing can affect animation tracks, nested prefabs and material/batching behavior. Inspect incoming references before a structural change and report unsupported identity preservation rather than rebuilding references by name.
- After import, \`check_asset_ready\` verifies only the imported AssetDB identity; inspect the actual SpriteFrame and saved component binding separately. Save/reopen when persistence is required and visually inspect corners at the target size.
- Group compatible materials/textures only while preserving intended render order. Editor node/component counts are not a runtime draw-call or GPU measurement.
Sources: [Sprite](https://docs.cocos.com/creator/3.8/manual/en/ui-system/components/editor/sprite.html) and [image assets](https://docs.cocos.com/creator/3.8/manual/en/asset/image.html).\n`,
'references/text-and-localization.md': `# Fonts, text sizing, and requested localization
- Preserve the project's font system: system font, imported TTF/OTF, bitmap font, RichText, or a project-specific localization component. Resolve font assets and their actual component bindings; do not replace the font strategy merely to silence a warning.
- Verify fontSize, lineHeight, alignment, wrapping, contentSize, cacheMode and overflow at the intended viewport. CLAMP clips, SHRINK changes readable size and can cost CPU on dynamic text, and RESIZE_HEIGHT transfers height ownership to the label. Choose from project policy rather than applying SHRINK everywhere.
- Check CJK, punctuation, digits, icons and other required glyphs in representative strings. Include line breaks, long translations and dynamic/code-composed strings when localization is requested. A successful string assignment does not establish glyph coverage or readability.
- Bitmap-font atlas glyphs, character-cache capacity, fallback behavior and persisted font assets need separate checks. If coverage cannot be measured, report unknown rather than assuming all characters render.
- For requested localization, identify the existing locale IDs and mapping, text keys, authored labels, runtime formatting and fallback policy. Change only requested languages/scope and preserve existing services; do not install an unrelated localization package by default.
- Read back persisted font/text/localization references and representative outputs. Report covered, missing and unverified strings separately; inspecting authored labels does not prove coverage of runtime-generated text.
- Capture representative languages and aspect ratios and inspect missing glyphs, clipping, wrapping and layout growth. Native/device performance and input-method behavior require corresponding platform evidence.
Sources: [Label](https://docs.cocos.com/creator/3.8/manual/en/ui-system/components/editor/label.html) and [font assets](https://docs.cocos.com/creator/3.8/manual/en/asset/font.html).\n`,
'references/input-and-validation.md': `# Input, animation, and visual verification
- Verify Button/Toggle/Slider/EditBox target nodes, serialized component/handler/custom data, disabled state, hit area and focus behavior. Bind once; don't make duplicate listeners to compensate for an unresolved reference.
- Emitting Button click events checks callbacks, not real pointer dispatch. For hit testing use the actual Game View/preview and calibrated screenshot coordinates; verify the resulting state or screenshot rather than treating event delivery as the business outcome.
- Screenshot \`captureId\` identifies one image and its observed geometry. Use \`coordinateSpace="image-pixels"\` with coordinates in that exact PNG. Calibration maps to Electron content coordinates and rejects stale or changed targets. It does not identify a Button or prove absence of occlusion.
- Keep UIOpacity, active state, Button interactability and BlockInputEvents consistent. A transparent modal may still block input; a visible scrim may not block anything. Check sibling order, masks and hidden states in preview.
- Animate a Visual/Container child when Widget or Layout owns the root. Cancel/reconcile prior tweens, and verify deterministic position, scale, opacity, active state and close/reopen behavior. Use an explicit UI clock only if menus must animate during gameplay pause.
- Test only requested interactions. An input with unknown delivery/outcome must be followed by readback, not automatic replay. Restore temporary preview state only if still owned by this task.
- Use \`validate_scene\`, exact component/reference readback and screenshots as complementary evidence. A complete hierarchy or non-empty image does not prove correct layout, visible text, hit testing or business behavior.
- \`get_performance_snapshot\` reports edit-scene node/component/UI/depth/memory counters, not browser/Game View draw calls or GPU performance. Use actual runtime/platform measurements before making performance claims.
- Choose representative aspect ratios and locales for the target project. Record which checks passed, failed, were incomplete or require a device; avoid claiming universal validation from one screenshot.
Sources: [UI system](https://docs.cocos.com/creator/3.8/manual/en/2d-object/ui-system/) and [node hierarchy](https://docs.cocos.com/creator/3.8/manual/en/concepts/scene/node-tree.html).\n`,
'references/image-to-prefab.md': `# From a full UI image to an editable Cocos prefab
Use this workflow for a new page or a set of switchable pages drawn in a user design. Work with the project's reusable artwork and the user's own designs and assets. For a third-party inspiration reference, create original visuals for the new UI.
## When image generation helps
Image generation is optional. Cocos MCP handles asset import, prefab composition, and preview verification. Any image generation or editing comes from a tool available in the AI client or the project's art pipeline.
- For a layered design, reuse its exported assets. For a flattened image, reuse clean cuts from visible regions and build text, dividers, and simple surfaces with native UI components. The reference can be analyzed by an image-capable client or described in a supplied component map.
- If a complex background or icon is missing, or a UI element hides part of the background, use an available image generation or editing tool to produce just the missing asset. Specify its intended dimensions, silhouette, style, and transparency or bleed. Inspect the output at its intended size and mark generated artwork as an approximation until it passes the visual comparison.
- With no generation tool, proceed with reusable assets and the layout that can be verified. If missing artwork blocks fidelity acceptance, request the corresponding clean background, transparent sprite, or layered design. Record any placeholder and the affected regions in the review.
## Lock the design and map the parts
- Keep each reference at its original pixel dimensions. Identify the game viewport, the selected page/tab, the locale, visible counter values, list scroll position, and relevant control states. Keep the reference and state record for comparison after implementation. If supplied pages disagree on a shared control, resolve the intended variant and record each deliberate departure from the references.
- Use the existing Canvas policy in an established project. On a new page without a baseline, use the intended full viewport as the design basis. Map part bounds in top-left reference pixels, node paths, stacking order, anchors, and fixed or flexible edges. Distinguish visible artwork bounds from the control's layout box and hit area.
- Record the chosen source for each part. Inspect cutouts, including their alpha edges and original padding, against the background they will actually use.
## Build the saved UI
- Keep the full reference image outside the rendered hierarchy. Import only the separately reusable art and use real SpriteFrames. Separate the background, title, button surfaces, icons, labels, badges, progress track/fill, and state overlays so each can move or change independently. Give text, dynamic values, and localization native text components. Reserve graphical lettering for artwork meant to stay fixed.
- Share a navigation prefab or shell across related pages. Keep each tab's icon and caption separate from the normal and selected backgrounds and divider lines. Derive the highlight, tab widths, divider positions, label placement, and hit areas from the selected state and available width. Use nine-slice for stretchable surfaces with fixed corners. Keep icon proportions and intentional blank margins.
- Author repeated lists as reusable rows in a ScrollView with a clipped viewport and Layout-managed content. Give each row separate art, text, and button bindings. Bind callbacks inside standalone prefab boundaries and use the project's normal events or controller bindings to connect them to a shell.
- Save the UI under the existing Canvas with UI_2D layers. Use native prefab serialization, verify exact imported references, and confirm that assets survive reload or fresh instantiation. Consult [sprites and importers](sprites-and-importers.md) for trim/insets and [text and localization](text-and-localization.md) for font behavior. If an icon appears too large, check the imported trim and padding first. If a label clips, apply the font and overflow policy before setting the final box, then inspect the glyph baseline in preview.
- Adapt regions independently. Use anchors for pinned controls, let the list viewport consume the remaining space, and crop flexible background art while preserving its aspect ratio. Keep a single owner for each driven dimension. Use [layout and adaptation](layout-and-adaptation.md) for the project's resize and safe-area policy.
## Verify fidelity in the actual preview
1. Capture the saved scene or prefab instance in the target Cocos preview. For fidelity, use a raw PNG of the same game viewport size and state as the reference. Check visible landmarks, the crop and the canvas size. Equal PNG dimensions alone can still conceal a cropped or zoomed capture.
2. Compare at the same pixel coordinates. Review the whole page, then zoom into the mapped regions for icon silhouettes, alignment, text baselines, borders, shadow/alpha edges, and clipping. Use a side-by-side view and, when available, a same-scale overlay, wipe, or difference heatmap. Avoid shifting or stretching individual regions during comparison.
3. Check node geometry and rendered appearance separately. Use runtime bounds projected into capture pixels for geometry. Use the visible pixels for glyphs, strokes, and artwork. Region color error, structural similarity, and tolerant edge overlap can help locate differences. Choose tolerances for the project before accepting results, and review each required region so a large matching background cannot hide a small control defect.
4. Fix the source of each difference and recapture under the same conditions. A flat 1 px stroke may require a filled border or different pixel alignment. A matching node box can still contain the wrong sprite or state. Preserve the original design, captures, per-region results, and any approved variations for review.
5. Check adaptation at the requested narrow and wide viewports with real pointer input. Exercise the in-scope page changes, button states, value updates, list scrolling and clipping using [input and validation](input-and-validation.md). Report the fidelity result for the baseline size and the adaptation/input results for the tested sizes. State any remaining mismatches or untested conditions.
For example, a shared bottom bar can have separate mapped regions for five icon silhouettes, the selected surface, a thin divider, and the full bar. At the reference size, check these independently. On a wider viewport, check that the highlight and lines follow the slots and that the same tabs respond to clicks. This catches trim and resize problems even when the page looks close in a thumbnail.
\n`,
});
function getProjectSkillReferences(skillName) {
const templates = skillName === 'funplay-cocos-mcp-workflow' ? WORKFLOW_REFERENCES
: skillName === 'funplay-cocos-ui-composition' ? UI_REFERENCES : {};
const execution = `# Project identity and frame-paced input
## Before editing through MCP
Generated connections use /mcp/project/<project-id>/ on the existing project port. Independently compare initialize.funplay.context.project_path and project_id to the user's intended project. Context metadata identifies an extension/Editor lifetime, not authentication or permission to edit another project.
Legacy / and /mcp addresses still support initialization and exposed read-only tools. Mutating tools require expected_context from that verified initialization, either as a tool argument or params._meta.expected_context. A project-scoped URL binds the project; an explicit expected_context also pins the extension/Editor instance. Missing, wrong-project, conflicting or stale pins execute nothing. Never automatically fetch a token from an arbitrary responding server just to bypass a rejection.
Prefer reconfiguration from MCP Server's existing connection/Skills notice, then reconnect or restart the client. Existing user edits remain protected. Unreadable client files need review; unrelated entries and historical shared entries are not silently deleted. A reload can invalidate the instance pin and calibrated screenshots even while the port remains the same. Read fresh identity and capture again; never replay a mutation solely to get a cleaner reply.
## Frame-paced mouse drag (Full profile)
Use this only when a drag test is requested and the originating input tool is exposed. Keep legacy timing for existing steps/stepDelayMs callers. For a new frame-paced gesture, capture the exact target, use coordinateSpace=image-pixels with its captureId, and choose a unique requestKey. Set timing=frame-paced and supply startX/startY/endX/endY from that PNG. durationMs is 50..10000 (default 600); pressHoldMs and endHoldMs are 0..2000 (default 100). Each edge still gets separate renderer frames at zero hold. Do not mix legacy step timing with these fields.
The tool waits up to waitMs (default 1200), then may return a running receipt. Read it through the SAME tool with action=status and jobId or requestKey; cancel through action=cancel without coordinates. A retained identical start recovers its original receipt and never dispatches the gesture again. Changed arguments conflict. Only the latest 32 receipts are retained; these are not durable transactions across eviction/reload. A missing receipt requires inspection of the resulting state, not an automatic retry with a new key. The preview wrapper and direct mouse-drag tool have separate ownership; do not change custom exposure lists to access another tool's receipts.
Frame-paced input observes the captured Electron renderer's requestAnimationFrame callbacks. Native Game View pause/stop state is checked separately; renderer progression does not prove that native game Update advanced or a game accepted the gesture. Receipts deliberately report nativeGameUpdateVerified=false and businessOutcomeVerified=false. Compare authored state, actual preview/game state and fresh screenshots independently. This is mouse input, not touch injection or proof of physical-device provenance.
Focus loss, stale geometry, stalled frames, cancellation, preview pause/stop and extension shutdown interrupt the job. Only its own mouse release is attempted, without business callbacks or a legacy fallback. Cleanup failure leaves the target window locked; explicitly cancel that job to retry cleanup. Status reads never send input. No background/focus policy, preview pause state, project input setting or dependency is automatically changed.
Sources: [MCP transport](https://modelcontextprotocol.io/specification/2025-11-25/basic/transports), [Electron input](https://www.electronjs.org/docs/latest/api/web-contents#contentssendinputeventinputevent) and [Creator Director](https://docs.cocos.com/creator/3.8/api/en/class/Director).
`;
return Object.entries(Object.keys(templates).length ? { ...templates, 'references/project-identity-and-input.md': execution } : {})
.map(([filePath, content]) => ({ path: filePath, content }));
}
module.exports = { getProjectSkillReferences };
+766
View File
@@ -0,0 +1,766 @@
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const path = require('path');
const {
COCOS_MCP_SKILL_DESCRIPTION,
COCOS_MCP_SKILL_NAME,
COCOS_MCP_SKILL_TITLE,
COCOS_UI_SKILL_DESCRIPTION,
COCOS_UI_SKILL_NAME,
COCOS_UI_SKILL_TITLE,
buildCocosMcpProjectSkillContent,
buildCocosUiProjectSkillContent,
buildLegacyCocosMcpProjectSkillContent,
listProjectInstructions,
normalizeSkillName,
parseSkillMetadata,
writeProjectInstruction,
} = require('./project-instructions');
const { resolveProjectFilePath: resolveProjectPath } = require('./path-safety');
const { SKILL_PLATFORMS, getSkillPlatform, getSkillsDirectory, getSkillProjectPath } = require('./skill-platforms');
const { readOptionalText } = require('./atomic-file');
const { getProjectSkillReferences } = require('./project-skill-references');
const COCOS_MCP_SKILL_TEMPLATE_VERSION = 4;
const COCOS_UI_SKILL_TEMPLATE_VERSION = 5;
const MANIFEST_FILE_NAME = '.funplay-cocos-mcp.json';
const BACKUP_ROOT = '.agents/skill-backups';
const BUILT_IN_PROJECT_SKILLS = Object.freeze([
Object.freeze({
id: 'cocos-mcp-workflow',
skillName: COCOS_MCP_SKILL_NAME,
title: COCOS_MCP_SKILL_TITLE,
description: COCOS_MCP_SKILL_DESCRIPTION,
templateVersion: COCOS_MCP_SKILL_TEMPLATE_VERSION,
buildContent: buildCocosMcpProjectSkillContent,
legacyTemplates: Object.freeze([
Object.freeze({ version: 3, hash: 'a1ab6bd3201e4e16513b0c6307d90db737326c3de4df51d85028b68a3495832c' }),
Object.freeze({ version: 2, hash: 'b0371afe3dd7084052927af8130a0929c0877cd48ade67ca9bd9605e1d8cee35' }),
Object.freeze({ version: 1, content: buildLegacyCocosMcpProjectSkillContent() }),
Object.freeze({
version: 1,
content: buildLegacyCocosMcpProjectSkillContent({ includePrefabPreservationRule: true }),
}),
]),
}),
Object.freeze({
id: 'cocos-ui-composition',
skillName: COCOS_UI_SKILL_NAME,
title: COCOS_UI_SKILL_TITLE,
description: COCOS_UI_SKILL_DESCRIPTION,
templateVersion: COCOS_UI_SKILL_TEMPLATE_VERSION,
buildContent: buildCocosUiProjectSkillContent,
legacyTemplates: Object.freeze([
Object.freeze({ version: 4, hash: '66a3c8d8df159ea796b838710b895992142851092c9d235d4b0f556b8e8aecb2' }),
Object.freeze({ version: 3, hash: 'aa57456be315901395adc8ba83e6fe55b5a4c996659365bcea9a76fa1e55d6f8' }),
Object.freeze({ version: 2, hash: 'f3ea391fd31b703e29919d92e95294b075494d0368b156524017fa7fcd58db9a' }),
Object.freeze({
version: 1,
// Original v1 content from v0.5.2, including installs without a manifest.
hash: '835f4c4b6e6dc79cabf4e5048ac056b6f2441b2b77c0c555ca502740cc175e72',
}),
]),
}),
]);
function sha256Text(value) {
return crypto.createHash('sha256').update(String(value || ''), 'utf8').digest('hex');
}
function getBuiltInProjectSkillDefinitions() {
return BUILT_IN_PROJECT_SKILLS.map((definition) => ({
id: definition.id,
skillName: definition.skillName,
title: definition.title,
description: definition.description,
templateVersion: definition.templateVersion,
}));
}
function resolveBuiltInProjectSkillDefinition(value = COCOS_MCP_SKILL_NAME) {
const key = String(value || COCOS_MCP_SKILL_NAME).trim();
const definition = BUILT_IN_PROJECT_SKILLS.find((item) => (
item.skillName === key || item.id === key
));
if (!definition) {
throw new Error(`Unknown built-in project skill: ${key}`);
}
return definition;
}
function definitionFromOptions(options = {}) {
return resolveBuiltInProjectSkillDefinition(
options.templateSkillName || options.skillName || options.skillId || COCOS_MCP_SKILL_NAME
);
}
function resolveReferencePath(projectPath, relativePath) {
const filePath = resolveProjectPath(projectPath, relativePath);
// A managed reference must not adopt a symlink to another authored project file.
const parts = path.relative(projectPath, filePath).split(path.sep);
let current = projectPath;
for (const part of parts) {
current = path.join(current, part);
try {
if (fs.lstatSync(current).isSymbolicLink()) throw new Error(`Skill reference path is a symbolic link: ${relativePath}`);
} catch (error) {
if (error.code !== 'ENOENT') throw error;
}
}
return filePath;
}
function referenceSnapshots(projectPath, skillName, definition, options, manifestData = {}) {
const root = path.dirname(getSkillRelativePath(skillName, options));
return getProjectSkillReferences(definition.skillName).map((template) => {
const relativePath = `${root}/${template.path}`;
const filePath = resolveReferencePath(projectPath, relativePath);
const content = readOptionalText(filePath);
const currentHash = content === null ? '' : sha256Text(content);
const templateHash = sha256Text(template.content);
const record = manifestData.skillName === skillName && manifestData.files &&
Object.prototype.hasOwnProperty.call(manifestData.files, template.path) ? manifestData.files[template.path] : null;
const tracked = Boolean(record && typeof record.installedHash === 'string' && /^[a-f0-9]{64}$/.test(record.installedHash));
const current = content !== null && currentHash === templateHash;
const modified = content !== null && !current && tracked && currentHash !== record.installedHash;
const conflict = content !== null && !current && !tracked;
return {
path: relativePath, relativePath: template.path, filePath, content, templateContent: template.content,
exists: content !== null, current, modified, conflict, managed: current || tracked,
currentHash, templateHash,
status: content === null ? 'missing' : conflict ? 'conflict' : modified ? 'modified' : current ? 'current' : 'update-available',
};
});
}
function publicReferenceState(reference) {
const { content, templateContent, filePath, ...state } = reference;
return state;
}
function getSkillRelativePath(skillName = COCOS_MCP_SKILL_NAME, options = {}) {
return `${getSkillsDirectory(options)}/${skillName}/SKILL.md`;
}
function getManifestRelativePath(skillName = COCOS_MCP_SKILL_NAME, options = {}) {
return `${getSkillsDirectory(options)}/${skillName}/${MANIFEST_FILE_NAME}`;
}
function readJsonFile(filePath) {
try {
return {
valid: true,
value: JSON.parse(fs.readFileSync(filePath, 'utf8')),
error: '',
};
} catch (error) {
return {
valid: false,
value: null,
error: error.message,
};
}
}
function readManagedSkillManifest(projectPath, skillName = COCOS_MCP_SKILL_NAME, options = {}) {
projectPath = getSkillProjectPath(projectPath, options);
const relativePath = getManifestRelativePath(skillName, options);
const filePath = resolveProjectPath(projectPath, relativePath);
if (!fs.existsSync(filePath)) {
return {
exists: false,
valid: false,
path: relativePath,
data: null,
error: '',
};
}
const parsed = readJsonFile(filePath);
return {
exists: true,
valid: parsed.valid,
path: relativePath,
data: parsed.value,
error: parsed.error,
};
}
function writeManagedSkillManifest(projectPath, content, options = {}) {
projectPath = getSkillProjectPath(projectPath, options);
const skillName = options.skillName || COCOS_MCP_SKILL_NAME;
let definition = null;
try {
definition = resolveBuiltInProjectSkillDefinition(skillName);
} catch (error) {
// A custom folder name may still contain the recommended workflow template.
}
const contentHash = sha256Text(content);
const data = {
schemaVersion: 2,
skillId: String(options.skillId || definition && definition.id || skillName),
skillName,
templateVersion: Number(
options.templateVersion || definition && definition.templateVersion || COCOS_MCP_SKILL_TEMPLATE_VERSION
),
templateHash: contentHash,
installedHash: contentHash,
files: Object.fromEntries([
['SKILL.md', { templateHash: contentHash, installedHash: contentHash }],
...(options.referenceFiles || []).map((file) => [file.path, {
templateHash: sha256Text(file.content), installedHash: sha256Text(file.content),
}]),
]),
extensionVersion: String(options.extensionVersion || ''),
updatedAt: new Date().toISOString(),
};
const result = writeProjectInstruction(projectPath, {
target: getManifestRelativePath(skillName, options),
content: `${JSON.stringify(data, null, 2)}\n`,
...(Object.prototype.hasOwnProperty.call(options, 'expectedManifestContent') ? { expectedContent: options.expectedManifestContent } : {}),
overwrite: true,
});
return { ...result, data };
}
function timestampForPath(date = new Date()) {
return date.toISOString().replace(/[:.]/g, '-');
}
function listProjectSkillBackups(projectPath, skillName = COCOS_MCP_SKILL_NAME, options = {}) {
projectPath = getSkillProjectPath(projectPath, options);
const relativeRoot = `${getSkillsDirectory(options).replace(/\/skills$/, '/skill-backups')}/${skillName}`;
const platform = getSkillPlatform(options);
const roots = [relativeRoot];
if (platform.legacyDirectory && !options.legacy) roots.push(`${platform.legacyDirectory.replace(/\/skills$/, '/skill-backups')}/${skillName}`);
return roots.flatMap((relativeRoot) => {
const root = resolveProjectPath(projectPath, relativeRoot);
if (!fs.existsSync(root)) return [];
return fs.readdirSync(root, { withFileTypes: true })
.filter((entry) => entry.isFile() && entry.name.endsWith('.md'))
.map((entry) => {
const filePath = path.join(root, entry.name);
const stat = fs.statSync(filePath);
return {
path: `${relativeRoot}/${entry.name}`,
size: stat.size,
mtime: stat.mtime.toISOString(),
};
});
})
.sort((left, right) => right.mtime.localeCompare(left.mtime) || right.path.localeCompare(left.path));
}
function createProjectSkillBackup(projectPath, content, options = {}) {
projectPath = getSkillProjectPath(projectPath, options);
const skillName = options.skillName || COCOS_MCP_SKILL_NAME;
const label = String(options.label || 'before-update').replace(/[^a-z0-9_-]+/gi, '-');
const root = `${getSkillsDirectory(options).replace(/\/skills$/, '/skill-backups')}/${skillName}`;
const baseName = `${timestampForPath(options.date || new Date())}-${label}-SKILL`;
let relativePath = `${root}/${baseName}.md`;
let suffix = 2;
while (fs.existsSync(resolveProjectPath(projectPath, relativePath))) {
relativePath = `${root}/${baseName}-${suffix}.md`;
suffix += 1;
}
const backup = writeProjectInstruction(projectPath, {
target: relativePath,
content: String(content || ''),
overwrite: false,
});
if (options.bundle) {
writeProjectInstruction(projectPath, {
target: `${relativePath}.files.json`,
content: `${JSON.stringify({ schemaVersion: 1, ...options.bundle }, null, 2)}\n`,
overwrite: false,
});
}
return backup;
}
function findRecognizedLegacyTemplate(definition, currentHash) {
return definition.legacyTemplates.find((legacy) => (
(legacy.hash || sha256Text(legacy.content)) === currentHash
)) || null;
}
function getBuiltInProjectSkillState(projectPath, options = {}) {
projectPath = getSkillProjectPath(projectPath, options);
const definition = definitionFromOptions(options);
const skillName = options.templateSkillName ? normalizeSkillName(options.skillName || definition.skillName) : definition.skillName;
const relativePath = getSkillRelativePath(skillName, options);
let filePath = resolveProjectPath(projectPath, relativePath);
const platform = getSkillPlatform(options);
const oldPath = platform.legacyDirectory ? `${platform.legacyDirectory}/${skillName}/SKILL.md` : '';
const legacyPath = !fs.existsSync(filePath) && oldPath && fs.existsSync(resolveProjectPath(projectPath, oldPath)) ? oldPath : '';
if (legacyPath) filePath = resolveProjectPath(projectPath, legacyPath);
const installed = fs.existsSync(filePath) && fs.statSync(filePath).isFile();
const templateContent = definition.buildContent({ skillName });
const templateHash = sha256Text(templateContent);
const content = installed ? fs.readFileSync(filePath, 'utf8') : '';
const currentHash = installed ? sha256Text(content) : '';
const metadata = installed ? parseSkillMetadata(content) : {
name: skillName,
description: '',
format: 'missing',
valid: false,
};
const manifest = readManagedSkillManifest(projectPath, skillName, { ...options, legacy: Boolean(legacyPath) });
const manifestData = manifest.valid && manifest.data ? manifest.data : {};
const recognizedLegacy = installed
? findRecognizedLegacyTemplate(definition, currentHash)
: null;
const contentCurrent = installed && currentHash === templateHash;
const references = referenceSnapshots(projectPath, skillName, definition, options, manifestData);
const current = contentCurrent && !legacyPath && references.every((file) => file.current);
const matchesManagedInstall = Boolean(
installed &&
manifest.valid &&
manifestData.skillName === skillName &&
manifestData.installedHash === currentHash
);
const modified = Boolean(
installed && !contentCurrent && !recognizedLegacy && !matchesManagedInstall ||
references.some((file) => file.modified || file.conflict)
);
const updateAvailable = Boolean(installed && !current);
const backups = listProjectSkillBackups(projectPath, skillName, options);
let status = 'missing';
if (current) {
status = 'current';
} else if (modified) {
status = 'modified';
} else if (installed) {
status = 'update-available';
}
const installedTemplateVersion = contentCurrent
? definition.templateVersion
: recognizedLegacy
? recognizedLegacy.version
: Number(manifestData.templateVersion || 0);
return {
skillId: definition.id,
skillName,
title: definition.title,
description: definition.description,
path: relativePath,
clientId: platform.id,
legacyPath,
absolutePath: filePath,
installed,
status,
current,
modified,
managed: Boolean(contentCurrent || recognizedLegacy || matchesManagedInstall),
updateAvailable,
templateVersion: definition.templateVersion,
installedTemplateVersion,
templateHash,
currentHash,
references: references.map(publicReferenceState),
missingReferenceCount: references.filter((file) => !file.exists).length,
modifiedReferenceCount: references.filter((file) => file.modified).length,
referenceConflictCount: references.filter((file) => file.conflict).length,
metadata,
manifest: {
exists: manifest.exists,
valid: manifest.valid,
path: manifest.path,
error: manifest.error,
},
backupCount: backups.length,
latestBackup: backups[0] || null,
canInstall: !installed && !references.some((file) => file.conflict),
canUpdate: updateAvailable && !references.some((file) => file.conflict),
};
}
function getCocosMcpProjectSkillState(projectPath, options = {}) {
return getBuiltInProjectSkillState(projectPath, { ...options, skillName: COCOS_MCP_SKILL_NAME });
}
function getCocosUiProjectSkillState(projectPath, options = {}) {
return getBuiltInProjectSkillState(projectPath, { ...options, skillName: COCOS_UI_SKILL_NAME });
}
function getProjectSkillsState(projectPath, options = {}) {
const platform = getSkillPlatform(options);
const platforms = SKILL_PLATFORMS.map((item) => ({ ...item }));
if (!platform) return { projectPath: path.resolve(projectPath), clientId: options.clientId, supported: false, platforms, builtIns: [], skills: [], backups: [] };
projectPath = getSkillProjectPath(projectPath, options);
try {
return readProjectSkillsState(projectPath, options, platform, platforms);
} catch (error) {
// A broken or unsafe directory for one client must not break every panel.
// Mutations still use the strict path checks and cannot install through it.
return {
projectPath: path.resolve(projectPath),
clientId: platform.id,
clientName: platform.name,
supported: true,
platforms,
error: error.message,
builtIns: [],
skills: [],
backups: [],
};
}
}
function readProjectSkillsState(projectPath, options, platform, platforms) {
const instructions = listProjectInstructions(projectPath, options);
const builtIns = BUILT_IN_PROJECT_SKILLS.map((definition) => (
getBuiltInProjectSkillState(projectPath, { ...options, skillName: definition.skillName })
));
const builtInByPath = new Map(builtIns.map((skill) => [skill.path, skill]));
return {
projectPath: path.resolve(projectPath),
clientId: platform.id,
clientName: platform.name,
supported: true,
platforms,
skillRoot: resolveProjectPath(projectPath, platform.directory),
builtIns,
official: builtIns[0],
skills: instructions.skills.map((skill) => {
const builtIn = builtInByPath.get(skill.path);
return {
...skill,
title: builtIn ? builtIn.title : skill.title,
description: builtIn ? builtIn.description : skill.description,
builtIn: Boolean(builtIn),
builtInId: builtIn ? builtIn.skillId : '',
official: Boolean(builtIn),
};
}),
backups: builtIns.flatMap((skill) => (
listProjectSkillBackups(projectPath, skill.skillName, options).map((backup) => ({
...backup,
skillName: skill.skillName,
}))
)),
};
}
function buildLineDiff(before, after, options = {}) {
const beforeLines = String(before || '').replace(/\r\n/g, '\n').split('\n');
const afterLines = String(after || '').replace(/\r\n/g, '\n').split('\n');
const maxLines = options.maxLines || 1000;
if (beforeLines.length > maxLines || afterLines.length > maxLines) {
return {
text: 'Diff preview is unavailable because the skill exceeds the safe line limit.',
added: afterLines.length,
removed: beforeLines.length,
};
}
const rows = beforeLines.length + 1;
const columns = afterLines.length + 1;
const table = Array.from({ length: rows }, () => new Uint16Array(columns));
for (let left = beforeLines.length - 1; left >= 0; left -= 1) {
for (let right = afterLines.length - 1; right >= 0; right -= 1) {
table[left][right] = beforeLines[left] === afterLines[right]
? table[left + 1][right + 1] + 1
: Math.max(table[left + 1][right], table[left][right + 1]);
}
}
const templateVersion = Number(options.templateVersion || COCOS_MCP_SKILL_TEMPLATE_VERSION);
const relativePath = options.relativePath || 'SKILL.md';
const output = [`--- installed/${relativePath}`, `+++ template-v${templateVersion}/${relativePath}`, '@@'];
let left = 0;
let right = 0;
let added = 0;
let removed = 0;
while (left < beforeLines.length && right < afterLines.length) {
if (beforeLines[left] === afterLines[right]) {
output.push(` ${beforeLines[left]}`);
left += 1;
right += 1;
} else if (table[left + 1][right] >= table[left][right + 1]) {
output.push(`- ${beforeLines[left]}`);
removed += 1;
left += 1;
} else {
output.push(`+ ${afterLines[right]}`);
added += 1;
right += 1;
}
}
while (left < beforeLines.length) {
output.push(`- ${beforeLines[left]}`);
removed += 1;
left += 1;
}
while (right < afterLines.length) {
output.push(`+ ${afterLines[right]}`);
added += 1;
right += 1;
}
return { text: output.join('\n'), added, removed };
}
function previewBuiltInProjectSkillUpdate(projectPath, options = {}) {
projectPath = getSkillProjectPath(projectPath, options);
const definition = definitionFromOptions(options);
const state = getBuiltInProjectSkillState(projectPath, options);
const currentContent = state.installed
? fs.readFileSync(state.absolutePath, 'utf8')
: '';
const templateContent = definition.buildContent({ skillName: state.skillName });
const diff = buildLineDiff(currentContent, templateContent, {
...options,
templateVersion: state.templateVersion,
});
const manifest = readManagedSkillManifest(projectPath, state.skillName, options);
const referenceDiffs = referenceSnapshots(projectPath, state.skillName, definition, options, manifest.valid ? manifest.data : {})
.filter((file) => !file.current)
.map((file) => ({
path: file.path,
status: file.status,
...buildLineDiff(file.content || '', file.templateContent, { ...options, relativePath: file.relativePath, templateVersion: state.templateVersion }),
}));
return {
skillId: state.skillId,
skillName: state.skillName,
title: state.title,
path: state.path,
legacyPath: state.legacyPath,
status: state.status,
modified: state.modified,
templateVersion: state.templateVersion,
installedTemplateVersion: state.installedTemplateVersion,
references: state.references,
addedLines: diff.added + referenceDiffs.reduce((sum, file) => sum + file.added, 0),
removedLines: diff.removed + referenceDiffs.reduce((sum, file) => sum + file.removed, 0),
diff: [diff.text, ...referenceDiffs.map((file) => file.text)].join('\n\n'),
};
}
function previewCocosMcpProjectSkillUpdate(projectPath, options = {}) {
return previewBuiltInProjectSkillUpdate(projectPath, {
...options,
skillName: options.skillName || COCOS_MCP_SKILL_NAME,
});
}
function updateBuiltInProjectSkill(projectPath, options = {}) {
projectPath = getSkillProjectPath(projectPath, options);
const definition = definitionFromOptions(options);
const state = getBuiltInProjectSkillState(projectPath, options);
const content = definition.buildContent({ ...options, skillName: state.skillName });
if (state.current && sha256Text(content) === state.currentHash) {
return {
installed: false,
updated: false,
alreadyCurrent: true,
backup: null,
state,
};
}
if (state.installed && options.onlyIfMissing === true) {
return { installed: false, updated: false, skipped: true, backup: null, state };
}
if (state.referenceConflictCount) {
throw new Error(`A reference destination for '${state.skillName}' is user-owned. Move or rename the conflicting file before installation; it will not be overwritten.`);
}
if (state.modified && options.allowModified !== true) {
throw new Error(`The built-in project skill '${state.skillName}' has local modifications. Confirm a backup update before replacing it.`);
}
const currentContent = state.installed ? fs.readFileSync(state.absolutePath, 'utf8') : null;
if (state.installed && sha256Text(currentContent) !== state.currentHash) throw new Error('Skill changed while preparing the update. Refresh and review it again.');
const manifestState = readManagedSkillManifest(projectPath, state.skillName, { ...options, legacy: Boolean(state.legacyPath) });
const references = referenceSnapshots(projectPath, state.skillName, definition, options, manifestState.valid ? manifestState.data : {});
if (references.some((file, index) => file.currentHash !== state.references[index].currentHash || file.conflict)) {
throw new Error('Skill references changed while preparing the update. Refresh and review them again.');
}
const manifestPath = resolveProjectPath(projectPath, getManifestRelativePath(state.skillName, options));
const manifestContent = readOptionalText(manifestPath);
// Resolve every destination before any write; a late conflict/symlink must not partially install SKILL.md.
resolveProjectPath(projectPath, state.path);
for (const file of references) resolveReferencePath(projectPath, file.path);
let backup = null;
if (state.installed) {
backup = createProjectSkillBackup(
projectPath,
currentContent,
{ ...options, skillName: state.skillName, label: 'before-update', bundle: {
files: Object.fromEntries(references.map((file) => [file.relativePath, file.content])),
manifest: manifestContent,
} }
);
}
const write = writeProjectInstruction(projectPath, {
target: state.path,
content,
expectedContent: state.legacyPath ? null : currentContent,
overwrite: true,
});
for (const file of references) {
if (file.current) continue;
resolveReferencePath(projectPath, file.path);
writeProjectInstruction(projectPath, {
target: file.path, content: file.templateContent, expectedContent: file.content, overwrite: true,
});
}
const manifest = writeManagedSkillManifest(projectPath, content, {
...options,
skillId: state.skillId,
skillName: state.skillName,
templateVersion: state.templateVersion,
extensionVersion: options.extensionVersion,
referenceFiles: references.map((file) => ({ path: file.relativePath, content: file.templateContent })),
expectedManifestContent: manifestContent,
});
return {
installed: !state.installed,
updated: state.installed,
alreadyCurrent: false,
backup,
write,
manifest: manifest.path,
references: references.map((file) => file.path),
state: getBuiltInProjectSkillState(projectPath, options),
};
}
function updateCocosMcpProjectSkill(projectPath, options = {}) {
return updateBuiltInProjectSkill(projectPath, {
...options,
skillName: options.skillName || COCOS_MCP_SKILL_NAME,
});
}
function restoreLatestBuiltInProjectSkillBackup(projectPath, options = {}) {
projectPath = getSkillProjectPath(projectPath, options);
const state = getBuiltInProjectSkillState(projectPath, options);
const backups = listProjectSkillBackups(projectPath, state.skillName, options);
const selected = options.backupPath
? backups.find((backup) => backup.path === options.backupPath)
: backups[0];
if (!selected) {
throw new Error(`No project skill backup is available to restore for '${state.skillName}'.`);
}
const sourcePath = resolveProjectPath(projectPath, selected.path);
const sourceContent = fs.readFileSync(sourcePath, 'utf8');
const currentContent = state.installed ? fs.readFileSync(state.absolutePath, 'utf8') : null;
if (state.installed && sha256Text(currentContent) !== state.currentHash) throw new Error('Skill changed while preparing the restore. Review the backup again.');
const definition = definitionFromOptions(options);
const manifestState = readManagedSkillManifest(projectPath, state.skillName, options);
const references = referenceSnapshots(projectPath, state.skillName, definition, options, manifestState.valid ? manifestState.data : {});
const manifestPath = getManifestRelativePath(state.skillName, options);
const currentManifest = readOptionalText(resolveProjectPath(projectPath, manifestPath));
const sidecarPath = resolveProjectPath(projectPath, `${selected.path}.files.json`);
let bundle = null;
if (fs.existsSync(sidecarPath)) {
const parsed = readJsonFile(sidecarPath);
bundle = parsed.valid && parsed.value;
if (!bundle || bundle.schemaVersion !== 1 || !bundle.files || typeof bundle.files !== 'object' || Array.isArray(bundle.files) ||
!(bundle.manifest === null || typeof bundle.manifest === 'string')) {
throw new Error('The skill reference backup is invalid; no files were restored.');
}
for (const [relativePath, content] of Object.entries(bundle.files)) {
const reference = references.find((file) => file.relativePath === relativePath);
if (!reference || !(content === null || typeof content === 'string') || content && content.length > 256 * 1024) {
throw new Error('The skill reference backup contains an unsupported path or content.');
}
if (reference.conflict) throw new Error(`Cannot restore over a user-owned reference: ${reference.path}`);
}
if (bundle.manifest === null && currentManifest !== null &&
(!manifestState.valid || manifestState.data.skillName !== state.skillName)) {
throw new Error('Cannot remove an unrecognized skill manifest while restoring a backup.');
}
}
let currentBackup = null;
if (state.installed) {
currentBackup = createProjectSkillBackup(
projectPath,
currentContent,
{ ...options, skillName: state.skillName, label: 'before-restore', bundle: {
files: Object.fromEntries(references.map((file) => [file.relativePath, file.content])),
manifest: currentManifest,
} }
);
}
const write = writeProjectInstruction(projectPath, {
target: state.path,
content: sourceContent,
expectedContent: state.legacyPath ? null : currentContent,
overwrite: true,
});
if (bundle) {
for (const [relativePath, content] of Object.entries(bundle.files)) {
const file = references.find((item) => item.relativePath === relativePath);
const destination = resolveReferencePath(projectPath, file.path);
if (content === null) {
if (file.content === null) continue;
if (readOptionalText(destination) !== file.content) throw new Error('Skill reference changed while restoring; review the backup again.');
// Remove only this recorded, managed file; unrelated references remain untouched.
fs.unlinkSync(destination);
} else {
writeProjectInstruction(projectPath, { target: file.path, content, expectedContent: file.content, overwrite: true });
}
}
if (bundle.manifest === null) {
if (currentManifest !== null) {
const destination = resolveProjectPath(projectPath, manifestPath);
if (readOptionalText(destination) !== currentManifest) throw new Error('Skill manifest changed while restoring.');
fs.unlinkSync(destination);
}
} else {
writeProjectInstruction(projectPath, { target: manifestPath, content: bundle.manifest, expectedContent: currentManifest, overwrite: true });
}
}
return {
restored: true,
source: selected,
currentBackup,
write,
state: getBuiltInProjectSkillState(projectPath, options),
};
}
function restoreLatestCocosMcpProjectSkillBackup(projectPath, options = {}) {
return restoreLatestBuiltInProjectSkillBackup(projectPath, {
...options,
skillName: options.skillName || COCOS_MCP_SKILL_NAME,
});
}
module.exports = {
BACKUP_ROOT,
BUILT_IN_PROJECT_SKILLS,
COCOS_MCP_SKILL_TEMPLATE_VERSION,
COCOS_UI_SKILL_TEMPLATE_VERSION,
MANIFEST_FILE_NAME,
buildLineDiff,
createProjectSkillBackup,
getBuiltInProjectSkillDefinitions,
getBuiltInProjectSkillState,
getCocosMcpProjectSkillState,
getCocosUiProjectSkillState,
getManifestRelativePath,
getProjectSkillsState,
getSkillRelativePath,
listProjectSkillBackups,
previewBuiltInProjectSkillUpdate,
previewCocosMcpProjectSkillUpdate,
readManagedSkillManifest,
resolveBuiltInProjectSkillDefinition,
restoreLatestBuiltInProjectSkillBackup,
restoreLatestCocosMcpProjectSkillBackup,
sha256Text,
updateBuiltInProjectSkill,
updateCocosMcpProjectSkill,
writeManagedSkillManifest,
};
+105
View File
@@ -0,0 +1,105 @@
'use strict';
const { loadProjectPrompts, interpolatePrompt } = require('./project-prompts');
const BUILT_IN_ARGUMENTS = {
fix_script_errors: ['touched_paths'],
create_playable_prototype: ['idea'],
scene_validation: ['focus'],
auto_wire_scene: ['target', 'component_type'],
};
class PromptProvider {
constructor(getRuntimeContext, options = {}) {
this.getRuntimeContext = getRuntimeContext;
this.onWarning = options.onWarning || (() => {});
this.reportedWarnings = new Set();
}
projectPrompts() {
const loaded = loadProjectPrompts(this.getRuntimeContext().projectPath, Object.keys(BUILT_IN_ARGUMENTS));
const warnings = new Set(loaded.warnings);
for (const warning of warnings) {
if (!this.reportedWarnings.has(warning)) this.onWarning(`mcp-prompts: ${warning}`);
}
this.reportedWarnings = warnings;
return loaded.prompts;
}
listPrompts() {
const { projectName } = this.getRuntimeContext();
return [
this.createPrompt('fix_script_errors', `In core mode, default to execute_javascript first and only switch to specialist tools when they are clearly better for diagnostics, screenshots, or resource reads in '${projectName}'.`),
this.createPrompt('create_playable_prototype', `In core mode, default to execute_javascript first and only switch to specialist tools when they are clearly better for screenshots, asset lookup, or scene opening in '${projectName}'.`),
this.createPrompt('scene_validation', `In core mode, default to execute_javascript first and only switch to specialist tools when they are clearly better for screenshots, diagnostics, or structured resource reads in '${projectName}'.`),
this.createPrompt('auto_wire_scene', `In core mode, default to execute_javascript first and only switch to specialist tools when they are clearly better for asset lookup, scene opening, diagnostics, or screenshots in '${projectName}'.`),
...this.projectPrompts().map(({ name, description, arguments: args }) => ({ name, description, arguments: args })),
];
}
getPrompt(name, args = {}) {
const invalid = (message) => { const error = new Error(message); error.code = -32602; throw error; };
const builtin = Object.prototype.hasOwnProperty.call(BUILT_IN_ARGUMENTS, name);
const projectPrompt = builtin ? null : this.projectPrompts().find((prompt) => prompt.name === name);
if (!builtin && !projectPrompt) invalid(`Prompt not found: ${name}`);
const declarations = builtin ? this.createPrompt(name, '').arguments : projectPrompt.arguments;
if (!args || typeof args !== 'object' || Array.isArray(args)) invalid('Prompt arguments must be an object of strings.');
const declared = new Set(declarations.map((arg) => arg.name));
for (const [key, value] of Object.entries(args)) {
if (!declared.has(key)) invalid(`Unknown argument for '${name}': ${key}`);
if (typeof value !== 'string') invalid(`Prompt argument '${key}' must be a string.`);
if (value.length > 65536) invalid(`Prompt argument '${key}' exceeds 65536 characters.`);
}
for (const arg of declarations) {
if (arg.required && (!Object.prototype.hasOwnProperty.call(args, arg.name) || !args[arg.name].trim())) invalid(`Missing required argument: ${arg.name}`);
}
const { projectName, projectPath } = this.getRuntimeContext();
let text = '';
switch (name) {
case 'fix_script_errors':
text = 'In `core` mode, assume `execute_javascript` is the default first tool. Start with `context="editor"` for diagnosis, local file edits, asset-db workflows, and orchestration; switch to `context="scene"` only when runtime or scene state must be inspected directly. Only use specialist tools when they are strictly better primitives: `run_script_diagnostics` and `get_script_diagnostic_context` for TypeScript errors, `resources/read` for structured project context, and screenshot tools for visual verification. Avoid hopping across many narrow tools when one `execute_javascript` call can inspect, decide, and act. Patch the smallest safe regions, refresh assets if needed, and verify the project returns to a healthy state.';
break;
case 'create_playable_prototype':
text = 'In `core` mode, treat `execute_javascript` as the primary tool for almost the entire workflow. Use `context="scene"` for node, component, UI, and runtime orchestration, and use `context="editor"` only when editor-side automation, file work, or asset-db access is required. Reach for specialist tools only when they provide a clearly better primitive: `open_scene` to load a scene, asset tools when you need exact asset identification, and screenshot tools when you need visual proof. Build the prototype in a few high-leverage `execute_javascript` steps instead of many tiny tool calls, then verify with runtime state and screenshots.';
break;
case 'scene_validation':
text = 'In `core` mode, start with `execute_javascript`, usually with `context="scene"`, and keep it as the main tool unless a specialist tool is clearly superior. Use it to inspect hierarchy, nodes, components, prefab instances, cameras, animations, and runtime state in one place. Only switch to specialist tools when you specifically need a screenshot, a structured resource read, or TypeScript diagnostics. Prefer a small number of high-signal validation steps over broad tool hopping.';
break;
case 'auto_wire_scene':
text = 'In `core` mode, begin with `execute_javascript` and assume it will handle nearly all inspection and repair. Use `context="scene"` for hierarchy, node, component, and UI wiring repair, and use `context="editor"` only when file edits, asset-db access, or editor-side orchestration is required. Switch to specialist tools only for exact asset lookup, scene opening, diagnostics, or screenshots. Inspect the target structure, identify missing references or expected children, and repair them with the smallest safe change rather than scattering work across many narrow tools.';
break;
default:
text = interpolatePrompt(projectPrompt.body, args, declarations);
break;
}
const context = builtin ? Object.entries(args).map(([key, value]) => `${key}: ${value}`).join('\n') : '';
if (name === 'scene_validation') text += '\nThis workflow is read-only unless the user also requests repairs.';
const fullText = `Target Cocos project: ${projectName}\nProject path: ${projectPath}\n${context}\n${text}`;
return {
description: fullText,
messages: [
{
role: 'user',
content: {
type: 'text',
text: fullText,
},
},
],
};
}
createPrompt(name, description) {
return {
name,
description,
arguments: (BUILT_IN_ARGUMENTS[name] || []).map((key) => ({ name: key, description: key, required: false })),
};
}
}
module.exports = {
PromptProvider,
};
+293
View File
@@ -0,0 +1,293 @@
'use strict';
const fs = require('fs');
const path = require('path');
const { getCurrentSelection, queryAssetInfo, queryAssetMeta } = require('./assets');
const { runScriptDiagnostics } = require('./diagnostics');
const { getRecentProjectLogs } = require('./logs');
const { resolveProjectPath } = require('./path-safety');
function createResource(uri, name, description) {
return { uri, name, description, mimeType: 'text/plain' };
}
function createTemplate(uriTemplate, name, description) {
return { uriTemplate, name, description, mimeType: 'text/plain' };
}
function truncate(text, limit = 12000) {
if (typeof text !== 'string') {
return text;
}
if (text.length <= limit) {
return text;
}
return `${text.slice(0, limit)}\n... (truncated)`;
}
function toText(value) {
if (typeof value === 'string') {
return value;
}
return JSON.stringify(value, null, 2);
}
function summarizeSelection() {
if (!global.Editor || !Editor.Selection || typeof Editor.Selection.getSelected !== 'function') {
return 'Selection API is unavailable in this Cocos environment.';
}
try {
const selectedNode = Editor.Selection.getSelected('node');
const selectedAsset = Editor.Selection.getSelected('asset');
return [
`Selected node: ${selectedNode || '(none)'}`,
`Selected asset: ${selectedAsset || '(none)'}`,
].join('\n');
} catch (error) {
return `Failed to inspect current selection: ${error.message}`;
}
}
class ResourceProvider {
constructor(getRuntimeContext, sceneBridge, interactionLog, runtimeLog) {
this.getRuntimeContext = getRuntimeContext;
this.sceneBridge = sceneBridge;
this.interactionLog = interactionLog;
this.runtimeLog = runtimeLog;
}
listResources() {
const { projectName } = this.getRuntimeContext();
return [
createResource('cocos://project/context', `${projectName} Project Context`, 'Live Cocos project context summary.'),
createResource('cocos://project/summary', `${projectName} Project Summary`, 'Project path, folder summary, and asset overview.'),
createResource('cocos://scene/active', `${projectName} Active Scene`, 'Summary of the active Cocos scene.'),
createResource('cocos://scene/current', `${projectName} Current Scene`, 'Alias of the active Cocos scene summary.'),
createResource('cocos://selection/current', `${projectName} Current Selection`, 'Summary of the current editor selection.'),
createResource('cocos://selection/asset', `${projectName} Selected Asset`, 'Details for the currently selected asset.'),
createResource('cocos://errors/scripts', `${projectName} Script Diagnostics`, 'Latest TypeScript diagnostic summary for the project.'),
createResource('cocos://logs/editor', `${projectName} Editor Logs`, 'Recent MCP runtime logs and tool interaction history.'),
createResource('cocos://logs/project', `${projectName} Project Logs`, 'Recent tails from common project log files.'),
createResource('cocos://mcp/interactions', `${projectName} MCP Interactions`, 'Recent MCP tool interaction summaries.'),
];
}
listResourceTemplates() {
return [
createTemplate('cocos://scene/node/{path}', 'Scene Node', 'Inspect a scene node by hierarchy path.'),
createTemplate('cocos://asset/path/{relative_path}', 'Asset By Path', 'Read a script or text asset by project-relative path.'),
createTemplate('cocos://asset/info/{uuid_or_path}', 'Asset Info', 'Inspect an asset by uuid, db url, or path.'),
];
}
async readResource(uri) {
const text = await this.resolveResourceText(uri);
return {
contents: [
{
uri,
mimeType: 'text/plain',
text,
},
],
};
}
async resolveResourceText(uri) {
const { projectName, projectPath, cocosVersion, version, config } = this.getRuntimeContext();
switch (uri) {
case 'cocos://project/context':
return [
'Funplay Cocos MCP Project Context',
`Project: ${projectName}`,
`Project Path: ${projectPath}`,
`Cocos Creator: ${cocosVersion}`,
`Extension Version: ${version}`,
`Tool Profile: ${config.toolProfile}`,
`Server: http://${config.host}:${config.port}/`,
'',
'Selection',
summarizeSelection(),
'',
'Active Scene',
await this.safeSceneCall('getSceneInfo', { maxDepth: 2 }),
].join('\n');
case 'cocos://project/summary':
return this.buildProjectSummary(projectPath, cocosVersion, version);
case 'cocos://scene/active':
case 'cocos://scene/current':
return await this.safeSceneCall('getSceneInfo', { maxDepth: 3 });
case 'cocos://selection/current':
return summarizeSelection();
case 'cocos://selection/asset':
return await this.getSelectedAssetText();
case 'cocos://errors/scripts':
return await this.getScriptDiagnosticsText(projectPath);
case 'cocos://logs/editor':
return this.getEditorLogsText();
case 'cocos://logs/project':
return this.getProjectLogsText(projectPath);
case 'cocos://mcp/interactions':
return this.interactionLog.summary();
default:
break;
}
if (uri.startsWith('cocos://scene/node/')) {
const nodePath = decodeURIComponent(uri.slice('cocos://scene/node/'.length));
return await this.safeSceneCall('inspectNode', { path: nodePath });
}
if (uri.startsWith('cocos://asset/path/')) {
const relativePath = decodeURIComponent(uri.slice('cocos://asset/path/'.length));
return this.readAssetByPath(relativePath);
}
if (uri.startsWith('cocos://asset/info/')) {
const uuidOrPath = decodeURIComponent(uri.slice('cocos://asset/info/'.length));
return await this.getAssetInfoText(uuidOrPath);
}
return `Resource not found: ${uri}`;
}
buildProjectSummary(projectPath, cocosVersion, version) {
const topLevel = fs.existsSync(projectPath)
? fs
.readdirSync(projectPath, { withFileTypes: true })
.filter((entry) => entry.isDirectory())
.map((entry) => entry.name)
.sort((left, right) => left.localeCompare(right))
: [];
const assetsDir = path.join(projectPath, 'assets');
const scriptCount = this.countFiles(assetsDir, ['.ts', '.js']);
const prefabCount = this.countFiles(assetsDir, ['.prefab']);
const sceneCount = this.countFiles(assetsDir, ['.scene']);
return [
'Project Summary',
`Project Root: ${projectPath}`,
`Assets Path: ${assetsDir}`,
`Cocos Creator: ${cocosVersion}`,
`Extension Version: ${version}`,
`Scripts: ${scriptCount}`,
`Prefabs: ${prefabCount}`,
`Scenes: ${sceneCount}`,
'',
`Top-Level Directories (${topLevel.length})`,
...topLevel.map((name) => `- ${name}`),
].join('\n');
}
countFiles(rootDir, extensions) {
if (!fs.existsSync(rootDir)) {
return 0;
}
let count = 0;
const stack = [rootDir];
while (stack.length) {
const current = stack.pop();
const entries = fs.readdirSync(current, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(current, entry.name);
if (entry.isDirectory()) {
stack.push(fullPath);
continue;
}
if (extensions.includes(path.extname(entry.name).toLowerCase())) {
count += 1;
}
}
}
return count;
}
readAssetByPath(relativePath) {
const { projectPath } = this.getRuntimeContext();
const fullPath = resolveProjectPath(projectPath, relativePath);
if (!fs.existsSync(fullPath)) {
return `Asset not found: ${relativePath}`;
}
return truncate(`[${relativePath}]\n${fs.readFileSync(fullPath, 'utf8')}`);
}
async safeSceneCall(method, payload) {
try {
const result = await this.sceneBridge.call(method, payload);
return toText(result);
} catch (error) {
return `Scene bridge error (${method}): ${error.message}`;
}
}
async getSelectedAssetText() {
try {
const selection = getCurrentSelection();
if (!selection.asset) {
return 'No asset is currently selected.';
}
return await this.getAssetInfoText(selection.asset);
} catch (error) {
return `Selected asset lookup failed: ${error.message}`;
}
}
async getAssetInfoText(uuidOrPath) {
try {
const info = await queryAssetInfo(uuidOrPath);
const meta = await queryAssetMeta(uuidOrPath).catch(() => null);
return JSON.stringify({ info, meta }, null, 2);
} catch (error) {
return `Asset lookup failed: ${error.message}`;
}
}
async getScriptDiagnosticsText(projectPath) {
try {
const result = await runScriptDiagnostics(projectPath);
return JSON.stringify(result, null, 2);
} catch (error) {
return `Script diagnostics failed: ${error.message}`;
}
}
getEditorLogsText() {
return [
'MCP Runtime Logs',
this.runtimeLog && typeof this.runtimeLog.summary === 'function'
? this.runtimeLog.summary(80)
: 'Runtime log is unavailable.',
'',
'MCP Tool Interactions',
this.interactionLog && typeof this.interactionLog.summary === 'function'
? this.interactionLog.summary(80)
: 'Interaction log is unavailable.',
].join('\n');
}
getProjectLogsText(projectPath) {
const logs = getRecentProjectLogs(projectPath, { limit: 10, lines: 100 });
if (!logs.length) {
return 'No project log files found in common project log directories.';
}
return logs
.map((log) => [
`# ${log.path}`,
`mtime: ${log.mtime}`,
`size: ${log.size}`,
'',
log.text,
].join('\n'))
.join('\n\n---\n\n');
}
}
module.exports = {
ResourceProvider,
};
+46
View File
@@ -0,0 +1,46 @@
'use strict';
class RuntimeLog {
constructor(limit = 200) {
this.limit = Math.max(10, Number(limit) || 200);
this.entries = [];
}
add(level, message, details) {
this.entries.unshift({
level: String(level || 'info'),
message: String(message || ''),
details: details === undefined ? null : details,
timestamp: new Date().toISOString(),
});
if (this.entries.length > this.limit) {
this.entries.length = this.limit;
}
}
list(limit = 50) {
return this.entries.slice(0, Math.max(1, Number(limit) || 50));
}
clear() {
const count = this.entries.length;
this.entries.length = 0;
return count;
}
summary(limit = 50) {
const items = this.list(limit);
if (!items.length) {
return 'No MCP runtime logs recorded yet.';
}
return items
.map((entry) => `[${entry.timestamp}] ${entry.level.toUpperCase()} ${entry.message}`)
.join('\n');
}
}
module.exports = {
RuntimeLog,
};
+129
View File
@@ -0,0 +1,129 @@
'use strict';
const fs = require('fs');
const path = require('path');
const { queryAssetInfo } = require('./assets');
const { resolveProjectPath } = require('./path-safety');
function requestEditorMessage(channel, method, ...args) {
if (!global.Editor || !Editor.Message || typeof Editor.Message.request !== 'function') {
throw new Error('Editor.Message.request is unavailable in the Cocos extension host.');
}
return Editor.Message.request(channel, method, ...args);
}
function normalizeSceneTarget(projectPath, target) {
const raw = String(target || '').trim().replace(/\\/g, '/');
if (!raw) {
throw new Error('target is required.');
}
let relative = raw;
if (relative.startsWith('db://assets/')) {
relative = relative.slice('db://'.length);
} else if (relative.startsWith('/assets/')) {
relative = relative.slice(1);
} else if (!relative.startsWith('assets/')) {
relative = `assets/${relative}`;
}
if (!relative.endsWith('.scene')) {
relative = `${relative}.scene`;
}
const filePath = resolveProjectPath(projectPath, relative);
const assetsRoot = path.join(projectPath, 'assets');
const relativeToAssets = path.relative(assetsRoot, filePath);
if (relativeToAssets.startsWith('..') || path.isAbsolute(relativeToAssets)) {
throw new Error('target must be inside the Cocos assets directory.');
}
const projectRelative = path.relative(projectPath, filePath).replace(/\\/g, '/');
return {
filePath,
projectRelative,
dbUrl: `db://${projectRelative}`,
sceneName: path.basename(filePath, '.scene'),
};
}
async function queryAssetInfoOptional(target) {
try {
return await queryAssetInfo(target);
} catch (error) {
return null;
}
}
async function saveSceneContent(projectPath, options = {}) {
const target = normalizeSceneTarget(projectPath, options.target);
const content = String(options.content || '');
if (!content) {
throw new Error('content is required.');
}
const parsed = JSON.parse(content);
if (!Array.isArray(parsed) || !parsed.some((entry) => entry && entry.__type__ === 'cc.SceneAsset')) {
throw new Error('content must contain a serialized cc.SceneAsset.');
}
const existed = fs.existsSync(target.filePath);
if (existed && options.overwrite !== true) {
throw new Error(`Target scene already exists: ${target.projectRelative}`);
}
fs.mkdirSync(path.dirname(target.filePath), { recursive: true });
let method = 'fs-write';
let result;
if (global.Editor && Editor.Message && typeof Editor.Message.request === 'function') {
if (existed) {
try {
result = await requestEditorMessage('asset-db', 'save-asset', target.dbUrl, content);
method = 'asset-db:save-asset';
if (!fs.existsSync(target.filePath) || fs.readFileSync(target.filePath, 'utf8').trimEnd() !== content.trimEnd()) {
fs.writeFileSync(target.filePath, content.endsWith('\n') ? content : `${content}\n`, 'utf8');
}
} catch (error) {
fs.writeFileSync(target.filePath, content.endsWith('\n') ? content : `${content}\n`, 'utf8');
result = { fallbackReason: error.message };
}
} else {
try {
result = await requestEditorMessage('asset-db', 'create-asset', target.dbUrl, content);
method = 'asset-db:create-asset';
} catch (error) {
if (fs.existsSync(target.filePath)) {
result = { fallbackReason: error.message, fileCreated: true };
} else {
throw error;
}
}
}
} else {
fs.writeFileSync(target.filePath, content.endsWith('\n') ? content : `${content}\n`, 'utf8');
}
const fileExists = fs.existsSync(target.filePath);
const info = await queryAssetInfoOptional(target.dbUrl);
if (!fileExists && !info) {
throw new Error(`Scene was not created: ${target.projectRelative}`);
}
return {
created: !existed,
overwritten: existed && options.overwrite === true,
method,
result,
dbUrl: target.dbUrl,
path: target.projectRelative,
sceneName: target.sceneName,
fileExists,
info,
};
}
module.exports = {
normalizeSceneTarget,
saveSceneContent,
};
+130
View File
@@ -0,0 +1,130 @@
'use strict';
const fs = require('fs');
const os = require('os');
const path = require('path');
const { execFile } = require('child_process');
const crypto = require('crypto');
const { resolveProjectFilePath } = require('./path-safety');
const electronTools = require('./electron-tools');
const { pngDimensions, readVisualState, registerCapture } = require('./visual-coordinates');
function ensureDir(dirPath) {
fs.mkdirSync(dirPath, { recursive: true });
}
function screenshotPath(projectPath, options, kind) {
const outputDir = resolveProjectFilePath(projectPath, 'temp/mcp-captures');
const fileName = options.fileName || `${kind}-${Date.now()}-${crypto.randomBytes(4).toString('hex')}.png`;
if (typeof fileName !== 'string' || fileName.length > 180 || /[\\/\0<>:"|?*\r\n]/.test(fileName) || !fileName.toLowerCase().endsWith('.png') || fileName === '.png') {
throw new Error('fileName must be a plain PNG filename under temp/mcp-captures.');
}
ensureDir(outputDir);
return checkedScreenshotPath(projectPath, path.join(outputDir, fileName));
}
function checkedScreenshotPath(projectPath, destination) {
const filePath = resolveProjectFilePath(projectPath, destination);
try {
if (fs.lstatSync(filePath).isSymbolicLink()) throw new Error('Screenshot destination cannot be a symbolic link.');
} catch (error) { if (error.code !== 'ENOENT') throw error; }
return filePath;
}
function exec(file, args) {
return new Promise((resolve, reject) => {
execFile(file, args, { maxBuffer: 8 * 1024 * 1024 }, (error, stdout, stderr) => {
if (error) {
reject(new Error(stderr || stdout || error.message));
return;
}
resolve({ stdout, stderr });
});
});
}
async function captureDesktopScreenshot(projectPath, options = {}) {
const filePath = screenshotPath(projectPath, options, 'desktop');
if (process.platform === 'darwin') {
await exec('screencapture', ['-x', filePath]);
} else if (process.platform === 'win32') {
const script = `
Add-Type -AssemblyName System.Windows.Forms
Add-Type -AssemblyName System.Drawing
$bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen
$bitmap = New-Object System.Drawing.Bitmap $bounds.Width, $bounds.Height
$graphics = [System.Drawing.Graphics]::FromImage($bitmap)
$graphics.CopyFromScreen($bounds.Location, [System.Drawing.Point]::Empty, $bounds.Size)
$bitmap.Save('${filePath.replace(/'/g, "''")}', [System.Drawing.Imaging.ImageFormat]::Png)
$graphics.Dispose()
$bitmap.Dispose()
`;
await exec('powershell', ['-NoProfile', '-Command', script]);
} else {
try {
await exec('gnome-screenshot', ['-f', filePath]);
} catch (error) {
await exec('import', ['-window', 'root', filePath]);
}
}
const data = fs.readFileSync(filePath).toString('base64');
return {
filePath,
dataUri: `data:image/png;base64,${data}`,
size: fs.statSync(filePath).size,
platform: os.platform(),
imageSize: pngDimensions(fs.readFileSync(filePath)),
interactive: false,
reason: 'Desktop capture has no Electron window calibration.',
};
}
async function captureEditorWindowScreenshot(projectPath, options = {}) {
const filePath = screenshotPath(projectPath, options, 'editor');
const target = electronTools.pickWindow(options);
const before = await readVisualState(target, null, options.getContext);
const image = await target.capturePage();
const png = image.toPNG();
const after = await readVisualState(target, null, options.getContext);
const geometry = registerCapture(target, png, before, after, { ...options, panel: null, projectPath });
fs.writeFileSync(checkedScreenshotPath(projectPath, filePath), png);
return {
filePath,
dataUri: `data:image/png;base64,${png.toString('base64')}`,
size: png.length,
title: typeof target.getTitle === 'function' ? target.getTitle() : '',
captureId: geometry.captureId,
geometry,
};
}
async function capturePanelScreenshot(projectPath, options = {}) {
const panel = options.panel || 'scene';
const filePath = screenshotPath(projectPath, options, panel);
const target = electronTools.pickWindow(options);
const before = await readVisualState(target, panel, options.getContext);
const image = await target.capturePage(before.inputBounds);
const png = image.toPNG();
const after = await readVisualState(target, panel, options.getContext);
const geometry = registerCapture(target, png, before, after, { ...options, panel, projectPath });
fs.writeFileSync(checkedScreenshotPath(projectPath, filePath), png);
return {
filePath,
dataUri: `data:image/png;base64,${png.toString('base64')}`,
size: png.length,
title: typeof target.getTitle === 'function' ? target.getTitle() : '',
bounds: before.panelBounds,
captureId: geometry.captureId,
geometry,
};
}
module.exports = {
captureDesktopScreenshot,
captureEditorWindowScreenshot,
capturePanelScreenshot,
};
@@ -0,0 +1,63 @@
'use strict';
const { formatWithOptions, types } = require('util');
const { createActivityPreview, sanitizeActivityText } = require('./activity-preview');
const SCRIPT_EXECUTION_PACKET = 'funplay.script-execution.v1';
const LOG_LIMITS = { entries: 50, message: 1000, characters: 20000 };
// Inject a console into this invocation only. Never patch the process console:
// concurrent/nested scripts and ordinary project logging must stay independent.
async function captureScriptExecution(run, { context, targetConsole = console }) {
const logs = [];
let logsOmitted = 0;
let characters = 0;
let active = true;
const started = Date.now();
const methods = Object.create(null);
for (const method of ['log', 'info', 'warn', 'error', 'debug']) {
methods[method] = (...values) => {
if (active) {
if (logs.length >= LOG_LIMITS.entries || characters >= LOG_LIMITS.characters) {
logsOmitted++;
} else {
// No custom inspection or getter evaluation while retaining a log.
let message;
try {
const safe = values.slice(0, 20).map((value) => types.isNativeError(value)
? sanitizeActivityText(Object.getOwnPropertyDescriptor(value, 'message')?.value || 'Error')
: createActivityPreview(value));
message = sanitizeActivityText(formatWithOptions({
depth: 6, getters: false, customInspect: false, maxArrayLength: 12,
}, ...safe), Math.min(LOG_LIMITS.message, LOG_LIMITS.characters - characters));
} catch (error) { message = '[unavailable]'; }
logs.push({ level: method === 'log' ? 'info' : method, message });
characters += message.length;
}
}
// The MCP print preference only controls MCP's own logger, not user scripts.
if (typeof targetConsole[method] === 'function') targetConsole[method](...values);
};
}
const scriptConsole = new Proxy(methods, {
get(target, key) {
if (Object.prototype.hasOwnProperty.call(target, key)) return target[key];
const value = targetConsole[key];
return typeof value === 'function' ? value.bind(targetConsole) : value;
},
});
const packet = { kind: SCRIPT_EXECUTION_PACKET };
try {
packet.value = await run(scriptConsole);
} catch (error) {
let message = 'Script execution failed.';
try { message = String(error && error.message || error); } catch (_) { /* Keep the fallback. */ }
packet.error = { message };
} finally {
active = false;
packet.execution = { context, durationMs: Math.max(0, Date.now() - started), logs, logsOmitted };
}
return packet;
}
module.exports = { captureScriptExecution, SCRIPT_EXECUTION_PACKET, LOG_LIMITS };
+852
View File
@@ -0,0 +1,852 @@
'use strict';
const crypto = require('crypto');
const http = require('http');
const { safeStringify } = require('./utils');
const { CONTEXT_META_KEY, projectContext, projectEndpoint, serverUrl, requestRoute, contextError, withContextSchema } = require('./project-context');
const IMAGE_DATA_URI_PREFIX = 'data:image/png;base64,';
const LOG_PREFIX = '[Funplay Cocos MCP Server]';
const MAX_PORT_FALLBACK_ATTEMPTS = 20;
const MAX_REQUEST_BODY_BYTES = 4 * 1024 * 1024;
const MCP_PROTOCOL_VERSION = '2025-11-25';
const SUPPORTED_PROTOCOL_VERSIONS = [
MCP_PROTOCOL_VERSION,
'2025-06-18',
'2025-03-26',
'2024-11-05',
];
function responseHeaders(protocolVersion = MCP_PROTOCOL_VERSION, extraHeaders = {}) {
return {
'MCP-Protocol-Version': protocolVersion,
...extraHeaders,
};
}
function json(response, statusCode, payload, protocolVersion = MCP_PROTOCOL_VERSION, extraHeaders = {}) {
response.writeHead(statusCode, {
'Content-Type': 'application/json; charset=utf-8',
...responseHeaders(protocolVersion, extraHeaders),
});
response.end(JSON.stringify(payload));
}
function empty(response, statusCode, protocolVersion = MCP_PROTOCOL_VERSION, extraHeaders = {}) {
response.writeHead(statusCode, responseHeaders(protocolVersion, extraHeaders));
response.end();
}
function textContent(value, metadataText) {
if (typeof value === 'string' && value.startsWith(IMAGE_DATA_URI_PREFIX)) {
return [
{
type: 'image',
data: value.slice(IMAGE_DATA_URI_PREFIX.length),
mimeType: 'image/png',
},
{
type: 'text',
text: metadataText || 'Screenshot captured successfully.',
},
];
}
return [
{
type: 'text',
text: typeof value === 'string' ? value : JSON.stringify(value, null, 2),
},
];
}
function isStructuredValue(value) {
return value !== null && typeof value === 'object' && !Buffer.isBuffer(value);
}
function structuredContent(value) {
if (!isStructuredValue(value)) {
return null;
}
try {
return JSON.parse(safeStringify(value));
} catch (error) {
return null;
}
}
class McpServer {
constructor(options) {
this.config = options.config;
this.toolRegistry = options.toolRegistry;
this.resourceProvider = options.resourceProvider;
this.promptProvider = options.promptProvider;
this.interactionLog = options.interactionLog;
this.runtimeLog = options.runtimeLog;
this.serverName = options.serverName;
this.serverVersion = options.serverVersion;
this.projectName = options.projectName || '';
this.projectIdentity = options.projectIdentity || '';
this.context = projectContext({ projectIdentity: this.projectIdentity, projectPath: options.projectPath || this.config.projectPath,
instanceId: options.instanceId || crypto.randomBytes(16).toString('hex') });
this.getActiveContext = options.getActiveContext;
this.server = null;
this.attached = false;
this.attachedInfo = null;
this.actualPort = null;
this.portFallbackInfo = null;
this.negotiatedProtocolVersion = MCP_PROTOCOL_VERSION;
this.enableSessions = Boolean(this.config && this.config.enableSessions);
this.sessions = new Set();
}
isRunning() {
return Boolean(this.attached || (this.server && this.server.listening));
}
getPort() {
if (this.attached && this.actualPort) {
return this.actualPort;
}
if (this.server && typeof this.server.address === 'function') {
const address = this.server.address();
if (address && typeof address.port === 'number') {
return address.port;
}
}
return this.actualPort || this.config.port;
}
getRequestedPort() {
return this.config.port;
}
getPortFallbackInfo() {
return this.portFallbackInfo;
}
getAttachInfo() {
return this.attachedInfo;
}
getProjectContext() {
return this.attachedInfo && this.attachedInfo.context || this.context;
}
rejectContext(id, code) {
const response = this.createError(id, -32001, code);
response.error.data = { code,
recovery: 'Reconnect using this project\'s generated scoped URL, or independently verify initialize.funplay.context against the intended project and pass its expected_context. Do not automatically trust a token from an arbitrary responding server.' };
return response;
}
log(level, message) {
if (this.runtimeLog && typeof this.runtimeLog.add === 'function') {
this.runtimeLog.add(level, message);
}
if (this.config && this.config.enableConsoleLogging === false) return;
const output = `${LOG_PREFIX} ${message}`;
if (level === 'error') {
console.error(output);
} else if (level === 'warn') {
console.warn(output);
} else {
console.log(output);
}
}
async start() {
if (this.isRunning()) {
this.log('info', 'Start skipped: already running.');
return;
}
this.actualPort = null;
this.portFallbackInfo = null;
this.attached = false;
this.attachedInfo = null;
const requestHandler = async (request, response) => {
try {
const requestUrl = new URL(request.url || '/', 'http://localhost');
if (!this.isAllowedOrigin(request)) {
this.log('warn', `Rejected ${request.method} ${request.url}: invalid Origin header.`);
return json(response, 403, { error: 'Forbidden: invalid Origin header' }, this.negotiatedProtocolVersion);
}
const route = requestRoute(requestUrl.pathname, this.projectIdentity);
if (route.error) return json(response, route.status, { error: route.error }, this.negotiatedProtocolVersion);
if (request.method === 'GET' && route.kind === 'health') {
this.log('info', 'GET /health');
return json(response, 200, {
ok: true,
name: this.serverName,
version: this.serverVersion,
projectName: this.projectName,
projectIdentity: this.projectIdentity,
context: this.getProjectContext(),
}, this.negotiatedProtocolVersion);
}
if (request.method === 'GET' && route.kind === 'tools') {
this.log('info', 'GET /tools');
const includeCatalog = requestUrl.searchParams.get('catalog') === '1';
const tools = includeCatalog && typeof this.toolRegistry.listToolCatalog === 'function'
? this.toolRegistry.listToolCatalog()
: this.toolRegistry.listTools().map(withContextSchema);
const baseUrl = `http://${request.headers.host || `${this.config.host}:${this.getPort()}`}${route.scoped ? projectEndpoint(this.projectIdentity).replace(/\/$/, '') : ''}`;
return json(response, 200, {
ok: true,
name: this.serverName,
version: this.serverVersion,
count: tools.length,
context: this.getProjectContext(),
tools,
examples: {
health: `curl ${baseUrl}/health`,
tools: `curl ${baseUrl}/tools`,
catalog: `curl ${baseUrl}/tools?catalog=1`,
},
}, this.negotiatedProtocolVersion);
}
if (route.kind !== 'rpc') return json(response, 405, { error: 'Method Not Allowed' }, this.negotiatedProtocolVersion);
if (request.method === 'DELETE') {
return this.handleDelete(request, response);
}
if (request.method === 'GET') {
// An SSE GET probe is normal MCP negotiation; 405 is the supported
// response when no SSE stream is offered, not a warning to log.
return json(response, 405, { error: 'Method Not Allowed: SSE streams are not supported' }, this.negotiatedProtocolVersion);
}
if (request.method !== 'POST') {
this.log('warn', `Rejected ${request.method} ${request.url}: method not allowed.`);
return json(response, 405, { error: 'Method Not Allowed' }, this.negotiatedProtocolVersion);
}
const acceptHeaderError = this.validateAcceptHeader(request);
if (acceptHeaderError) {
return json(response, 406, acceptHeaderError, this.negotiatedProtocolVersion);
}
const body = await this.readBody(request);
if (!body) {
return json(response, 400, this.createError(null, -32700, 'Parse error: empty body'), this.negotiatedProtocolVersion);
}
let rpc;
try {
rpc = JSON.parse(body);
} catch (error) {
return json(response, 400, this.createError(null, -32700, `Parse error: ${error.message}`), this.negotiatedProtocolVersion);
}
if (rpc && rpc.method) {
this.log('info', `RPC ${rpc.method}`);
}
const protocolHeaderError = this.validateProtocolVersionHeader(request, rpc);
if (protocolHeaderError) {
return json(response, 400, protocolHeaderError, this.negotiatedProtocolVersion);
}
const responseProtocolVersion = this.getProtocolVersionForResponse(request, rpc);
const sessionError = this.validateSession(request, rpc);
if (sessionError) {
return json(response, sessionError.statusCode, sessionError.error, responseProtocolVersion);
}
const messageType = this.classifyJsonRpcMessage(rpc);
if (messageType === 'response') {
return empty(response, 202, responseProtocolVersion);
}
if (messageType === 'notification') {
const notificationError = this.handleRpcNotification(rpc);
if (notificationError) {
return json(response, 400, notificationError, responseProtocolVersion);
}
return empty(response, 202, responseProtocolVersion);
}
if (messageType !== 'request') {
return json(response, 400, this.createError(rpc && rpc.id, -32600, 'Invalid Request'), responseProtocolVersion);
}
const result = await this.handleRpcRequest(rpc, route);
if (result == null) {
return empty(response, 202, responseProtocolVersion);
}
const extraHeaders = {};
if (this.enableSessions && rpc.method === 'initialize' && result && !result.error) {
const sessionId = this.createSessionId();
this.sessions.add(sessionId);
extraHeaders['Mcp-Session-Id'] = sessionId;
}
return json(response, 200, result, this.getProtocolVersionForResponse(request, rpc), extraHeaders);
} catch (error) {
this.log('error', `Request handling failed: ${error.message}`);
const statusCode = error.statusCode || 500;
const rpcCode = error.rpcCode || -32603;
const message = statusCode === 500 ? `Internal error: ${error.message}` : error.message;
return json(response, statusCode, this.createError(null, rpcCode, message), this.negotiatedProtocolVersion);
}
};
let attempt = 0;
let port = this.config.port;
let lastError = null;
while (attempt <= MAX_PORT_FALLBACK_ATTEMPTS) {
this.log('info', `Creating HTTP server on ${this.config.host}:${port}...`);
const candidate = http.createServer(requestHandler);
try {
await this.listen(candidate, port, this.config.host);
this.server = candidate;
this.actualPort = candidate.address() && typeof candidate.address().port === 'number'
? candidate.address().port
: port;
if (this.config.port !== 0 && this.actualPort !== this.config.port) {
this.portFallbackInfo = {
requestedPort: this.config.port,
actualPort: this.actualPort,
attempts: attempt,
};
this.log(
'warn',
`Port ${this.config.port} was unavailable. Fell back to ${this.actualPort}.`
);
}
this.log('info', `Listening on ${serverUrl(this.config, this.actualPort, this.projectIdentity)}`);
return;
} catch (error) {
lastError = error;
candidate.removeAllListeners();
if (error && error.code === 'EADDRINUSE' && port < 65535 && attempt < MAX_PORT_FALLBACK_ATTEMPTS) {
if (await this.tryAttachToExisting(port)) {
return;
}
const nextPort = port + 1;
this.log(
'warn',
`Port ${port} is already in use. Trying fallback port ${nextPort}...`
);
port = nextPort;
attempt += 1;
continue;
}
break;
}
}
this.server = null;
this.actualPort = null;
this.portFallbackInfo = null;
throw lastError || new Error('Failed to start MCP server.');
}
async stop() {
if (this.attached) {
this.log('info', `Detached from existing MCP listener on ${this.config.host}:${this.actualPort}.`);
this.attached = false;
this.attachedInfo = null;
this.actualPort = null;
this.portFallbackInfo = null;
return;
}
if (!this.server) {
this.log('info', 'Stop skipped: server object is empty.');
return;
}
this.log('info', 'Closing HTTP server...');
const active = this.server;
this.server = null;
this.actualPort = null;
this.portFallbackInfo = null;
this.attachedInfo = null;
await new Promise((resolve, reject) => {
active.close((error) => {
if (error) {
this.log('error', `Close failed: ${error.message}`);
reject(error);
return;
}
this.log('info', 'HTTP server closed.');
resolve();
});
});
}
async tryAttachToExisting(port) {
if (!this.projectIdentity || this.config.attachToExisting === false || port === 0) {
return false;
}
const probe = await this.probeExistingServer(port);
if (!probe || !probe.result) {
this.log('warn', `Port ${port} is occupied, but no compatible Funplay MCP initialize response was received.`);
return false;
}
const result = probe.result || {};
const serverInfo = result.serverInfo || {};
const funplay = result.funplay || {};
const remoteProjectIdentity = funplay.projectIdentity || serverInfo.projectIdentity || '';
const remoteName = serverInfo.name || '';
if (remoteName === this.serverName && remoteProjectIdentity === this.projectIdentity
&& funplay.routingVersion === 1 && funplay.context && funplay.context.project_id === this.projectIdentity
&& typeof funplay.context.instance_id === 'string' && funplay.context.instance_id
&& funplay.context.expected_context === `${this.projectIdentity}:${funplay.context.instance_id}`) {
this.attached = true;
this.attachedInfo = {
host: this.config.host,
port,
serverName: remoteName,
projectName: funplay.projectName || this.projectName,
projectIdentity: remoteProjectIdentity,
version: serverInfo.version || '',
context: funplay.context,
};
this.actualPort = port;
this.portFallbackInfo = null;
this.log('info', `Attached to existing MCP listener for this project at http://${this.config.host}:${port}/.`);
return true;
}
this.log(
'warn',
`Port ${port} belongs to another listener; expected name=${this.serverName}, project=${this.projectIdentity}, ` +
`got name=${remoteName || 'unknown'}, project=${remoteProjectIdentity || 'unknown'}.`
);
return false;
}
probeExistingServer(port) {
const body = JSON.stringify({
jsonrpc: '2.0',
id: 'funplay-probe',
method: 'initialize',
params: {
protocolVersion: MCP_PROTOCOL_VERSION,
clientInfo: {
name: 'funplay-cocos-mcp-probe',
version: this.serverVersion,
},
},
});
return new Promise((resolve) => {
const request = http.request(
{
host: this.config.host,
port,
method: 'POST',
path: '/',
timeout: 600,
headers: {
Accept: 'application/json, text/event-stream',
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(body),
},
},
(response) => {
const chunks = [];
response.on('data', (chunk) => chunks.push(chunk));
response.on('end', () => {
if (response.statusCode !== 200) {
resolve(null);
return;
}
try {
resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')));
} catch (error) {
resolve(null);
}
});
}
);
request.on('timeout', () => {
request.destroy();
resolve(null);
});
request.on('error', () => resolve(null));
request.end(body);
});
}
listen(server, port, host) {
return new Promise((resolve, reject) => {
const onError = (error) => {
server.off('listening', onListening);
reject(error);
};
const onListening = () => {
server.off('error', onError);
resolve();
};
server.once('error', onError);
server.once('listening', onListening);
server.listen(port, host);
});
}
readBody(request) {
return new Promise((resolve, reject) => {
const chunks = [];
let size = 0;
request.on('data', (chunk) => {
size += chunk.length;
if (size > MAX_REQUEST_BODY_BYTES) {
const error = new Error(`Request body exceeds ${MAX_REQUEST_BODY_BYTES} bytes.`);
error.statusCode = 413;
error.rpcCode = -32600;
reject(error);
request.destroy();
return;
}
chunks.push(chunk);
});
request.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
request.on('error', reject);
});
}
isAllowedOrigin(request) {
const origin = request.headers && request.headers.origin;
if (!origin) {
return true;
}
try {
const parsed = new URL(String(origin));
const hostname = parsed.hostname.toLowerCase();
const configuredHost = String(this.config.host || '').toLowerCase();
return hostname === 'localhost'
|| hostname === '127.0.0.1'
|| hostname === '::1'
|| (configuredHost && hostname === configuredHost);
} catch (error) {
return false;
}
}
validateAcceptHeader(request) {
const header = request.headers && request.headers.accept;
if (!header) {
return this.createError(
null,
-32600,
'Missing Accept header. Streamable HTTP clients must accept application/json and text/event-stream.'
);
}
const tokens = String(Array.isArray(header) ? header.join(',') : header)
.split(',')
.map((item) => item.split(';')[0].trim().toLowerCase())
.filter(Boolean);
const hasWildcard = tokens.includes('*/*');
const hasJson = hasWildcard || tokens.includes('application/json') || tokens.includes('application/*');
const hasSse = hasWildcard || tokens.includes('text/event-stream') || tokens.includes('text/*');
if (!hasJson || !hasSse) {
return this.createError(
null,
-32600,
'Invalid Accept header. Streamable HTTP clients must accept both application/json and text/event-stream.'
);
}
return null;
}
validateProtocolVersionHeader(request, rpc) {
const header = request.headers && request.headers['mcp-protocol-version'];
if (!header || (rpc && rpc.method === 'initialize')) {
return null;
}
const version = Array.isArray(header) ? header[0] : String(header);
if (!SUPPORTED_PROTOCOL_VERSIONS.includes(version)) {
return this.createError(
rpc && rpc.id,
-32600,
`Unsupported MCP protocol version header: ${version}`
);
}
return null;
}
getProtocolVersionForResponse(request, rpc) {
if (rpc && rpc.method === 'initialize') {
return this.negotiatedProtocolVersion;
}
const header = request.headers && request.headers['mcp-protocol-version'];
const version = Array.isArray(header) ? header[0] : header ? String(header) : '';
if (SUPPORTED_PROTOCOL_VERSIONS.includes(version)) {
return version;
}
return this.negotiatedProtocolVersion;
}
validateSession(request, rpc) {
if (!this.enableSessions || (rpc && rpc.method === 'initialize')) {
return null;
}
const sessionId = this.getSessionId(request);
if (!sessionId) {
return {
statusCode: 400,
error: this.createError(rpc && rpc.id, -32600, 'Missing Mcp-Session-Id header.'),
};
}
if (!this.sessions.has(sessionId)) {
return {
statusCode: 404,
error: this.createError(rpc && rpc.id, -32001, 'Unknown or expired MCP session.'),
};
}
return null;
}
getSessionId(request) {
const value = request.headers && (request.headers['mcp-session-id'] || request.headers['Mcp-Session-Id']);
if (Array.isArray(value)) {
return value[0] || '';
}
return value ? String(value) : '';
}
createSessionId() {
if (typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
return crypto.randomBytes(16).toString('hex');
}
handleDelete(request, response) {
if (!this.enableSessions) {
return json(response, 405, { error: 'Method Not Allowed: MCP sessions are disabled' }, this.negotiatedProtocolVersion);
}
const sessionId = this.getSessionId(request);
if (!sessionId) {
return json(
response,
400,
this.createError(null, -32600, 'Missing Mcp-Session-Id header.'),
this.negotiatedProtocolVersion
);
}
if (!this.sessions.has(sessionId)) {
return json(
response,
404,
this.createError(null, -32001, 'Unknown or expired MCP session.'),
this.negotiatedProtocolVersion
);
}
this.sessions.delete(sessionId);
return empty(response, 202, this.negotiatedProtocolVersion);
}
classifyJsonRpcMessage(message) {
if (!message || message.jsonrpc !== '2.0') {
return 'invalid';
}
if (typeof message.method === 'string') {
return Object.prototype.hasOwnProperty.call(message, 'id') ? 'request' : 'notification';
}
if (
Object.prototype.hasOwnProperty.call(message, 'id') &&
(Object.prototype.hasOwnProperty.call(message, 'result') || Object.prototype.hasOwnProperty.call(message, 'error'))
) {
return 'response';
}
return 'invalid';
}
handleRpcNotification(notification) {
if (!notification || notification.jsonrpc !== '2.0' || typeof notification.method !== 'string') {
return this.createError(null, -32600, 'Invalid Request');
}
if (notification.method.startsWith('notifications/')) {
return null;
}
return this.createError(null, -32601, `Notification method not found: ${notification.method}`);
}
async handleRpcRequest(request, route = {}) {
if (!request || request.jsonrpc !== '2.0') {
return this.createError(request && request.id, -32600, 'Invalid Request');
}
const method = request.method;
if (typeof method !== 'string' || !method) {
return this.createError(request.id, -32600, 'Invalid Request: method is required');
}
if (this.getActiveContext) {
let active;
try { active = this.getActiveContext(); } catch (error) { return this.rejectContext(request.id, 'PROJECT_CONTEXT_UNAVAILABLE'); }
if (!active || active.project_id !== this.context.project_id
|| active.instance_id !== this.context.instance_id) return this.rejectContext(request.id, 'PROJECT_CONTEXT_MISMATCH');
}
if (method === 'initialize') {
this.negotiatedProtocolVersion = this.negotiateProtocolVersion(request.params && request.params.protocolVersion);
return this.createResult(request.id, {
protocolVersion: this.negotiatedProtocolVersion,
serverInfo: {
name: this.serverName,
version: this.serverVersion,
},
funplay: {
server: 'funplay-cocos-mcp',
projectName: this.projectName,
projectIdentity: this.projectIdentity,
routingVersion: 1,
context: this.getProjectContext(),
},
capabilities: {
tools: {},
resources: {},
prompts: {},
},
instructions: 'Independently compare initialize.funplay.context.project_path and project_id with the intended project before writes. Generated /mcp/project/<project_id>/ URLs guard project routing. Legacy URLs remain readable but mutations require expected_context in arguments or params._meta; explicit pins also detect an Editor restart. Identity guards are not authentication. Input event delivery is not proof of gameplay acceptance.',
});
}
if (method === 'notifications/initialized' || method === 'notifications/cancelled' || method.startsWith('notifications/')) {
return null;
}
if (method === 'tools/list') {
return this.createResult(request.id, { tools: this.toolRegistry.listTools().map(withContextSchema) });
}
if (method === 'tools/call') {
const params = request.params || {};
if (typeof params.name !== 'string' || !params.name) {
return this.createError(request.id, -32602, "Invalid params: 'name' is required");
}
const tool = this.toolRegistry.listTools().find((item) => item.name === params.name);
const guard = contextError(this.getProjectContext(), params, {
scoped: route.scoped === true,
readOnly: Boolean(tool && tool.annotations && tool.annotations.readOnlyHint === true),
});
if (guard) return this.rejectContext(request.id, guard);
const args = { ...(params.arguments || {}) };
delete args.expected_context;
try {
const output = typeof this.toolRegistry.callToolDetailed === 'function'
? await this.toolRegistry.callToolDetailed(params.name, args)
: { value: null, text: await this.toolRegistry.callTool(params.name, args) };
const result = { content: textContent(output.text, output.metadataText), _meta: { [CONTEXT_META_KEY]: this.getProjectContext() } };
const structured = structuredContent(output.value);
if (structured) {
result.structuredContent = structured;
}
return this.createResult(request.id, result);
} catch (error) {
const result = {
content: textContent(error.inputOutcome && error.toolEnvelope ? safeStringify(error.toolEnvelope) : error.message),
isError: true,
_meta: { [CONTEXT_META_KEY]: this.getProjectContext() },
};
const structured = structuredContent(error.toolEnvelope);
if (structured) {
result.structuredContent = structured;
}
return this.createResult(request.id, result);
}
}
if (method === 'resources/list') {
return this.createResult(request.id, { resources: this.resourceProvider.listResources() });
}
if (method === 'resources/read') {
const params = request.params || {};
if (typeof params.uri !== 'string' || !params.uri) {
return this.createError(request.id, -32602, "Invalid params: 'uri' is required");
}
return this.createResult(request.id, await this.resourceProvider.readResource(params.uri));
}
if (method === 'resources/templates/list') {
return this.createResult(request.id, { resourceTemplates: this.resourceProvider.listResourceTemplates() });
}
if (method === 'prompts/list') {
return this.createResult(request.id, { prompts: this.promptProvider.listPrompts() });
}
if (method === 'prompts/get') {
const params = request.params || {};
if (typeof params.name !== 'string' || !params.name) {
return this.createError(request.id, -32602, "Invalid params: 'name' is required");
}
try {
return this.createResult(request.id, this.promptProvider.getPrompt(
params.name, params.arguments === undefined ? {} : params.arguments
));
} catch (error) {
return this.createError(request.id, error.code === -32602 ? -32602 : -32603, error.message);
}
}
return this.createError(request.id, -32601, `Method not found: ${method}`);
}
negotiateProtocolVersion(clientVersion) {
if (SUPPORTED_PROTOCOL_VERSIONS.includes(clientVersion)) {
return clientVersion;
}
return MCP_PROTOCOL_VERSION;
}
createResult(id, result) {
return {
jsonrpc: '2.0',
id,
result,
};
}
createError(id, code, message) {
return {
jsonrpc: '2.0',
id,
error: {
code,
message,
},
};
}
}
module.exports = {
McpServer,
MCP_PROTOCOL_VERSION,
SUPPORTED_PROTOCOL_VERSIONS,
};
+50
View File
@@ -0,0 +1,50 @@
'use strict';
const fs = require('fs');
const path = require('path');
const SKILL_PLATFORMS = Object.freeze([
{ id: 'codex', name: 'Codex', directory: '.agents/skills', legacyDirectory: '.codex/skills' },
{ id: 'claude_code', name: 'Claude Code', directory: '.claude/skills' },
{ id: 'cursor', name: 'Cursor', directory: '.cursor/skills' },
{ id: 'vscode', name: 'VS Code / Copilot', directory: '.github/skills' },
{ id: 'trae', name: 'Trae', directory: '.trae/skills' },
{ id: 'antigravity', name: 'Antigravity', directory: '.agents/skills', legacyDirectory: '.agent/skills' },
{ id: 'pi', name: 'Pi', directory: '.agents/skills' },
{ id: 'kiro', name: 'Kiro', directory: '.kiro/skills' },
{ id: 'qoder', name: 'Qoder', directory: '.qoder/skills' },
{ id: 'kimi', name: 'Kimi Code', directory: '.kimi-code/skills', gitRoot: true },
{ id: 'opencode', name: 'OpenCode', directory: '.opencode/skills' },
{ id: 'codebuddy', name: 'CodeBuddy', directory: '.codebuddy/skills' },
{ id: 'deepseek_harness', name: 'DeepSeek Harness (DSH)', directory: '.dsh/skills', gitRoot: true },
]);
function findGitRootOrSelf(projectPath) {
const original = path.resolve(projectPath);
for (let current = original; ; current = path.dirname(current)) {
if (fs.existsSync(path.join(current, '.git'))) return current;
if (path.dirname(current) === current) return original;
}
}
function getSkillPlatform(options = {}) {
const id = options.clientId || 'codex';
return SKILL_PLATFORMS.find((platform) => platform.id === id) || null;
}
function requireSkillPlatform(options = {}) {
const platform = getSkillPlatform(options);
if (!platform) throw new Error(`Project Skills installation is not supported for client: ${options.clientId}`);
return platform;
}
function getSkillsDirectory(options = {}) {
const platform = requireSkillPlatform(options);
return options.legacy && platform.legacyDirectory ? platform.legacyDirectory : platform.directory;
}
function getSkillProjectPath(projectPath, options = {}) {
return requireSkillPlatform(options).gitRoot ? findGitRootOrSelf(projectPath) : path.resolve(projectPath);
}
module.exports = { SKILL_PLATFORMS, findGitRootOrSelf, getSkillPlatform, getSkillsDirectory, getSkillProjectPath };
+155
View File
@@ -0,0 +1,155 @@
'use strict';
const PROFILE_FIELDS = [
'toolProfile',
'enabledToolCategories',
'disabledToolCategories',
'enabledTools',
'disabledTools',
];
function normalizeProfileName(value) {
const normalized = String(value || '').trim();
if (!normalized) {
throw new Error('profile name is required.');
}
return normalized.slice(0, 80);
}
function normalizeStringList(value) {
if (Array.isArray(value)) {
return value.map((item) => String(item || '').trim()).filter(Boolean);
}
if (typeof value === 'string') {
return value.split(/[\n,]/).map((item) => item.trim()).filter(Boolean);
}
return [];
}
function normalizeProfileMode(value) {
const normalized = String(value || 'core').trim().toLowerCase();
return normalized === 'full' || normalized === 'custom' ? normalized : 'core';
}
function normalizeToolProfile(value) {
const profile = value || {};
return {
name: normalizeProfileName(profile.name),
toolProfile: normalizeProfileMode(profile.toolProfile),
enabledToolCategories: normalizeStringList(profile.enabledToolCategories).map((item) => item.toLowerCase()),
disabledToolCategories: normalizeStringList(profile.disabledToolCategories).map((item) => item.toLowerCase()),
enabledTools: normalizeStringList(profile.enabledTools),
disabledTools: normalizeStringList(profile.disabledTools),
updatedAt: profile.updatedAt ? String(profile.updatedAt) : new Date().toISOString(),
};
}
function normalizeSavedToolProfiles(value) {
const profiles = [];
const seen = new Set();
for (const item of Array.isArray(value) ? value : []) {
try {
const profile = normalizeToolProfile(item);
const key = profile.name.toLowerCase();
if (seen.has(key)) {
const index = profiles.findIndex((existing) => existing.name.toLowerCase() === key);
profiles[index] = profile;
} else {
seen.add(key);
profiles.push(profile);
}
} catch (error) {
// Ignore malformed saved profile entries rather than breaking extension startup.
}
}
return profiles.sort((left, right) => left.name.localeCompare(right.name));
}
function createToolProfileSnapshot(config = {}, name) {
return normalizeToolProfile({
name,
toolProfile: config.toolProfile,
enabledToolCategories: config.enabledToolCategories,
disabledToolCategories: config.disabledToolCategories,
enabledTools: config.enabledTools,
disabledTools: config.disabledTools,
});
}
function upsertToolProfile(savedProfiles, profile) {
const normalized = normalizeToolProfile(profile);
const profiles = normalizeSavedToolProfiles(savedProfiles);
const key = normalized.name.toLowerCase();
const index = profiles.findIndex((item) => item.name.toLowerCase() === key);
if (index >= 0) {
profiles[index] = normalized;
} else {
profiles.push(normalized);
}
return normalizeSavedToolProfiles(profiles);
}
function deleteToolProfile(savedProfiles, name) {
const key = normalizeProfileName(name).toLowerCase();
return normalizeSavedToolProfiles(savedProfiles)
.filter((profile) => profile.name.toLowerCase() !== key);
}
function findToolProfile(savedProfiles, name) {
const key = normalizeProfileName(name).toLowerCase();
return normalizeSavedToolProfiles(savedProfiles)
.find((profile) => profile.name.toLowerCase() === key) || null;
}
function applyToolProfile(config = {}, profile) {
const normalized = normalizeToolProfile(profile);
const next = { ...config };
for (const field of PROFILE_FIELDS) {
next[field] = Array.isArray(normalized[field])
? normalized[field].slice()
: normalized[field];
}
next.activeToolProfileName = normalized.name;
return next;
}
function exportToolProfiles(savedProfiles) {
return {
version: 1,
profiles: normalizeSavedToolProfiles(savedProfiles),
};
}
function parseProfileImportPayload(payload) {
if (typeof payload === 'string') {
return JSON.parse(payload);
}
return payload || {};
}
function importToolProfiles(savedProfiles, payload, options = {}) {
const parsed = parseProfileImportPayload(payload);
const incoming = Array.isArray(parsed)
? parsed
: Array.isArray(parsed.profiles)
? parsed.profiles
: [];
if (!incoming.length) {
throw new Error('No tool profiles found in import payload.');
}
const base = options.replace ? [] : normalizeSavedToolProfiles(savedProfiles);
return incoming.reduce((profiles, profile) => upsertToolProfile(profiles, profile), base);
}
module.exports = {
applyToolProfile,
createToolProfileSnapshot,
deleteToolProfile,
exportToolProfiles,
findToolProfile,
importToolProfiles,
normalizeSavedToolProfiles,
normalizeToolProfile,
upsertToolProfile,
};
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,236 @@
'use strict';
const { checkAssetReady } = require('../asset-readiness');
const fs = require('fs');
const path = require('path');
const { listAssets, queryAssetInfo } = require('../assets');
const { resolveProjectPath } = require('../path-safety');
const UUID_KEY_PATTERN = /uuid|assetUuid|prefabUuid|sceneUuid|__uuid__/i;
const UUID_LITERAL_PATTERN = /[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}|[A-Za-z0-9+/=-]{20,32}/g;
function assetUrlToPath(projectPath, url) {
if (!url || !String(url).startsWith('db://assets/')) {
return '';
}
return path.join(projectPath, String(url).slice('db://'.length));
}
function assetFilePath(projectPath, info) {
const candidates = [
info && info.file,
info && info.path,
info && info.source,
info && info.url ? assetUrlToPath(projectPath, info.url) : '',
].filter(Boolean);
for (const candidate of candidates) {
const fullPath = resolveProjectPath(projectPath, candidate);
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
return fullPath;
}
}
return '';
}
function collectStructuredUuidReferences(value, refs = [], pointer = '') {
if (value == null) {
return refs;
}
if (Array.isArray(value)) {
value.forEach((item, index) => collectStructuredUuidReferences(item, refs, `${pointer}/${index}`));
return refs;
}
if (typeof value !== 'object') {
return refs;
}
for (const [key, child] of Object.entries(value)) {
const childPointer = `${pointer}/${key}`;
if (typeof child === 'string' && UUID_KEY_PATTERN.test(key)) {
refs.push({ uuid: child, path: childPointer, key, source: 'structured' });
continue;
}
collectStructuredUuidReferences(child, refs, childPointer);
}
return refs;
}
function collectTextUuidReferences(text) {
const refs = [];
const seen = new Set();
let match;
while ((match = UUID_LITERAL_PATTERN.exec(String(text || '')))) {
const uuid = match[0];
if (seen.has(uuid)) {
continue;
}
seen.add(uuid);
refs.push({ uuid, path: `@${match.index}`, key: '', source: 'text' });
}
return refs;
}
function dedupeReferences(refs) {
const seen = new Set();
const result = [];
for (const ref of refs) {
const key = `${ref.uuid}:${ref.path}`;
if (seen.has(key)) {
continue;
}
seen.add(key);
result.push(ref);
}
return result;
}
function collectUuidReferences(content) {
const refs = [];
try {
refs.push(...collectStructuredUuidReferences(JSON.parse(content)));
} catch (error) {
// Non-JSON assets still get a literal reference scan below.
}
refs.push(...collectTextUuidReferences(content));
return dedupeReferences(refs);
}
async function inspectAssetDependencies(projectPath, target, options = {}) {
const info = await queryAssetInfo(target);
const filePath = assetFilePath(projectPath, info);
if (!filePath) {
throw new Error(`Asset file was not found: ${target}`);
}
const content = fs.readFileSync(filePath, 'utf8');
const limit = Number.isFinite(options.limit) ? Math.max(1, Math.min(500, options.limit)) : 200;
const references = collectUuidReferences(content).slice(0, limit);
const dependencies = [];
const missing = [];
for (const ref of references) {
try {
const asset = await queryAssetInfo(ref.uuid);
dependencies.push({
...ref,
exists: true,
asset: {
uuid: asset.uuid,
url: asset.url,
type: asset.type,
importer: asset.importer,
},
});
} catch (error) {
missing.push({ ...ref, exists: false, error: error.message });
}
}
return {
ok: missing.length === 0,
target,
asset: {
uuid: info.uuid,
url: info.url,
type: info.type,
},
filePath: path.relative(projectPath, filePath).replace(/\\/g, '/'),
referenceCount: references.length,
dependencyCount: dependencies.length,
missingCount: missing.length,
dependencies,
missing,
};
}
async function validateAssetDependencies(projectPath, options = {}) {
const targets = options.target
? [options.target]
: (await listAssets({ pattern: options.pattern || 'db://assets/**', ccType: options.ccType }))
.slice(0, Number.isFinite(options.limit) ? Math.max(1, Math.min(200, options.limit)) : 50)
.map((asset) => asset.uuid || asset.url)
.filter(Boolean);
const assets = [];
for (const target of targets) {
try {
assets.push(await inspectAssetDependencies(projectPath, target, options));
} catch (error) {
assets.push({
ok: false,
target,
error: error.message,
missingCount: 1,
});
}
}
const missingCount = assets.reduce((sum, asset) => sum + (Number(asset.missingCount) || 0), 0);
return {
ok: missingCount === 0,
assetCount: assets.length,
missingCount,
assets,
};
}
function createAssetsAdvancedTools({ createSchema, getRuntimeContext }) {
return [
{
name: 'check_asset_ready',
profile: 'full',
category: 'assets',
description: '[specialist] Check bounded AssetDB readiness and optionally a stable imported UUID/URL identity. Does not prove importer queue, script compilation, source bytes, or runtime loading completion.',
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true },
inputSchema: createSchema({
target: { type: 'string', description: 'Optional exact asset UUID, db:// URL, or assets/... path. No extension guessing.' },
waitMs: { type: 'integer', minimum: 0, maximum: 10000, description: 'Total polling budget; defaults to 1500 ms. Zero returns one unconfirmed observation.' },
pollIntervalMs: { type: 'integer', minimum: 20, maximum: 2000, description: 'Polling interval; defaults to 100 ms.' },
}, []),
handler: async (args) => await checkAssetReady(args),
},
{
name: 'inspect_asset_dependencies',
profile: 'core',
description: '[specialist] Inspect UUID-style dependencies referenced by a serialized Cocos asset.',
inputSchema: createSchema(
{
target: { type: 'string', description: 'Asset uuid, db url, or project path.' },
limit: { type: 'number', description: 'Maximum dependency references to inspect.' },
},
['target']
),
handler: async (args) => {
const { projectPath } = getRuntimeContext();
return await inspectAssetDependencies(projectPath, args.target, args);
},
},
{
name: 'validate_asset_dependencies',
profile: 'core',
description: '[specialist] Validate UUID-style dependencies for one asset or a project asset query.',
inputSchema: createSchema(
{
target: { type: 'string', description: 'Optional asset uuid, db url, or project path.' },
pattern: { type: 'string', description: 'Asset-db pattern used when target is omitted.' },
ccType: { type: 'string', description: 'Optional Cocos asset type filter.' },
limit: { type: 'number', description: 'Maximum assets to scan when target is omitted.' },
},
[]
),
handler: async (args) => {
const { projectPath } = getRuntimeContext();
return await validateAssetDependencies(projectPath, args);
},
},
];
}
module.exports = {
collectUuidReferences,
createAssetsAdvancedTools,
inspectAssetDependencies,
validateAssetDependencies,
};
@@ -0,0 +1,547 @@
'use strict';
const previewRuntime = require('../preview-runtime');
const PREVIEW_PROFILE_PACKAGE = 'preview';
const PREVIEW_PROFILE_KEY = 'preview.current.platform';
const PREVIEW_PROFILE_SCOPE = 'local';
const PREVIEW_MODES = Object.freeze(['browser', 'gameView', 'simulator']);
const PREVIEW_MODE_DETAILS = Object.freeze({
browser: Object.freeze({
mode: 'browser',
label: 'Browser Preview',
description: 'Run the scene in the system browser and expose the preview URL.',
hasUrl: true,
}),
gameView: Object.freeze({
mode: 'gameView',
label: 'Editor Preview',
description: 'Run the scene inside the Cocos Creator Game View.',
hasUrl: false,
}),
simulator: Object.freeze({
mode: 'simulator',
label: 'Simulator Preview',
description: 'Run the scene in the Cocos native simulator.',
hasUrl: false,
}),
});
const PREVIEW_MODE_ALIASES = Object.freeze({
browser: 'browser',
web: 'browser',
'browser-preview': 'browser',
gameview: 'gameView',
'game-view': 'gameView',
editor: 'gameView',
'editor-preview': 'gameView',
simulator: 'simulator',
native: 'simulator',
'simulator-preview': 'simulator',
});
function hasEditorMessage() {
return Boolean(global.Editor && Editor.Message);
}
function ensureEditorMessage() {
if (!hasEditorMessage()) {
throw new Error('Editor.Message is unavailable in this Cocos extension host.');
}
}
async function requestEditorMessage(channel, method, ...args) {
ensureEditorMessage();
if (typeof Editor.Message.request !== 'function') {
throw new Error('Editor.Message.request is unavailable in this Cocos extension host.');
}
return await Editor.Message.request(channel, method, ...args);
}
async function tryEditorRequests(candidates) {
const attempts = [];
for (const candidate of candidates) {
const channel = candidate.channel;
const method = candidate.method;
const args = Array.isArray(candidate.args) ? candidate.args : [];
try {
const result = await requestEditorMessage(channel, method, ...args);
return {
ok: true,
channel,
method,
result,
attempts,
};
} catch (error) {
attempts.push({ channel, method, error: error.message });
}
}
const message = attempts.length
? attempts.map((attempt) => `${attempt.channel}.${attempt.method}: ${attempt.error}`).join('; ')
: 'no editor message candidates were provided';
const error = new Error(`No compatible Cocos editor message succeeded: ${message}`);
error.attempts = attempts;
throw error;
}
async function tryEditorRequestsStatus(candidates) {
try {
return await tryEditorRequests(candidates);
} catch (error) {
return {
ok: false,
available: false,
attempts: error.attempts || [],
error: error.message,
};
}
}
function normalizePreviewMode(value, options = {}) {
const raw = String(value == null ? '' : value).trim();
if (!raw && options.allowEmpty === true) {
return '';
}
const mode = PREVIEW_MODE_ALIASES[raw.toLowerCase()];
if (!mode) {
throw new Error(`Unsupported preview mode '${raw}'. Expected one of: ${PREVIEW_MODES.join(', ')}.`);
}
return mode;
}
function previewModeCatalog() {
return PREVIEW_MODES.map((mode) => ({ ...PREVIEW_MODE_DETAILS[mode] }));
}
function ensurePreviewProfile() {
if (
!global.Editor ||
!Editor.Profile ||
typeof Editor.Profile.getConfig !== 'function' ||
typeof Editor.Profile.setConfig !== 'function'
) {
throw new Error('Editor.Profile.getConfig/setConfig is unavailable in this Cocos extension host.');
}
}
async function queryPreviewUrl() {
const result = await requestEditorMessage('preview', 'query-preview-url');
return typeof result === 'string' ? result : '';
}
function normalizePreviewHostname(value) {
return String(value || '').trim().toLowerCase().replace(/^\[|\]$/g, '');
}
function isLoopbackPreviewHostname(value) {
const hostname = normalizePreviewHostname(value);
if (hostname === 'localhost' || hostname.endsWith('.localhost') || hostname === '::1') {
return true;
}
const ipv4 = hostname.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);
return Boolean(ipv4 && ipv4.slice(1).every((part) => Number(part) <= 255) && Number(ipv4[1]) === 127);
}
function resolvePreviewUrls(value) {
const reportedUrl = typeof value === 'string' ? value.trim() : '';
const empty = {
url: '',
localUrl: '',
networkUrl: '',
reportedUrl: '',
urlAvailable: false,
urlWarning: '',
};
if (!reportedUrl) {
return empty;
}
let parsed;
try {
parsed = new URL(reportedUrl);
} catch (_error) {
return {
...empty,
url: reportedUrl,
reportedUrl,
urlAvailable: true,
urlWarning: 'Cocos Creator returned a preview URL that is not an absolute HTTP(S) URL; the value was left unchanged.',
};
}
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
return {
...empty,
url: reportedUrl,
reportedUrl,
urlAvailable: true,
urlWarning: `Cocos Creator returned an unsupported preview URL protocol '${parsed.protocol}'; the value was left unchanged.`,
};
}
const loopback = isLoopbackPreviewHostname(parsed.hostname);
const wildcard = ['0.0.0.0', '::'].includes(normalizePreviewHostname(parsed.hostname));
let localUrl = reportedUrl;
if (!loopback) {
const local = new URL(parsed.href);
local.hostname = 'localhost';
localUrl = local.href;
}
return {
url: localUrl,
localUrl,
networkUrl: loopback || wildcard ? '' : reportedUrl,
reportedUrl,
urlAvailable: true,
urlWarning: '',
};
}
async function getPreviewMode(options = {}) {
ensurePreviewProfile();
const storedValue = await Editor.Profile.getConfig(
PREVIEW_PROFILE_PACKAGE,
PREVIEW_PROFILE_KEY,
PREVIEW_PROFILE_SCOPE
);
let mode = 'browser';
let warning = '';
try {
mode = normalizePreviewMode(storedValue || 'browser');
} catch (error) {
warning = `${error.message} Falling back to browser.`;
}
let previewUrls = resolvePreviewUrls('');
let urlError = '';
if (mode === 'browser' && options.includeUrl !== false) {
try {
previewUrls = resolvePreviewUrls(await queryPreviewUrl());
} catch (error) {
urlError = error.message;
}
}
return {
mode,
label: PREVIEW_MODE_DETAILS[mode].label,
storedValue: storedValue == null ? '' : String(storedValue),
supportedModes: previewModeCatalog(),
...previewUrls,
warning,
urlError,
};
}
async function setPreviewMode(value) {
ensurePreviewProfile();
ensureEditorMessage();
if (typeof Editor.Message.send !== 'function') {
throw new Error('Editor.Message.send is unavailable in this Cocos extension host.');
}
const mode = normalizePreviewMode(value);
const previous = await getPreviewMode({ includeUrl: false });
const runtime = await previewRuntime.controlPreviewToolbar({ action: 'set-mode', mode });
const current = await getPreviewMode({ includeUrl: false });
if (current.mode !== mode) {
throw new Error(`Cocos Creator did not persist preview mode '${mode}'. Current mode is '${current.mode}'.`);
}
return {
changed: previous.mode !== mode,
previousMode: previous.mode,
mode,
label: PREVIEW_MODE_DETAILS[mode].label,
editorPreviewStop: previous.mode === 'gameView' && mode !== 'gameView' ? !runtime.running : null,
editorPreviewStopError: '',
runtime,
supportedModes: previewModeCatalog(),
};
}
async function runProjectPreview(options = {}) {
const modeInput = options.mode == null ? options.platform : options.mode;
if (options.mode != null && options.platform != null) {
const mode = normalizePreviewMode(options.mode);
const platform = normalizePreviewMode(options.platform);
if (mode !== platform) {
throw new Error(`Conflicting preview mode values: mode='${options.mode}', platform='${options.platform}'.`);
}
}
let modeChange = null;
let mode;
if (modeInput == null || String(modeInput).trim() === '') {
mode = (await getPreviewMode({ includeUrl: false })).mode;
} else {
mode = normalizePreviewMode(modeInput);
modeChange = await setPreviewMode(mode);
}
const usedDeprecatedPlatform = options.mode == null && options.platform != null;
if (mode === 'gameView') {
const runtime = await previewRuntime.controlPreviewToolbar({ action: 'start' });
return {
started: true,
mode,
label: PREVIEW_MODE_DETAILS[mode].label,
method: 'preview.toolbar.play',
result: true,
runtime,
...resolvePreviewUrls(''),
urlError: '',
modeChange,
usedDeprecatedPlatform,
};
}
const result = await requestEditorMessage('preview', 'open-terminal', undefined);
let previewUrls = resolvePreviewUrls('');
let urlError = '';
if (mode === 'browser') {
try {
previewUrls = resolvePreviewUrls(await queryPreviewUrl());
} catch (error) {
urlError = error.message;
}
}
return {
started: true,
mode,
label: PREVIEW_MODE_DETAILS[mode].label,
method: 'preview.open-terminal',
result,
...previewUrls,
urlError,
modeChange,
usedDeprecatedPlatform,
};
}
async function openPanel(panelName) {
const id = String(panelName || 'builder').trim();
if (!id) {
throw new Error('panelName is required.');
}
if (!global.Editor || !Editor.Panel || typeof Editor.Panel.open !== 'function') {
throw new Error('Editor.Panel.open is unavailable in this Cocos extension host.');
}
const result = await Editor.Panel.open(id);
return { opened: true, panelName: id, result };
}
function getEditorPreference(scope, key) {
if (!global.Editor || !Editor.Profile) {
throw new Error('Editor.Profile is unavailable in this Cocos extension host.');
}
const normalizedScope = String(scope || 'project').toLowerCase();
const target = normalizedScope === 'global' ? Editor.Profile : Editor.Profile;
const getters = normalizedScope === 'global'
? ['getConfig', 'getGlobal']
: ['getProject', 'getConfig'];
for (const getter of getters) {
if (typeof target[getter] === 'function') {
return target[getter](key);
}
}
throw new Error('No compatible Editor.Profile getter is available.');
}
function setEditorPreference(scope, key, value) {
if (!global.Editor || !Editor.Profile) {
throw new Error('Editor.Profile is unavailable in this Cocos extension host.');
}
const normalizedScope = String(scope || 'project').toLowerCase();
const target = Editor.Profile;
const setters = normalizedScope === 'global'
? ['setConfig', 'setGlobal']
: ['setProject', 'setConfig'];
for (const setter of setters) {
if (typeof target[setter] === 'function') {
const result = target[setter](key, value);
return { set: true, scope: normalizedScope, key, value, method: setter, result };
}
}
throw new Error('No compatible Editor.Profile setter is available.');
}
function broadcastEditorMessage(options = {}) {
ensureEditorMessage();
const channel = String(options.channel || '').trim();
const message = String(options.message || '').trim();
if (!message) {
throw new Error('message is required.');
}
const payload = options.payload === undefined ? {} : options.payload;
if (channel && typeof Editor.Message.send === 'function') {
const result = Editor.Message.send(channel, message, payload);
return { sent: true, mode: 'send', channel, message, payload, result };
}
if (typeof Editor.Message.broadcast === 'function') {
const result = Editor.Message.broadcast(message, payload);
return { sent: true, mode: 'broadcast', message, payload, result };
}
throw new Error('Neither Editor.Message.send nor Editor.Message.broadcast is available.');
}
function createCocosProjectTools({ createSchema }) {
return [
{
name: 'save_current_scene',
profile: 'full',
description: '[core] Save the currently open Cocos scene using available editor scene messages.',
inputSchema: createSchema({}, []),
handler: async () => {
const result = await tryEditorRequests([
{ channel: 'scene', method: 'save-scene' },
{ channel: 'scene', method: 'save' },
]);
return { saved: true, ...result };
},
},
{
name: 'open_build_panel',
profile: 'full',
description: '[core] Open the Cocos build panel, defaulting to the builder panel id.',
inputSchema: createSchema(
{
panelName: { type: 'string', description: 'Panel id to open. Defaults to builder.' },
},
[]
),
handler: async (args) => openPanel(args.panelName || 'builder'),
},
{
name: 'get_build_status',
profile: 'core',
description: '[specialist] Query Cocos build/preview status using known builder message variants.',
inputSchema: createSchema({}, []),
handler: async () => await tryEditorRequestsStatus([
{ channel: 'builder', method: 'query-build-status' },
{ channel: 'builder', method: 'get-build-status' },
{ channel: 'builder', method: 'query-build-tasks' },
]),
},
{
name: 'get_preview_mode',
profile: 'core',
description: '[specialist] Query the active Cocos Creator preview mode. Browser results use a same-host loopback url/localUrl and preserve Creator\'s reported LAN address as networkUrl.',
inputSchema: createSchema({}, []),
handler: async () => await getPreviewMode(),
},
{
name: 'set_preview_mode',
profile: 'full',
description: '[core] Switch Cocos Creator 3.8.x preview mode through the native toolbar, synchronizing its state and stopping Game View before switching away.',
inputSchema: createSchema(
{
mode: {
type: 'string',
enum: PREVIEW_MODES,
description: 'Preview mode: browser, gameView (editor preview), or simulator.',
},
},
['mode']
),
handler: async (args) => await setPreviewMode(args.mode),
},
{
name: 'run_project_preview',
profile: 'full',
description: '[core] Start Cocos Creator 3.8.x preview in browser, editor Game View, or simulator mode. Game View uses the native toolbar and does not toggle off an already running preview. Browser results use a same-host loopback url/localUrl and preserve Creator\'s reported LAN address as networkUrl.',
inputSchema: createSchema(
{
mode: {
type: 'string',
enum: PREVIEW_MODES,
description: 'Preview mode: browser, gameView (editor preview), or simulator. Defaults to the current mode.',
},
platform: {
type: 'string',
enum: PREVIEW_MODES,
description: 'Deprecated alias for mode. This selects preview mode, not a build target.',
},
},
[]
),
handler: async (args) => await runProjectPreview(args),
},
{
name: 'get_editor_preference',
profile: 'full',
description: '[core] Read a Cocos editor preference through Editor.Profile when available.',
inputSchema: createSchema(
{
scope: { type: 'string', description: 'Preference scope: project or global. Defaults to project.' },
key: { type: 'string', description: 'Preference key.' },
},
['key']
),
handler: async (args) => ({
scope: args.scope || 'project',
key: args.key,
value: getEditorPreference(args.scope, args.key),
}),
},
{
name: 'set_editor_preference',
profile: 'full',
description: '[core] Write a Cocos editor preference through Editor.Profile when available.',
inputSchema: createSchema(
{
scope: { type: 'string', description: 'Preference scope: project or global. Defaults to project.' },
key: { type: 'string', description: 'Preference key.' },
valueJson: { type: 'string', description: 'JSON encoded preference value.' },
},
['key', 'valueJson']
),
handler: async (args) => {
let value;
try {
value = JSON.parse(args.valueJson);
} catch (error) {
throw new Error(`valueJson must be valid JSON: ${error.message}`);
}
return setEditorPreference(args.scope, args.key, value);
},
},
{
name: 'broadcast_editor_message',
profile: 'full',
description: '[core] Send or broadcast a Cocos editor message for advanced editor automation.',
inputSchema: createSchema(
{
channel: { type: 'string', description: 'Optional Editor.Message channel for send().' },
message: { type: 'string', description: 'Message name to send or broadcast.' },
payload: { type: 'object', description: 'Optional JSON payload.' },
},
['message']
),
handler: async (args) => broadcastEditorMessage(args),
},
];
}
module.exports = {
PREVIEW_MODES,
broadcastEditorMessage,
createCocosProjectTools,
getEditorPreference,
getPreviewMode,
normalizePreviewMode,
resolvePreviewUrls,
runProjectPreview,
setEditorPreference,
setPreviewMode,
tryEditorRequests,
tryEditorRequestsStatus,
};
+303
View File
@@ -0,0 +1,303 @@
'use strict';
const fs = require('fs');
const path = require('path');
const { resolveProjectPath } = require('../path-safety');
/**
* Build a focused, line-numbered snippet around one file line.
* @param {string} filePath Absolute file path.
* @param {number} lineNumber One-based target line number.
* @param {number} contextLines Surrounding lines to include.
* @returns {string}
*/
function buildSnippet(filePath, lineNumber, contextLines = 3) {
const lines = fs.readFileSync(filePath, 'utf8').split(/\r?\n/);
const start = Math.max(1, Number(lineNumber || 1) - Math.max(0, contextLines));
const end = Math.min(lines.length, Number(lineNumber || 1) + Math.max(0, contextLines));
const snippet = [];
for (let line = start; line <= end; line += 1) {
const marker = line === Number(lineNumber || 1) ? '>' : ' ';
snippet.push(`${marker} ${String(line).padStart(4, ' ')} | ${lines[line - 1]}`);
}
return snippet.join('\n');
}
function matchesPattern(fileName, pattern) {
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
return new RegExp(`^${escaped}$`, 'i').test(fileName);
}
function searchFiles(rootDir, pattern, limit) {
const results = [];
if (!fs.existsSync(rootDir)) {
return results;
}
const stack = [rootDir];
while (stack.length && results.length < limit) {
const current = stack.pop();
const entries = fs.readdirSync(current, { withFileTypes: true });
for (const entry of entries) {
if (entry.name === '.git' || entry.name === 'node_modules' || entry.name === 'temp' || entry.name === 'library') {
continue;
}
const fullPath = path.join(current, entry.name);
if (entry.isDirectory()) {
stack.push(fullPath);
continue;
}
if (matchesPattern(entry.name, pattern)) {
results.push(fullPath);
if (results.length >= limit) {
break;
}
}
}
}
return results;
}
function replaceAllLiteral(content, search, replacement) {
if (!search) {
throw new Error('search text is required.');
}
return content.split(search).join(replacement);
}
/**
* Best-effort refresh for Cocos asset database after external file edits.
* @param {string} projectPath Active Cocos project root.
* @param {string} targetPath Absolute file or directory path.
* @returns {Promise<string>}
*/
async function refreshAssets(projectPath, targetPath) {
if (!global.Editor || !Editor.Message || typeof Editor.Message.request !== 'function') {
return 'Asset refresh API is unavailable; Cocos Creator should pick up file changes automatically.';
}
const relative = path.relative(path.join(projectPath, 'assets'), targetPath).replace(/\\/g, '/');
if (!relative.startsWith('..')) {
const dbUrl = relative ? `db://assets/${relative}` : 'db://assets';
try {
await Editor.Message.request('asset-db', 'refresh-asset', dbUrl);
return `Refreshed asset database for ${dbUrl}`;
} catch (error) {
try {
await Editor.Message.request('asset-db', 'refresh-asset', 'db://assets');
return `Refreshed asset database after writing ${dbUrl}`;
} catch (innerError) {
return `File written, but asset refresh failed: ${innerError.message}`;
}
}
}
return 'File written outside assets directory; no asset-db refresh was needed.';
}
/**
* File-system tools. Kept separate from the registry so path safety and asset
* refresh behavior can be tested and evolved independently.
*/
function createFileTools({ createSchema, getRuntimeContext }) {
return [
{
name: 'read_file',
profile: 'full',
description: '[core] Read a file from the Cocos project.',
inputSchema: createSchema(
{
path: { type: 'string', description: 'Project-relative or absolute file path.' },
},
['path']
),
handler: async (args) => {
const { projectPath } = getRuntimeContext();
const fullPath = resolveProjectPath(projectPath, args.path);
if (!fs.existsSync(fullPath)) {
throw new Error(`File not found: ${args.path}`);
}
const content = fs.readFileSync(fullPath, 'utf8');
return content.length > 12000 ? `${content.slice(0, 12000)}\n... (truncated)` : content;
},
},
{
name: 'get_file_snippet',
profile: 'full',
description: '[core] Read a focused snippet around a file line number.',
inputSchema: createSchema(
{
path: { type: 'string', description: 'Project-relative or absolute file path.' },
line: { type: 'number', description: 'Target line number, starting at 1.' },
contextLines: { type: 'number', description: 'Number of surrounding context lines.' },
},
['path', 'line']
),
handler: async (args) => {
const { projectPath } = getRuntimeContext();
const fullPath = resolveProjectPath(projectPath, args.path);
if (!fs.existsSync(fullPath)) {
throw new Error(`File not found: ${args.path}`);
}
return buildSnippet(fullPath, args.line, Number.isFinite(args.contextLines) ? args.contextLines : 3);
},
},
{
name: 'write_file',
profile: 'full',
description: '[core] Write or overwrite a file in the Cocos project.',
inputSchema: createSchema(
{
path: { type: 'string', description: 'Project-relative or absolute file path.' },
content: { type: 'string', description: 'File content to write.' },
},
['path', 'content']
),
handler: async (args) => {
const { projectPath } = getRuntimeContext();
const fullPath = resolveProjectPath(projectPath, args.path);
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
fs.writeFileSync(fullPath, args.content, 'utf8');
return `Wrote ${args.content.length} chars to ${args.path}\n${await refreshAssets(projectPath, fullPath)}`;
},
},
{
name: 'replace_in_file',
profile: 'full',
description: '[core] Replace text in a file, useful for script auto-fix loops.',
inputSchema: createSchema(
{
path: { type: 'string', description: 'Project-relative or absolute file path.' },
search: { type: 'string', description: 'Literal text to search for.' },
replace: { type: 'string', description: 'Replacement text.' },
replaceAll: { type: 'boolean', description: 'Replace every occurrence instead of only the first.' },
},
['path', 'search', 'replace']
),
handler: async (args) => {
const { projectPath } = getRuntimeContext();
const fullPath = resolveProjectPath(projectPath, args.path);
if (!fs.existsSync(fullPath)) {
throw new Error(`File not found: ${args.path}`);
}
const original = fs.readFileSync(fullPath, 'utf8');
if (!original.includes(args.search)) {
throw new Error(`Search text was not found in ${args.path}`);
}
const updated = args.replaceAll
? replaceAllLiteral(original, args.search, args.replace)
: original.replace(args.search, args.replace);
fs.writeFileSync(fullPath, updated, 'utf8');
return `Updated ${args.path} (${args.replaceAll ? 'all matches' : 'first match'})\n${await refreshAssets(projectPath, fullPath)}`;
},
},
{
name: 'search_files',
profile: 'full',
description: '[core] Search project files by simple wildcard pattern.',
inputSchema: createSchema(
{
pattern: { type: 'string', description: "Wildcard file pattern such as '*.ts' or 'Player*'." },
directory: { type: 'string', description: 'Project-relative search root. Defaults to assets.' },
limit: { type: 'number', description: 'Maximum number of results to return.' },
},
['pattern']
),
handler: async (args) => {
const { projectPath } = getRuntimeContext();
const searchRoot = resolveProjectPath(projectPath, args.directory || 'assets');
if (!fs.existsSync(searchRoot)) {
throw new Error(`Directory not found: ${args.directory || 'assets'}`);
}
const limit = Number.isFinite(args.limit) ? Math.max(1, Math.min(500, args.limit)) : 100;
const results = searchFiles(searchRoot, args.pattern, limit).map((fullPath) =>
path.relative(projectPath, fullPath).replace(/\\/g, '/')
);
return {
count: results.length,
files: results,
};
},
},
{
name: 'list_directory',
profile: 'full',
description: '[core] List files and directories inside a project directory.',
inputSchema: createSchema(
{
path: { type: 'string', description: 'Project-relative or absolute directory path.' },
},
['path']
),
handler: async (args) => {
const { projectPath } = getRuntimeContext();
const targetPath = resolveProjectPath(projectPath, args.path);
if (!fs.existsSync(targetPath) || !fs.statSync(targetPath).isDirectory()) {
throw new Error(`Directory not found: ${args.path}`);
}
const entries = fs
.readdirSync(targetPath, { withFileTypes: true })
.filter((entry) => !entry.name.startsWith('.'))
.map((entry) => ({
name: entry.name,
type: entry.isDirectory() ? 'directory' : 'file',
}));
return {
path: args.path,
entries,
};
},
},
{
name: 'exists',
profile: 'full',
description: '[core] Check whether a project file or directory exists.',
inputSchema: createSchema(
{
path: { type: 'string', description: 'Project-relative or absolute path.' },
},
['path']
),
handler: async (args) => {
const { projectPath } = getRuntimeContext();
const targetPath = resolveProjectPath(projectPath, args.path);
return {
path: args.path,
exists: fs.existsSync(targetPath),
isFile: fs.existsSync(targetPath) ? fs.statSync(targetPath).isFile() : false,
isDirectory: fs.existsSync(targetPath) ? fs.statSync(targetPath).isDirectory() : false,
};
},
},
{
name: 'refresh_assets',
profile: 'full',
description: '[core] Best-effort asset database refresh for a file or the assets root.',
inputSchema: createSchema(
{
path: { type: 'string', description: 'Optional project-relative file path to refresh.' },
},
[]
),
handler: async (args) => {
const { projectPath } = getRuntimeContext();
const targetPath = resolveProjectPath(projectPath, args.path || 'assets');
return await refreshAssets(projectPath, targetPath);
},
},
];
}
module.exports = {
buildSnippet,
createFileTools,
refreshAssets,
};
@@ -0,0 +1,45 @@
'use strict';
function createSceneEventTools({ createSchema, sceneBridge }) {
return [
{
name: 'list_button_click_events',
profile: 'full',
description: '[core] List click event bindings on a Cocos Button component.',
inputSchema: createSchema(
{
path: { type: 'string', description: 'Button node hierarchy path.' },
uuid: { type: 'string', description: 'Button node uuid.' },
name: { type: 'string', description: 'Fallback exact button node name.' },
},
[]
),
handler: async (args) => sceneBridge.call('listButtonClickEvents', args),
},
{
name: 'bind_button_click_event',
profile: 'full',
description: '[core] Bind a Cocos Button click event to a target node component method.',
inputSchema: createSchema(
{
path: { type: 'string', description: 'Button node hierarchy path.' },
uuid: { type: 'string', description: 'Button node uuid.' },
name: { type: 'string', description: 'Fallback exact button node name.' },
targetPath: { type: 'string', description: 'Target node path containing the handler component.' },
targetUuid: { type: 'string', description: 'Target node uuid containing the handler component.' },
targetName: { type: 'string', description: 'Fallback exact target node name.' },
componentName: { type: 'string', description: 'Target component class name.' },
handler: { type: 'string', description: 'Method name to invoke on the target component.' },
customEventData: { type: 'string', description: 'Optional custom event data string.' },
replace: { type: 'boolean', description: 'Replace an identical existing binding.' },
},
['componentName', 'handler']
),
handler: async (args) => sceneBridge.call('bindButtonClickEvent', args),
},
];
}
module.exports = {
createSceneEventTools,
};
+155
View File
@@ -0,0 +1,155 @@
'use strict';
const https = require('https');
const LATEST_RELEASE_URL = 'https://api.github.com/repos/FunplayAI/funplay-cocos-mcp/releases/latest';
const EXTENSION_ZIP_PATTERN = /^Funplay\.CocosMcp\.v.+\.zip$/i;
function normalizeVersion(value) {
return String(value || '')
.trim()
.replace(/^v/i, '')
.split(/[+-]/)[0];
}
function parseVersion(value) {
return normalizeVersion(value)
.split('.')
.map((part) => Number.parseInt(part, 10))
.map((part) => (Number.isFinite(part) ? part : 0));
}
function compareVersions(left, right) {
const leftParts = parseVersion(left);
const rightParts = parseVersion(right);
const length = Math.max(leftParts.length, rightParts.length, 3);
for (let index = 0; index < length; index += 1) {
const leftPart = leftParts[index] || 0;
const rightPart = rightParts[index] || 0;
if (leftPart > rightPart) return 1;
if (leftPart < rightPart) return -1;
}
return 0;
}
function fetchJson(url, timeoutMs = 5000) {
return new Promise((resolve, reject) => {
const request = https.get(
url,
{
headers: {
Accept: 'application/vnd.github+json',
'User-Agent': 'funplay-cocos-mcp-update-checker',
},
timeout: timeoutMs,
},
(response) => {
const chunks = [];
response.on('data', (chunk) => chunks.push(chunk));
response.on('end', () => {
const body = Buffer.concat(chunks).toString('utf8');
if (response.statusCode < 200 || response.statusCode >= 300) {
reject(new Error(`GitHub returned HTTP ${response.statusCode}: ${body.slice(0, 160)}`));
return;
}
try {
resolve(JSON.parse(body));
} catch (error) {
reject(new Error(`Failed to parse GitHub response: ${error.message}`));
}
});
}
);
request.on('timeout', () => {
request.destroy(new Error(`Update check timed out after ${timeoutMs}ms.`));
});
request.on('error', reject);
});
}
function mapReleaseAsset(asset) {
return {
name: String(asset && asset.name || ''),
browserDownloadUrl: String(asset && asset.browser_download_url || asset && asset.browserDownloadUrl || ''),
size: Number(asset && asset.size || 0),
contentType: String(asset && asset.content_type || asset && asset.contentType || ''),
};
}
function selectReleaseAssets(version, assets = []) {
const mapped = (Array.isArray(assets) ? assets : [])
.map(mapReleaseAsset)
.filter((asset) => asset.name && asset.browserDownloadUrl);
const exactZipName = `Funplay.CocosMcp.v${normalizeVersion(version)}.zip`;
const extensionAsset = mapped.find((asset) => asset.name === exactZipName)
|| mapped.find((asset) => EXTENSION_ZIP_PATTERN.test(asset.name))
|| mapped.find((asset) => /\.zip$/i.test(asset.name));
const checksumAsset = mapped.find((asset) => asset.name === 'SHA256SUMS.txt')
|| mapped.find((asset) => /sha256sums/i.test(asset.name));
const manifestAsset = mapped.find((asset) => asset.name === 'release-manifest.json');
return {
assets: mapped,
extensionAsset: extensionAsset || null,
checksumAsset: checksumAsset || null,
manifestAsset: manifestAsset || null,
};
}
async function checkForUpdate(options = {}) {
const currentVersion = normalizeVersion(options.currentVersion || '0.0.0');
const checkedAt = new Date().toISOString();
try {
const release = await fetchJson(options.url || LATEST_RELEASE_URL, options.timeoutMs || 5000);
const latestVersion = normalizeVersion(release.tag_name || release.name || '');
const comparison = latestVersion ? compareVersions(latestVersion, currentVersion) : 0;
const releaseAssets = selectReleaseAssets(latestVersion, release.assets);
return {
ok: true,
checkedAt,
currentVersion,
latestVersion,
updateAvailable: comparison > 0,
releaseUrl: release.html_url || '',
publishedAt: release.published_at || '',
source: options.url || LATEST_RELEASE_URL,
tagName: release.tag_name || '',
releaseName: release.name || '',
assets: releaseAssets.assets,
extensionAsset: releaseAssets.extensionAsset,
checksumAsset: releaseAssets.checksumAsset,
manifestAsset: releaseAssets.manifestAsset,
downloadAvailable: Boolean(releaseAssets.extensionAsset && releaseAssets.checksumAsset),
};
} catch (error) {
return {
ok: false,
checkedAt,
currentVersion,
latestVersion: '',
updateAvailable: false,
releaseUrl: '',
publishedAt: '',
source: options.url || LATEST_RELEASE_URL,
tagName: '',
releaseName: '',
assets: [],
extensionAsset: null,
checksumAsset: null,
manifestAsset: null,
downloadAvailable: false,
error: error.message,
};
}
}
module.exports = {
LATEST_RELEASE_URL,
checkForUpdate,
compareVersions,
normalizeVersion,
selectReleaseAssets,
};
+502
View File
@@ -0,0 +1,502 @@
'use strict';
const crypto = require('crypto');
const fs = require('fs');
const http = require('http');
const https = require('https');
const os = require('os');
const path = require('path');
const zlib = require('zlib');
const { compareVersions, normalizeVersion, selectReleaseAssets } = require('./update-checker');
const PACKAGE_NAME = 'funplay-cocos-mcp';
const MAX_REDIRECTS = 5;
const DEFAULT_TIMEOUT_MS = 30000;
const DEFAULT_MAX_DOWNLOAD_BYTES = 64 * 1024 * 1024;
const DEFAULT_MAX_UNCOMPRESSED_BYTES = 128 * 1024 * 1024;
const DEFAULT_MAX_FILE_BYTES = 32 * 1024 * 1024;
const DEFAULT_MAX_ZIP_ENTRIES = 5000;
function logMessage(log, level, message, details) {
if (typeof log === 'function') {
log(level, message, details);
}
}
function normalizeAsset(asset) {
if (!asset) {
return null;
}
return {
name: String(asset.name || ''),
browserDownloadUrl: String(asset.browserDownloadUrl || asset.browser_download_url || ''),
size: Number(asset.size || 0),
contentType: String(asset.contentType || asset.content_type || ''),
};
}
function parseChecksum(text, fileName) {
const target = path.basename(String(fileName || ''));
for (const line of String(text || '').split(/\r?\n/)) {
const match = /^([a-fA-F0-9]{64})\s+[* ]?(.+?)\s*$/.exec(line.trim());
if (!match) {
continue;
}
const candidate = path.basename(match[2].trim());
if (candidate === target) {
return match[1].toLowerCase();
}
}
return '';
}
function sha256File(filePath) {
return crypto.createHash('sha256').update(fs.readFileSync(filePath)).digest('hex');
}
function assertInside(parent, target) {
const resolvedParent = path.resolve(parent);
const resolvedTarget = path.resolve(target);
const prefix = resolvedParent.endsWith(path.sep) ? resolvedParent : `${resolvedParent}${path.sep}`;
if (resolvedTarget !== resolvedParent && !resolvedTarget.startsWith(prefix)) {
throw new Error(`Unsafe archive path escaped destination: ${target}`);
}
return resolvedTarget;
}
function normalizeArchivePath(value) {
const raw = String(value || '').replace(/\\/g, '/');
if (!raw || raw.includes('\0') || raw.startsWith('/') || /^[A-Za-z]:/.test(raw)) {
throw new Error(`Unsafe archive path: ${raw}`);
}
const normalized = path.posix.normalize(raw);
if (!normalized || normalized === '.' || normalized === '..' || normalized.startsWith('../')) {
throw new Error(`Unsafe archive path: ${raw}`);
}
return normalized;
}
function findEndOfCentralDirectory(buffer) {
const minOffset = Math.max(0, buffer.length - 22 - 0xffff);
for (let offset = buffer.length - 22; offset >= minOffset; offset -= 1) {
if (buffer.readUInt32LE(offset) === 0x06054b50) {
return offset;
}
}
throw new Error('Invalid zip file: end of central directory was not found.');
}
function extractZip(zipPath, destination, options = {}) {
const buffer = fs.readFileSync(zipPath);
const eocd = findEndOfCentralDirectory(buffer);
const entryCount = buffer.readUInt16LE(eocd + 10);
const centralDirectoryOffset = buffer.readUInt32LE(eocd + 16);
const maxEntries = options.maxEntries || DEFAULT_MAX_ZIP_ENTRIES;
const maxFileBytes = options.maxFileBytes || DEFAULT_MAX_FILE_BYTES;
const maxUncompressedBytes = options.maxUncompressedBytes || DEFAULT_MAX_UNCOMPRESSED_BYTES;
if (entryCount > maxEntries) {
throw new Error(`Zip has too many entries: ${entryCount}`);
}
fs.mkdirSync(destination, { recursive: true });
let offset = centralDirectoryOffset;
let totalUncompressed = 0;
const extracted = [];
for (let index = 0; index < entryCount; index += 1) {
if (buffer.readUInt32LE(offset) !== 0x02014b50) {
throw new Error(`Invalid zip central directory entry at offset ${offset}.`);
}
const method = buffer.readUInt16LE(offset + 10);
const compressedSize = buffer.readUInt32LE(offset + 20);
const uncompressedSize = buffer.readUInt32LE(offset + 24);
const nameLength = buffer.readUInt16LE(offset + 28);
const extraLength = buffer.readUInt16LE(offset + 30);
const commentLength = buffer.readUInt16LE(offset + 32);
const localHeaderOffset = buffer.readUInt32LE(offset + 42);
const rawName = buffer.slice(offset + 46, offset + 46 + nameLength).toString('utf8');
offset += 46 + nameLength + extraLength + commentLength;
if (compressedSize === 0xffffffff || uncompressedSize === 0xffffffff || localHeaderOffset === 0xffffffff) {
throw new Error('Zip64 archives are not supported by the built-in updater.');
}
const archivePath = normalizeArchivePath(rawName);
if (archivePath.endsWith('/')) {
fs.mkdirSync(assertInside(destination, path.join(destination, archivePath)), { recursive: true });
continue;
}
if (uncompressedSize > maxFileBytes) {
throw new Error(`Zip entry is too large: ${archivePath}`);
}
totalUncompressed += uncompressedSize;
if (totalUncompressed > maxUncompressedBytes) {
throw new Error('Zip archive expands beyond the safe size limit.');
}
if (buffer.readUInt32LE(localHeaderOffset) !== 0x04034b50) {
throw new Error(`Invalid zip local header for ${archivePath}.`);
}
const localNameLength = buffer.readUInt16LE(localHeaderOffset + 26);
const localExtraLength = buffer.readUInt16LE(localHeaderOffset + 28);
const dataOffset = localHeaderOffset + 30 + localNameLength + localExtraLength;
const compressed = buffer.slice(dataOffset, dataOffset + compressedSize);
let content;
if (method === 0) {
content = compressed;
} else if (method === 8) {
content = zlib.inflateRawSync(compressed);
} else {
throw new Error(`Unsupported zip compression method ${method} for ${archivePath}.`);
}
if (content.length !== uncompressedSize) {
throw new Error(`Zip entry size mismatch for ${archivePath}.`);
}
const targetPath = assertInside(destination, path.join(destination, archivePath));
fs.mkdirSync(path.dirname(targetPath), { recursive: true });
fs.writeFileSync(targetPath, content);
extracted.push(targetPath);
}
return {
entries: entryCount,
files: extracted.length,
totalUncompressedBytes: totalUncompressed,
};
}
function requestUrl(url, options = {}, redirectCount = 0) {
return new Promise((resolve, reject) => {
const parsed = new URL(url);
const client = parsed.protocol === 'http:' ? http : https;
const request = client.get(
parsed,
{
headers: {
'User-Agent': 'funplay-cocos-mcp-updater',
Accept: '*/*',
},
timeout: options.timeoutMs || DEFAULT_TIMEOUT_MS,
},
(response) => {
const status = response.statusCode || 0;
const location = response.headers.location;
if ([301, 302, 303, 307, 308].includes(status) && location) {
response.resume();
if (redirectCount >= MAX_REDIRECTS) {
reject(new Error(`Too many redirects while downloading ${url}`));
return;
}
const redirected = new URL(location, parsed).toString();
requestUrl(redirected, options, redirectCount + 1).then(resolve, reject);
return;
}
if (status < 200 || status >= 300) {
const chunks = [];
response.on('data', (chunk) => chunks.push(chunk));
response.on('end', () => {
const body = Buffer.concat(chunks).toString('utf8').slice(0, 200);
reject(new Error(`Download failed with HTTP ${status}: ${body}`));
});
return;
}
resolve(response);
}
);
request.on('timeout', () => {
request.destroy(new Error(`Download timed out after ${options.timeoutMs || DEFAULT_TIMEOUT_MS}ms.`));
});
request.on('error', reject);
});
}
async function downloadFile(url, destination, options = {}) {
const response = await requestUrl(url, options);
const maxBytes = options.maxBytes || DEFAULT_MAX_DOWNLOAD_BYTES;
await new Promise((resolve, reject) => {
const output = fs.createWriteStream(destination);
let total = 0;
response.on('data', (chunk) => {
total += chunk.length;
if (total > maxBytes) {
response.destroy(new Error(`Download exceeded ${maxBytes} bytes.`));
}
});
response.on('error', reject);
output.on('error', reject);
output.on('finish', resolve);
response.pipe(output);
});
return {
path: destination,
sizeBytes: fs.statSync(destination).size,
};
}
async function downloadText(url, options = {}) {
const response = await requestUrl(url, options);
const maxBytes = options.maxBytes || 1024 * 1024;
return await new Promise((resolve, reject) => {
const chunks = [];
let total = 0;
response.on('data', (chunk) => {
total += chunk.length;
if (total > maxBytes) {
response.destroy(new Error(`Download exceeded ${maxBytes} bytes.`));
return;
}
chunks.push(chunk);
});
response.on('error', reject);
response.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
});
}
function findPackageDirectory(root) {
const direct = path.join(root, PACKAGE_NAME);
if (isExpectedPackageDirectory(direct)) {
return direct;
}
const entries = fs.readdirSync(root, { withFileTypes: true });
for (const entry of entries) {
if (!entry.isDirectory()) {
continue;
}
const candidate = path.join(root, entry.name);
if (isExpectedPackageDirectory(candidate)) {
return candidate;
}
}
throw new Error(`Release archive does not contain a ${PACKAGE_NAME} package directory.`);
}
function isExpectedPackageDirectory(directory) {
const packagePath = path.join(directory, 'package.json');
if (!fs.existsSync(packagePath)) {
return false;
}
try {
const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
return pkg.name === PACKAGE_NAME;
} catch (error) {
return false;
}
}
function validatePackageDirectory(directory, expectedVersion) {
const packagePath = path.join(directory, 'package.json');
const pkg = JSON.parse(fs.readFileSync(packagePath, 'utf8'));
const version = normalizeVersion(pkg.version);
if (pkg.name !== PACKAGE_NAME) {
throw new Error(`Update package name mismatch: ${pkg.name}`);
}
if (expectedVersion && version !== normalizeVersion(expectedVersion)) {
throw new Error(`Update package version ${version} does not match release ${expectedVersion}.`);
}
if (!pkg.main || !fs.existsSync(path.join(directory, pkg.main))) {
throw new Error('Update package main file is missing.');
}
return {
name: pkg.name,
version,
packageVersion: pkg.package_version || pkg.packageVersion || 0,
};
}
function hasGitMetadata(directory) {
return fs.existsSync(path.join(directory, '.git'));
}
function pathEntryExists(targetPath) {
try {
fs.lstatSync(targetPath);
return true;
} catch (error) {
if (error && error.code === 'ENOENT') {
return false;
}
throw error;
}
}
function assertInstallablePackagePath(packagePath, options = {}) {
if (!pathEntryExists(packagePath)) {
return;
}
const stat = fs.lstatSync(packagePath);
if (stat.isSymbolicLink() && !options.allowSymlinkInstall) {
throw new Error('One-click update is disabled for symlink installs. Use git pull, Cocos Store, or replace the extension manually.');
}
if (hasGitMetadata(packagePath) && !options.allowGitWorktreeInstall) {
throw new Error('One-click update is disabled inside a git worktree. Use git pull or install the release package manually.');
}
}
function timestampForPath(date = new Date()) {
return date.toISOString().replace(/[:.]/g, '-');
}
function copyDirectoryContents(source, destination) {
fs.mkdirSync(destination, { recursive: true });
for (const entry of fs.readdirSync(source)) {
fs.cpSync(path.join(source, entry), path.join(destination, entry), {
recursive: true,
force: true,
});
}
}
function cleanDirectory(directory) {
fs.mkdirSync(directory, { recursive: true });
for (const entry of fs.readdirSync(directory)) {
fs.rmSync(path.join(directory, entry), { recursive: true, force: true });
}
}
function restoreBackup(backupDir, packagePath) {
cleanDirectory(packagePath);
copyDirectoryContents(backupDir, packagePath);
}
async function installLatestUpdate(options = {}) {
const releaseInfo = options.releaseInfo || {};
const currentVersion = normalizeVersion(options.currentVersion || releaseInfo.currentVersion || '0.0.0');
const latestVersion = normalizeVersion(releaseInfo.latestVersion || releaseInfo.tagName || '');
const packagePath = path.resolve(options.packagePath || path.join(__dirname, '..'));
const packagePathExisted = pathEntryExists(packagePath);
const timeoutMs = options.timeoutMs || DEFAULT_TIMEOUT_MS;
const log = options.log;
if (!latestVersion) {
throw new Error('Latest release version is unknown.');
}
if (!options.force && compareVersions(latestVersion, currentVersion) <= 0) {
throw new Error(`Already up to date: ${currentVersion}.`);
}
assertInstallablePackagePath(packagePath, options);
const selected = selectReleaseAssets(latestVersion, releaseInfo.assets || []);
const extensionAsset = normalizeAsset(releaseInfo.extensionAsset) || selected.extensionAsset;
const checksumAsset = normalizeAsset(releaseInfo.checksumAsset) || selected.checksumAsset;
if (!extensionAsset || !extensionAsset.browserDownloadUrl) {
throw new Error('Latest release does not include a downloadable extension zip.');
}
if (!checksumAsset || !checksumAsset.browserDownloadUrl) {
throw new Error('Latest release does not include SHA256SUMS.txt, so one-click update was refused.');
}
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'funplay-cocos-mcp-update-'));
const downloadDir = path.join(tempRoot, 'downloads');
const extractDir = path.join(tempRoot, 'extract');
fs.mkdirSync(downloadDir, { recursive: true });
fs.mkdirSync(extractDir, { recursive: true });
const zipPath = path.join(downloadDir, path.basename(extensionAsset.name));
const checksumPath = path.join(downloadDir, 'SHA256SUMS.txt');
let backupDir = '';
try {
logMessage(log, 'info', `Downloading update package ${extensionAsset.name}...`);
await downloadFile(extensionAsset.browserDownloadUrl, zipPath, {
timeoutMs,
maxBytes: options.maxDownloadBytes || DEFAULT_MAX_DOWNLOAD_BYTES,
});
await downloadFile(checksumAsset.browserDownloadUrl, checksumPath, {
timeoutMs,
maxBytes: 1024 * 1024,
});
const expectedSha256 = parseChecksum(fs.readFileSync(checksumPath, 'utf8'), extensionAsset.name);
if (!expectedSha256) {
throw new Error(`SHA256SUMS.txt does not contain a checksum for ${extensionAsset.name}.`);
}
const actualSha256 = sha256File(zipPath);
if (actualSha256 !== expectedSha256) {
throw new Error(`Checksum mismatch for ${extensionAsset.name}.`);
}
logMessage(log, 'info', `Checksum verified for ${extensionAsset.name}.`);
const extraction = extractZip(zipPath, extractDir, options);
const extractedPackage = findPackageDirectory(extractDir);
const packageInfo = validatePackageDirectory(extractedPackage, latestVersion);
if (pathEntryExists(packagePath) !== packagePathExisted) {
throw new Error('The extension install path changed while the release was downloading. Try again.');
}
assertInstallablePackagePath(packagePath, options);
if (packagePathExisted) {
const backupRoot = path.join(path.dirname(packagePath), '.funplay-cocos-mcp-backups');
backupDir = path.join(backupRoot, `${path.basename(packagePath)}-${timestampForPath()}`);
fs.mkdirSync(backupRoot, { recursive: true });
copyDirectoryContents(packagePath, backupDir);
} else {
fs.mkdirSync(path.dirname(packagePath), { recursive: true });
}
logMessage(
log,
'info',
packagePathExisted
? `Replacing extension package. Backup: ${backupDir}`
: `Installing extension package at ${packagePath}`
);
try {
if (packagePathExisted) {
cleanDirectory(packagePath);
} else {
fs.mkdirSync(packagePath, { recursive: true });
}
copyDirectoryContents(extractedPackage, packagePath);
} catch (error) {
if (backupDir) {
restoreBackup(backupDir, packagePath);
} else {
fs.rmSync(packagePath, { recursive: true, force: true });
}
throw error;
}
return {
ok: true,
installed: true,
currentVersion,
installedVersion: packageInfo.version,
backupDir,
packagePath,
zipName: extensionAsset.name,
zipSha256: actualSha256,
checksumVerified: true,
extraction,
};
} finally {
if (!options.keepTemp) {
fs.rmSync(tempRoot, { recursive: true, force: true });
}
}
}
module.exports = {
downloadFile,
downloadText,
extractZip,
installLatestUpdate,
parseChecksum,
sha256File,
validatePackageDirectory,
};
+31
View File
@@ -0,0 +1,31 @@
'use strict';
function safeJsonParse(text, fallback = null) {
try {
return JSON.parse(text);
} catch (error) {
return fallback;
}
}
function safeStringify(value) {
const seen = new WeakSet();
return JSON.stringify(
value,
(key, current) => {
if (typeof current === 'object' && current !== null) {
if (seen.has(current)) {
return '[Circular]';
}
seen.add(current);
}
return current;
},
2
);
}
module.exports = {
safeJsonParse,
safeStringify,
};
@@ -0,0 +1,204 @@
'use strict';
const crypto = require('crypto');
const path = require('path');
const electronTools = require('./electron-tools');
const CAPTURE_TTL_MS = 60000;
const MAX_CAPTURES = 32;
const captures = new Map();
const inputWindows = new WeakSet();
// Serialized into the target renderer. Read display geometry, not business data.
function windowGeometry() {
const key = Symbol.for('funplay-cocos-mcp.visual-geometry');
const state = window[key] || (window[key] = { ids: new WeakMap(), nextId: 1 });
const identity = (node) => {
if (!state.ids.has(node)) state.ids.set(node, state.nextId++);
return state.ids.get(node);
};
const canvases = [];
const frames = [];
let visited = 0;
let complete = true;
const rectOf = (node) => {
const rect = node.getBoundingClientRect();
const style = window.getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden' || rect.width <= 0 || rect.height <= 0) return null;
return { x: rect.left, y: rect.top, width: rect.width, height: rect.height };
};
const collect = (root) => {
for (const node of root.querySelectorAll('*')) {
if (++visited > 15000) { complete = false; return; }
const tag = node.tagName && node.tagName.toLowerCase();
if (tag === 'canvas') {
const rect = rectOf(node);
if (rect) {
if (canvases.length >= 64) { complete = false; return; }
canvases.push({ id: identity(node), rect, width: node.width, height: node.height });
}
} else if (tag === 'iframe' || tag === 'webview') {
const rect = rectOf(node);
if (rect) {
if (frames.length >= 64) { complete = false; return; }
let epoch = null;
try { epoch = node.contentWindow.performance.timeOrigin; } catch (error) { /* Cross-origin frames are identified by element/src only. */ }
frames.push({ id: identity(node), rect, src: node.getAttribute('src') || '', epoch });
}
}
if (node.shadowRoot) collect(node.shadowRoot);
if (!complete) return;
}
};
collect(document);
return {
width: window.innerWidth, height: window.innerHeight,
devicePixelRatio: window.devicePixelRatio, documentEpoch: performance.timeOrigin,
scrollX: window.scrollX, scrollY: window.scrollY,
url: window.location.href, canvases, frames, complete,
};
}
function boundedRead(read) {
return new Promise((resolve, reject) => {
const timer = setTimeout(() => reject(new Error('Visual geometry query timed out. Recapture after the editor becomes responsive.')), 1500);
Promise.resolve().then(read).then(
(value) => { clearTimeout(timer); resolve(value); },
(error) => { clearTimeout(timer); reject(error); }
);
});
}
function usableWindow(window) {
if (!window || typeof window.isDestroyed === 'function' && window.isDestroyed()) throw new Error('The captured window is no longer available.');
if (typeof window.isVisible === 'function' && !window.isVisible() ||
typeof window.isMinimized === 'function' && window.isMinimized()) {
throw new Error('A visible, non-minimized window is required for calibrated screenshots/input.');
}
if (!window.webContents || typeof window.webContents.isDestroyed === 'function' && window.webContents.isDestroyed()) {
throw new Error('The captured renderer is no longer available.');
}
}
async function readVisualState(window, panel, getContext) {
usableWindow(window);
const renderer = await boundedRead(() => electronTools.executeJavaScript(window, `(${windowGeometry.toString()})()`));
if (!renderer || !Number.isFinite(renderer.width) || renderer.width <= 0 || !Number.isFinite(renderer.height) || renderer.height <= 0 || renderer.complete !== true) {
throw new Error('Complete visible-window geometry is unavailable; calibrated input is not safe.');
}
const zoomFactor = typeof window.webContents.getZoomFactor === 'function' ? window.webContents.getZoomFactor() : 1;
if (!Number.isFinite(zoomFactor) || zoomFactor <= 0) throw new Error('The renderer zoom factor is unavailable.');
const panelBounds = panel ? await boundedRead(() => electronTools.getPanelBounds(window, panel)) : null;
const windowWidth = Math.round(renderer.width * zoomFactor);
const windowHeight = Math.round(renderer.height * zoomFactor);
const css = panelBounds || { x: 0, y: 0, width: renderer.width, height: renderer.height };
if (![css.x, css.y, css.width, css.height].every(Number.isFinite) || css.width <= 0 || css.height <= 0) {
throw new Error('The capture region has invalid geometry.');
}
// Electron capturePage/sendInputEvent use content coordinates; DOM bounds are zoomed CSS coordinates.
const x = Math.max(0, Math.floor(css.x * zoomFactor));
const y = Math.max(0, Math.floor(css.y * zoomFactor));
const right = Math.min(windowWidth, Math.ceil((css.x + css.width) * zoomFactor));
const bottom = Math.min(windowHeight, Math.ceil((css.y + css.height) * zoomFactor));
if (right <= x || bottom <= y) throw new Error('The requested capture region is outside the visible window.');
const inputBounds = { x, y, width: right - x, height: bottom - y };
const context = getContext ? await boundedRead(getContext) : null;
const signature = crypto.createHash('sha256').update(JSON.stringify({ renderer, zoomFactor, inputBounds, context })).digest('hex');
return {
signature, inputBounds, panelBounds,
viewport: { width: windowWidth, height: windowHeight, cssWidth: renderer.width, cssHeight: renderer.height, devicePixelRatio: renderer.devicePixelRatio, zoomFactor },
context,
};
}
function pngDimensions(png) {
if (!Buffer.isBuffer(png) || png.length < 24 || !png.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) || png.toString('ascii', 12, 16) !== 'IHDR') {
throw new Error('Screenshot did not contain a PNG with measurable dimensions.');
}
const width = png.readUInt32BE(16);
const height = png.readUInt32BE(20);
if (!width || !height) throw new Error('Screenshot PNG has empty dimensions.');
return { width, height };
}
function registerCapture(window, png, before, after, options = {}) {
const image = pngDimensions(png);
const capturedAt = Date.now();
for (const [id, entry] of captures) if (capturedAt - entry.createdAt > CAPTURE_TTL_MS) captures.delete(id);
while (captures.size >= MAX_CAPTURES) captures.delete(captures.keys().next().value);
const captureId = `capture_${crypto.randomBytes(12).toString('hex')}`;
const interactive = before.signature === after.signature;
const geometry = {
schemaVersion: 1, captureId, capturedAt: new Date(capturedAt).toISOString(),
coordinateSpace: 'image-pixels', origin: 'top-left',
windowId: window.id, webContentsId: window.webContents.id,
panel: options.panel || null, image, viewport: before.viewport,
inputBounds: before.inputBounds,
imageToWindowScale: { x: before.inputBounds.width / image.width, y: before.inputBounds.height / image.height },
interactive, expiresAfterMs: CAPTURE_TTL_MS,
reason: interactive ? null : 'geometry_changed_during_capture',
editorScene: before.context,
projectContext: options.projectContext || null,
runtimeContentVerified: false,
};
captures.set(captureId, {
window, webContents: window.webContents, geometry, createdAt: capturedAt,
signature: before.signature, getContext: options.getContext,
projectPath: options.projectPath ? path.resolve(options.projectPath) : '',
inputOwner: options.inputOwner || '',
});
return geometry;
}
function captureRecord(options) {
if (typeof options.captureId !== 'string' || !options.captureId) throw new Error('captureId is required for image-pixels input.');
const record = captures.get(options.captureId);
if (!record) throw new Error('Unknown or expired captureId. Capture a new screenshot; do not guess a target window.');
if (Date.now() - record.createdAt > CAPTURE_TTL_MS) {
captures.delete(options.captureId);
throw new Error('The screenshot is stale. Capture a new screenshot before sending input.');
}
if (!record.geometry.interactive) throw new Error('Geometry changed during screenshot capture. Capture a new stable image.');
if (record.projectPath && (!options.projectPath || path.resolve(options.projectPath) !== record.projectPath)) throw new Error('The screenshot belongs to a different project.');
if (record.inputOwner && options.inputOwner !== record.inputOwner) throw new Error('The screenshot belongs to a different Editor session. Recapture before input.');
usableWindow(record.window);
if (record.window.webContents !== record.webContents) throw new Error('The captured renderer was replaced. Recapture.');
if (options.windowId !== undefined && options.windowId !== record.geometry.windowId) throw new Error('windowId does not match the screenshot.');
if (options.panel && options.panel !== record.geometry.panel) throw new Error('panel does not match the screenshot.');
if (options.titleContains && !String(record.window.getTitle()).toLowerCase().includes(String(options.titleContains).toLowerCase())) throw new Error('The target title does not match the screenshot window.');
if (options.windowKind && options.windowKind !== 'focused' && options.windowKind !== electronTools.inferWindowKind(record.window.getTitle())) throw new Error('windowKind does not match the screenshot window. Use its windowId.');
return record;
}
function getCaptureWindow(options) {
return captureRecord(options).window;
}
async function resolveImagePoints(options, points) {
const record = captureRecord(options);
const geometry = record.geometry;
const mapped = points.map((point) => {
if (!Number.isFinite(point.x) || !Number.isFinite(point.y) || point.x < 0 || point.y < 0 || point.x >= geometry.image.width || point.y >= geometry.image.height) {
throw new Error('Image coordinates must be finite and inside the exact captured PNG.');
}
return {
x: Math.min(geometry.inputBounds.x + geometry.inputBounds.width - 1, Math.floor(geometry.inputBounds.x + point.x * geometry.imageToWindowScale.x)),
y: Math.min(geometry.inputBounds.y + geometry.inputBounds.height - 1, Math.floor(geometry.inputBounds.y + point.y * geometry.imageToWindowScale.y)),
};
});
const state = await readVisualState(record.window, geometry.panel, record.getContext);
captureRecord(options); // A long read or concurrent capture may have expired/evicted this receipt.
if (state.signature !== record.signature) throw new Error('Window, viewport, renderer, panel, or editor scene changed since capture. Recapture before input.');
return { window: record.window, points: mapped, captureId: geometry.captureId, panel: geometry.panel, coordinateSpace: 'image-pixels' };
}
function acquireInputWindow(window) {
if (inputWindows.has(window)) throw new Error('A calibrated input operation is already active in this window.');
inputWindows.add(window);
return () => inputWindows.delete(window);
}
module.exports = {
CAPTURE_TTL_MS, MAX_CAPTURES, acquireInputWindow, getCaptureWindow, pngDimensions,
readVisualState, registerCapture, resolveImagePoints,
};
+296
View File
@@ -0,0 +1,296 @@
{
"name": "funplay-cocos-mcp",
"title": "i18n:funplay-cocos-mcp.title",
"package_version": 2,
"version": "0.7.6",
"description": "Embedded MCP server for Cocos Creator with scene script execution, project resources, prompts, and file/scene tools.",
"author": "Funplay",
"license": "MIT",
"main": "browser.js",
"bin": {
"funplay-cocos-mcp": "bin/funplay-cocos-mcp.js"
},
"mcpName": "io.github.FunplayAI/funplay-cocos-mcp",
"repository": {
"type": "git",
"url": "git+https://github.com/FunplayAI/funplay-cocos-mcp.git"
},
"homepage": "https://github.com/FunplayAI/funplay-cocos-mcp#readme",
"bugs": {
"url": "https://github.com/FunplayAI/funplay-cocos-mcp/issues"
},
"keywords": [
"mcp",
"cocos",
"cocos-creator",
"funplay",
"model-context-protocol",
"ai"
],
"engines": {
"node": ">=18"
},
"files": [
"bin/",
"docs/",
"lib/",
"i18n/",
"panel/",
"browser.js",
"scene.js",
"server.json",
"README.md",
"README_CN.md",
"CHANGELOG.md",
"CONTRIBUTING.md",
"LICENSE",
"RELEASE_WORKFLOW.md",
"RELEASE_CHECKLIST.md"
],
"publishConfig": {
"access": "public"
},
"scripts": {
"check": "node --check lib/project-context.js && node --check lib/input-frames.js && node --check lib/jsonc.js && node --check lib/preview-runtime.js && node --check browser.js && node --check scene.js && node --check panel/index.js && node --check panel/contact.js && node --check panel/shared.js && node --check panel/tool-description-i18n.js && node --check panel/tool-exposure.js && node --check panel/settings.js && node --check panel/project-skills.js && node --check bin/funplay-cocos-mcp.js && node --check i18n/en.js && node --check i18n/zh.js && node --check lib/activity-preview.js && node --check lib/script-execution.js && node --check lib/atomic-file.js && node --check lib/project-prompts.js && node --check lib/skill-platforms.js && node --check lib/asset-readiness.js && node --check lib/assets.js && node --check lib/client-config.js && node --check lib/config.js && node --check lib/diagnostics.js && node --check lib/electron-tools.js && node --check lib/global-install.js && node --check lib/i18n.js && node --check lib/input.js && node --check lib/interaction-log.js && node --check lib/javascript-safety.js && node --check lib/logs.js && node --check lib/path-safety.js && node --check lib/prefab-metadata.js && node --check lib/prefabs.js && node --check lib/project-instructions.js && node --check lib/project-skills.js && node --check lib/project-skill-references.js && node --check lib/prompts.js && node --check lib/resources.js && node --check lib/runtime-log.js && node --check lib/scenes.js && node --check lib/screenshots.js && node --check lib/visual-coordinates.js && node --check lib/server.js && node --check lib/tool-profiles.js && node --check lib/tool-registry.js && node --check lib/tools/assets-advanced.js && node --check lib/tools/cocos-project.js && node --check lib/tools/files.js && node --check lib/tools/scene-events.js && node --check lib/update-checker.js && node --check lib/updater.js && node --check lib/utils.js && node --check scripts/generate-tool-docs.js && node --check scripts/release.js",
"test": "node --test",
"docs:generate": "node scripts/generate-tool-docs.js",
"docs:check": "node scripts/generate-tool-docs.js --check",
"pack:dry-run": "npm pack --dry-run",
"registry:validate": "mcp-publisher validate server.json",
"release:check": "node scripts/release.js check && npm run docs:check",
"release:package": "node scripts/release.js package",
"release:verify": "npm run check && npm test && npm run release:check && npm run pack:dry-run && npm run release:package"
},
"panels": {
"default": {
"title": "i18n:funplay-cocos-mcp.panel_server",
"type": "dockable",
"main": "panel/index.js",
"size": {
"min-width": 420,
"min-height": 360,
"width": 560,
"height": 620
}
},
"tool-exposure": {
"title": "i18n:funplay-cocos-mcp.panel_tool_exposure",
"type": "dockable",
"main": "panel/tool-exposure.js",
"size": {
"min-width": 560,
"min-height": 460,
"width": 760,
"height": 760
}
},
"settings": {
"title": "i18n:funplay-cocos-mcp.panel_settings",
"type": "dockable",
"main": "panel/settings.js",
"size": {
"min-width": 460,
"min-height": 360,
"width": 620,
"height": 620
}
},
"project-skills": {
"title": "i18n:funplay-cocos-mcp.panel_project_skills",
"type": "dockable",
"main": "panel/project-skills.js",
"size": {
"min-width": 580,
"min-height": 480,
"width": 780,
"height": 760
}
},
"contact": {
"title": "i18n:funplay-cocos-mcp.panel_contact",
"type": "simple",
"main": "panel/contact.js",
"size": {
"min-width": 420,
"min-height": 320,
"width": 520,
"height": 400
}
}
},
"contributions": {
"menu": [
{
"path": "Funplay",
"label": "i18n:funplay-cocos-mcp.menu_server",
"message": "open-panel"
},
{
"path": "Funplay",
"label": "i18n:funplay-cocos-mcp.menu_tool_exposure",
"message": "open-tool-exposure"
},
{
"path": "Funplay",
"label": "i18n:funplay-cocos-mcp.menu_settings",
"message": "open-settings"
},
{
"path": "Funplay",
"label": "i18n:funplay-cocos-mcp.menu_project_skills",
"message": "open-project-skills"
},
{
"path": "Funplay",
"label": "i18n:funplay-cocos-mcp.menu_contact",
"message": "open-contact"
}
],
"messages": {
"open-panel": {
"methods": [
"openPanel"
]
},
"open-tool-exposure": {
"methods": [
"openToolExposurePanel"
]
},
"open-settings": {
"methods": [
"openSettingsPanel"
]
},
"open-project-skills": {
"methods": [
"openProjectSkillsPanel"
]
},
"open-contact": {
"methods": [
"openContactPanel"
]
},
"start-server": {
"methods": [
"startServer"
]
},
"stop-server": {
"methods": [
"stopServer"
]
},
"restart-server": {
"methods": [
"restartServer"
]
},
"get-status": {
"methods": [
"getStatus"
]
},
"get-panel-state": {
"methods": [
"getPanelState"
]
},
"clear-recent-activity": {
"methods": [
"clearRecentActivity"
]
},
"save-config": {
"methods": [
"saveConfig"
]
},
"list-tools": {
"methods": [
"listToolsForPanel"
]
},
"call-tool": {
"methods": [
"callToolFromPanel"
]
},
"get-project-skills-state": {
"methods": [
"getProjectSkillsState"
]
},
"preview-project-skill-update": {
"methods": [
"previewProjectSkillUpdate"
]
},
"install-or-update-project-skill": {
"methods": [
"installOrUpdateProjectSkill"
]
},
"restore-project-skill-backup": {
"methods": [
"restoreProjectSkillBackup"
]
},
"create-project-skill": {
"methods": [
"createProjectSkillFromPanel"
]
},
"reveal-project-skill": {
"methods": [
"revealProjectSkill"
]
},
"check-updates": {
"methods": [
"checkUpdates"
]
},
"auto-check-updates": {
"methods": [
"autoCheckUpdates"
]
},
"install-update": {
"methods": [
"installUpdate"
]
},
"install-globally": {
"methods": [
"installGlobally"
]
},
"open-update-release": {
"methods": [
"openUpdateRelease"
]
},
"read-resource": {
"methods": [
"readResourceFromPanel"
]
},
"get-client-config": {
"methods": [
"getClientConfig"
]
},
"configure-client": {
"methods": [
"configureClient"
]
}
},
"scene": {
"script": "scene.js"
}
},
"_storeId": "8f97142faa9e6a81400a34b7ec5a5973"
}
+5
View File
@@ -0,0 +1,5 @@
'use strict';
const { createPanel } = require('./shared');
module.exports = createPanel('contact');
+5
View File
@@ -0,0 +1,5 @@
'use strict';
const { createPanel } = require('./shared');
module.exports = createPanel('dashboard');
@@ -0,0 +1,5 @@
'use strict';
const { createPanel } = require('./shared');
module.exports = createPanel('project-skills');
+5
View File
@@ -0,0 +1,5 @@
'use strict';
const { createPanel } = require('./shared');
module.exports = createPanel('settings');
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,143 @@
'use strict';
const ZH_PROFILE_LABELS = {
primary: '主要',
compat: '兼容',
specialist: '专用',
core: '核心',
};
const ZH_TOOL_DESCRIPTIONS = {
execute_javascript: '在场景或编辑器上下文中执行 JavaScript。使用 context="scene" 检查和修改实时场景或运行时;使用 context="editor" 调用 Editor API、处理 asset-db、编排 MCP、访问本地文件系统及执行高级自动化。当多个窄工具会产生过多调用时,优先使用此主要通用工具。',
execute_scene_script: '在当前 Cocos 场景上下文中执行 JavaScript。优先使用 context="scene" 的 execute_javascript 作为统一入口;仅在明确需要场景专用兼容入口时使用此工具。',
execute_editor_script: '在编辑器或浏览器上下文中执行 JavaScript。优先使用 context="editor" 的 execute_javascript 作为统一入口;仅在明确需要编辑器专用兼容入口时使用此工具。',
get_editor_state: '返回结构化编辑器状态快照,包括项目信息、运行时服务状态、当前选择和可见的 Electron 窗口。需要一份紧凑编辑器摘要时优先使用。',
get_tool_catalog: '返回所有内置 MCP 工具及其 profile、分类和当前开放状态。修改自定义工具开放范围前使用。',
check_for_updates: '检查最新的 Funplay Cocos MCP GitHub Release,并与当前安装版本比较。',
check_asset_ready: '有界检查 AssetDB 就绪状态;可核对指定资源已导入的 UUID/URL 身份及连续稳定读取。不证明导入队列、脚本编译、源文件内容或预览加载已完成。',
get_selection: '以紧凑结构返回当前编辑器选择。下一步操作依赖选择状态时优先使用。',
list_project_instructions: '列出项目 AI 指令文件和所选客户端的本地项目技能。',
read_project_instruction: '读取 AGENTS.md、CLAUDE.md 或客户端技能目录下的 SKILL.md 等项目 AI 指令文件。',
write_project_instruction: '在 Cocos 项目内创建或更新项目 AI 指令文件。',
create_project_skill: '在所选客户端的技能目录创建项目技能,默认使用 Codex 的 .agents/skills。',
create_cocos_mcp_project_skill: '为所选客户端创建推荐的 Funplay Cocos MCP 项目工作流技能。',
set_selection: '设置或清除编辑器中选中的资源或节点。后续编辑器流程依赖选择状态时使用。',
get_scene_info: '返回当前 Cocos 场景的结构化摘要。多步检查或修改优先使用 execute_javascript;仅需要紧凑场景快照时使用此工具。',
get_hierarchy: '返回当前场景或指定节点路径下的结构化层级树。复杂推理或修复优先使用 execute_javascript;需要稳定层级快照时使用此工具。',
find_nodes: '按精确名称、部分路径或组件类型查找场景节点。',
inspect_node: '按路径、uuid 或名称检查指定节点。',
create_node: '在当前场景或指定父节点路径下创建新节点。',
delete_node: '按路径、uuid 或名称删除节点。',
set_node_transform: '更新节点的位置、旋转、缩放或激活状态。',
get_project_info: '返回当前 Cocos 项目路径、版本和 MCP 服务配置。需要快速结构化项目摘要时优先使用;需要在检查后立即操作时使用 execute_javascript。',
save_current_scene: '使用可用的编辑器场景消息保存当前打开的 Cocos 场景。',
open_build_panel: '打开 Cocos 构建面板,默认使用 builder 面板 ID。',
get_build_status: '通过已知的 builder 消息变体查询 Cocos 构建和预览状态。',
get_preview_mode: '查询当前 Cocos Creator 预览模式。浏览器模式下,url/localUrl 返回同机 loopback 地址,networkUrl 保留 Creator 返回的局域网地址。',
set_preview_mode: '通过 Cocos Creator 3.8.x 原生工具栏切换预览模式并同步状态;离开 Game View 前先停止预览。',
run_project_preview: '在浏览器、编辑器 Game View 或模拟器中启动 Cocos Creator 3.8.x 预览。Game View 使用原生工具栏,重复调用不会停止已运行的预览。浏览器模式下,url/localUrl 返回同机 loopback 地址,networkUrl 保留 Creator 返回的局域网地址。',
get_editor_preference: '在 Editor.Profile 可用时读取 Cocos 编辑器偏好设置。',
set_editor_preference: '在 Editor.Profile 可用时写入 Cocos 编辑器偏好设置。',
broadcast_editor_message: '发送或广播 Cocos 编辑器消息,用于高级编辑器自动化。',
create_scene: '在明确的 assets 路径创建空场景或当前场景副本,不打开交互式保存对话框。',
list_scenes: '列出项目中的场景资源。打开场景前需要精确查找时优先使用;更广泛的工作流使用 execute_javascript。',
open_scene: '按 uuid、db url 或路径在 Cocos Creator 中打开场景资源。明确需要切换场景时使用;其他情况继续以 execute_javascript 作为主要规划工具。',
list_prefabs: '列出项目中的 Prefab 资源。',
inspect_prefab: '检查 Prefab 资源、元数据、序列化文件路径和类似 UUID 的资源引用。',
validate_prefab_references: '通过 asset-db 检查序列化 UUID 引用,验证 Prefab 资源引用。',
duplicate_prefab: '复制现有 Prefab 文件创建新 Prefab 资源,但不复制其 .meta UUID。',
edit_prefab_json: '通过 JSON 路径赋值或文本查找替换编辑 Prefab JSON 文件,然后验证引用。',
create_prefab_from_node: '通过场景进程序列化和 asset-db 持久化,从现有场景节点创建 Prefab 资源。克隆的节点树会统一设为 UI_2D,源场景节点保持不变。在 Cocos Creator 3.8.x 中使用此工具替代原始 scene:create-prefab。',
create_prefab_instance: '在可用时使用 Cocos 场景 create-node 消息,在编辑器层级中创建并验证关联的 Prefab 实例。',
inspect_prefab_instance: '检查场景节点是否关联到 Prefab 实例,并在可用时返回 Prefab 元数据。',
apply_prefab_instance: '使用 Cocos 编辑器场景 apply-prefab 消息,将场景中的 Prefab 实例改动应用回关联资源。',
revert_prefab_instance: '使用可用的 Cocos 编辑器 Prefab 还原消息,将场景 Prefab 实例还原为关联资源状态。',
instantiate_prefab: '按 Prefab uuid 将 Prefab 实例化到当前场景。',
run_scene_asset: '按 uuid 将场景资源直接加载到当前运行时场景上下文。',
list_assets: '按模式或资源类型从 asset-db 查询项目资源。需要精确查找资源时优先使用;更广泛的自动化使用 execute_javascript。',
inspect_asset: '按 uuid 或路径检查 asset-db 信息、元数据和序列化资源数据。需要精确结构化资源读取时优先使用。',
open_asset: '按 uuid、db url 或路径在 Cocos Creator 中打开资源。仅当明确需要打开资源本身时使用。',
delete_asset: '按 uuid、db url 或路径从 asset-db 删除资源。',
select_asset: '在 Cocos 编辑器中选择资源。编辑器选择状态很重要时使用;其他情况继续以 execute_javascript 作为主要工作流。',
inspect_asset_dependencies: '检查 Cocos 序列化资源中引用的 UUID 类型依赖。',
validate_asset_dependencies: '验证单个资源或项目资源查询结果中的 UUID 类型依赖。',
get_editor_selection: '返回 Cocos 编辑器当前选择的节点和资源。优先使用 get_selection 作为主要结构化选择读取工具。',
list_components: '列出场景节点上挂载的组件。',
inspect_component: '检查节点上挂载的组件。',
add_component: '按组件类名向节点添加组件。',
remove_component: '按名称或索引从节点移除组件。',
set_component_property: '使用 JSON 值按点路径设置组件属性。',
reset_component_property: '按点路径重置或清除组件属性。',
create_canvas: '创建带有 UITransform 的 Cocos Canvas 节点。',
create_label: '在父节点下创建 UI Label 节点。',
create_button: '创建带有子 Label 的 UI Button 节点。',
create_sprite: '创建 UI Sprite 节点,并可选择指定 SpriteFrame 资源 uuid。',
list_cameras: '列出当前场景中的 Camera 组件。',
create_camera: '在当前场景中创建 Camera 节点。',
set_camera_properties: '设置所选 Camera 组件的属性。',
list_animations: '列出当前场景或指定节点下的 Animation 组件。',
add_animation_clip: '向节点的 Animation 组件添加 AnimationClip 资源。',
play_animation: '在节点上播放 Animation 组件中的动画片段。',
stop_animation: '停止节点上 Animation 组件播放的动画片段。',
read_file: '读取 Cocos 项目中的文件。',
get_file_snippet: '读取文件指定行附近的聚焦代码片段。',
write_file: '写入或覆盖 Cocos 项目中的文件。',
replace_in_file: '替换文件中的文本,适合脚本自动修复循环。',
search_files: '使用简单通配符模式搜索项目文件。',
list_directory: '列出项目目录内的文件和子目录。',
exists: '检查项目文件或目录是否存在。',
refresh_assets: '尽力刷新指定文件或 assets 根目录的资源数据库。',
run_script_diagnostics: '对当前 Cocos 项目运行 TypeScript no-emit 检查并返回解析后的诊断。需要诊断脚本错误时优先使用此专用工具。',
get_recent_logs: '返回最近的 MCP 运行日志、工具调用记录和常见项目日志文件尾部内容。',
search_project_logs: '使用字符串或正则表达式搜索常见 Cocos 项目日志文件。',
clear_logs: '清除内存中的 MCP 日志;仅在明确确认后截断常见项目日志文件。',
validate_scene: '对当前场景、运行时状态、TypeScript 诊断和最近项目日志错误执行紧凑验证。',
get_performance_snapshot: '返回编辑场景规模和性能计数,包括节点/组件数量、UI 数量、深度、内存和警告;director 计数不是 Game View 的预览运行态。',
get_runtime_state: '返回编辑器 Game View 的实际运行/暂停状态及工具栏同步状态,而非编辑场景的 director 计数;不查询浏览器或模拟器运行态。',
pause_runtime: '通过原生工具栏暂停正在运行的 Game View 预览。重复调用不会恢复,也不会暂停编辑场景 director、浏览器或模拟器。',
resume_runtime: '通过原生工具栏恢复已暂停的 Game View 预览。重复调用不会暂停;需要先启动 Game View。',
set_time_scale: '设置编辑场景的 Cocos 调度器时间缩放,不影响独立的 Game View 预览运行态。',
emit_node_event: '在目标场景节点上触发自定义事件,并可附带 JSON 数据。',
simulate_button_click: '通过在目标按钮节点上触发点击事件,模拟 Cocos Button 点击。',
list_button_click_events: '列出 Cocos Button 组件的点击事件绑定。',
bind_button_click_event: '将 Cocos Button 点击事件绑定到目标节点的组件方法。',
invoke_component_method: '调用组件方法,用于运行时验证和测试钩子。',
get_script_diagnostic_context: '运行 TypeScript 诊断并为每个错误附加源码片段。修复前分析编译错误时优先使用此专用工具。',
capture_desktop_screenshot: '截取本地桌面,并以 MCP 图片数据返回。',
capture_editor_screenshot: '截取当前聚焦的 Cocos Creator 编辑器窗口,并以 MCP 图片数据返回。仅在明确需要视觉验证时优先使用截图工具。',
capture_scene_screenshot: '截取编辑器 Scene 面板区域,并在可用时按面板裁剪。仅用于场景侧结果的视觉验证。',
capture_game_screenshot: '截取所选窗口中可见的 Cocos Game View 或 GameCanvas。找不到可见游戏视口时返回错误。',
list_editor_windows: '列出可用的 Electron 窗口,便于截图或输入工具选择正确目标。明确需要处理窗口目标问题时使用。',
simulate_mouse_click: '向编辑器、预览或模拟器窗口发送底层 Electron 鼠标点击。',
simulate_mouse_drag: '发送 Electron 鼠标拖拽。兼容旧步数模式;可显式启用跨渲染帧模式,按时长移动并支持去重、查询和取消。渲染帧及事件发送不代表游戏逻辑已响应。',
simulate_key_press: '向编辑器、预览或模拟器窗口发送底层 Electron 按键。',
simulate_key_combo: '向编辑器、预览或模拟器窗口发送底层 Electron 组合按键,例如 Ctrl+S 或 Cmd+P。',
simulate_preview_input: '预览或模拟器输入的便捷封装。默认点击或按键;拖拽模式支持跨渲染帧时序及同一工具内的回执查询、取消。事件发送不代表游戏行为已验证。',
capture_preview_screenshot: '截取预览或模拟器窗口,并以 MCP 图片数据返回。仅在需要游戏或预览输出的视觉证明时使用。',
};
function localizeToolDescription(tool, language) {
const description = String(tool && tool.description || '');
if (language !== 'zh') {
return description;
}
const translated = ZH_TOOL_DESCRIPTIONS[tool && tool.name];
if (!translated) {
return description;
}
const profileMatch = description.match(/^\[([a-z]+)\]\s*/i);
if (!profileMatch) {
return translated;
}
const profile = profileMatch[1].toLowerCase();
const label = ZH_PROFILE_LABELS[profile] || profile;
return `[${label}] ${translated}`;
}
module.exports = {
ZH_PROFILE_LABELS,
ZH_TOOL_DESCRIPTIONS,
localizeToolDescription,
};
@@ -0,0 +1,5 @@
'use strict';
const { createPanel } = require('./shared');
module.exports = createPanel('tool-exposure');
File diff suppressed because it is too large. Load diff
+37
View File
@@ -0,0 +1,37 @@
{
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
"name": "io.github.FunplayAI/funplay-cocos-mcp",
"title": "Funplay Cocos MCP",
"description": "stdio bridge for the local Cocos Creator Editor MCP server from FunplayAI/funplay-cocos-mcp.",
"repository": {
"url": "https://github.com/FunplayAI/funplay-cocos-mcp",
"source": "github"
},
"version": "0.7.6",
"packages": [
{
"registryType": "npm",
"identifier": "funplay-cocos-mcp",
"version": "0.7.6",
"transport": {
"type": "stdio"
},
"environmentVariables": [
{
"name": "FUNPLAY_COCOS_MCP_URL",
"description": "Optional local Cocos MCP HTTP endpoint. Defaults to http://127.0.0.1:8765/.",
"format": "string",
"isRequired": false,
"isSecret": false
},
{
"name": "FUNPLAY_COCOS_MCP_TIMEOUT_SECONDS",
"description": "Optional HTTP timeout per request in seconds. Defaults to 120.",
"format": "string",
"isRequired": false,
"isSecret": false
}
]
}
]
}