fix(execute_script): route to own scene script eval instead of nonexistent 'console'

This commit is contained in:
feng0207
2026-06-20 21:48:19 +08:00
parent fe742a2abe
commit f3f1176ae7
5 changed files with 63 additions and 20 deletions

32
dist/scene.js vendored

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -141,6 +141,7 @@
"scene": { "scene": {
"script": "./dist/scene.js", "script": "./dist/scene.js",
"methods": [ "methods": [
"executeScript",
"createNewScene", "createNewScene",
"addComponentToNode", "addComponentToNode",
"removeComponentFromNode", "removeComponentFromNode",

View File

@@ -2,6 +2,30 @@ import { join } from 'path';
module.paths.push(join(Editor.App.path, 'node_modules')); module.paths.push(join(Editor.App.path, 'node_modules'));
export const methods: { [key: string]: (...any: any) => any } = { export const methods: { [key: string]: (...any: any) => any } = {
/**
* Execute arbitrary JavaScript in the scene process.
* `cc` is available in scope; the value of the last expression is returned
* (compatible with `(function(){ ... })();` IIFE scripts).
*/
executeScript(script: string) {
try {
const cc = require('cc');
const body = String(script).trim().replace(/;+\s*$/, '');
let fn: Function;
try {
fn = new Function('cc', 'return (' + body + '\n);');
} catch (_e) {
fn = new Function('cc', script);
}
const result = fn(cc);
let data: any = result;
try { JSON.stringify(result); } catch (_) { data = String(result); }
return { success: true, data: { result: data } };
} catch (error: any) {
return { success: false, error: error.message };
}
},
/** /**
* Create a new scene * Create a new scene
*/ */

View File

@@ -255,17 +255,11 @@ export class DebugTools implements ToolExecutor {
private async executeScript(script: string): Promise<ToolResponse> { private async executeScript(script: string): Promise<ToolResponse> {
return new Promise((resolve) => { return new Promise((resolve) => {
Editor.Message.request('scene', 'execute-scene-script', { Editor.Message.request('scene', 'execute-scene-script', {
name: 'console', name: 'cocos-mcp-server',
method: 'eval', method: 'executeScript',
args: [script] args: [script]
}).then((result: any) => { }).then((result: any) => {
resolve({ resolve(result);
success: true,
data: {
result: result,
message: 'Script executed successfully'
}
});
}).catch((err: Error) => { }).catch((err: Error) => {
resolve({ success: false, error: err.message }); resolve({ success: false, error: err.message });
}); });