dsh-unreal-python-api 1.2.0 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/builder.js CHANGED
@@ -2,7 +2,7 @@
2
2
  * Scaffolds Unreal Python tools from a description plus verified API symbols.
3
3
  *
4
4
  * The emitted code follows the ToolsetRegistry shape: one `@unreal.uclass()`
5
- * class inheriting `unreal.ToolsetDefinition`, one `@toolset_registry.tool_call`
5
+ * class inheriting `unreal.ToolsetDefinition`, one `@tool_call`
6
6
  * static method per tool, annotated parameters, and manual registration. Tool
7
7
  * bodies are deliberately unimplemented, and every Unreal symbol the tool needs
8
8
  * is recorded next to the body with the documentation page it was verified in.
@@ -30,7 +30,29 @@ const TYPE_MAP = new Map([
30
30
  ])
31
31
 
32
32
  /** Import line assumed for the ToolsetRegistry Python decorator module. */
33
- export const DEFAULT_REGISTRY_IMPORT = 'from toolset_registry import toolset_registry'
33
+ export const DEFAULT_REGISTRY_IMPORT = 'from toolset_registry import tool_call'
34
+
35
+ /**
36
+ * The decorator text implied by a registry import line. The UE 5.8 module ships
37
+ * `tool_call` directly, so the default import yields `@tool_call`; an import of
38
+ * the module or registry object keeps its `.tool_call` attribute form.
39
+ * @param {unknown} importLine
40
+ * @returns {string} decorator text such as `@tool_call`
41
+ */
42
+ export function registryDecoratorName(importLine) {
43
+ const line = String(importLine ?? '').trim()
44
+ if (line === '') return '@tool_call'
45
+ const fromImport = /^from\s+[A-Za-z0-9_.]+\s+import\s+([A-Za-z0-9_]+)$/.exec(line)
46
+ if (fromImport) {
47
+ return fromImport[1] === 'tool_call' ? '@tool_call' : `@${fromImport[1]}.tool_call`
48
+ }
49
+ const plainImport = /^(?:import\s+)?([A-Za-z0-9_.]+)(?:\s+as\s+([A-Za-z0-9_]+))?$/.exec(line)
50
+ if (plainImport) {
51
+ const name = plainImport[2] ?? plainImport[1].split('.').pop()
52
+ return name === 'tool_call' ? '@tool_call' : `@${name}.tool_call`
53
+ }
54
+ return '@tool_call'
55
+ }
34
56
 
35
57
  /** Base class assumed for a generated toolset. */
36
58
  export const DEFAULT_BASE_CLASS = 'unreal.ToolsetDefinition'
@@ -200,11 +222,12 @@ function symbolComments(symbols, urls, indent, prefix = '#') {
200
222
  * Render one tool method.
201
223
  * @param {object} tool Tool definition.
202
224
  * @param {Map<string, string>} urls Verified symbol URLs.
225
+ * @param {string} [decorator] Registry decorator text, such as `@tool_call`.
203
226
  * @returns {string[]} Method lines.
204
227
  */
205
- function renderTool(tool, urls) {
228
+ function renderTool(tool, urls, decorator = '@tool_call') {
206
229
  const lines = []
207
- lines.push(' @toolset_registry.tool_call')
230
+ lines.push(` ${decorator}`)
208
231
  lines.push(' @staticmethod')
209
232
  const parameters = (tool.parameters ?? []).map((parameter) => {
210
233
  const name = requireIdentifier(`parameter name in tool '${tool.name}'`, snakeCase(parameter.name))
@@ -252,12 +275,13 @@ function renderToolset(input, urls) {
252
275
  lines.push(input.registryImport)
253
276
  lines.push('')
254
277
  }
278
+ const decorator = registryDecoratorName(input.registryImport)
255
279
  lines.push('')
256
280
  lines.push('@unreal.uclass()')
257
281
  lines.push(`class ${className}(${input.baseClass}):`)
258
282
  lines.push(` """${input.description}"""`)
259
283
  lines.push('')
260
- for (const tool of input.tools) lines.push(...renderTool(tool, urls))
284
+ for (const tool of input.tools) lines.push(...renderTool(tool, urls, decorator))
261
285
  lines.push('')
262
286
  lines.push(`def register_toolsets() -> None:`)
263
287
  lines.push(` """Register ${className} with the ToolsetRegistry."""`)
@@ -565,6 +589,7 @@ export function buildToolset(input, resolve) {
565
589
 
566
590
  const notes = [
567
591
  'Tool bodies raise NotImplementedError; implement them before registering.',
592
+ 'A Python-defined toolset registers as PythonTypes.<ClassName>_<hex>; find the exact name with unreal.ToolsetRegistry.get_all_toolset_json_schemas().',
568
593
  `Registry decorator import: ${normalized.registryImport === '' ? 'omitted (supply the line for your ToolsetRegistry plugin)' : normalized.registryImport}.`,
569
594
  `Base class: ${normalized.baseClass}.`,
570
595
  ]
@@ -578,7 +603,7 @@ export function buildToolset(input, resolve) {
578
603
  testLabel: 'Test module (Python)',
579
604
  code: renderToolset,
580
605
  tests: renderTests,
581
- note: 'Registry decorator import and base class are the ToolsetRegistry defaults; change registry_import or base_class when your plugin differs.',
606
+ note: 'Registry decorator import and base class are the UE 5.8 ToolsetRegistry defaults (from toolset_registry import tool_call); change registry_import or base_class when your plugin differs.',
582
607
  },
583
608
  editor_script: {
584
609
  codeLabel: 'Editor script (Python)',
package/lib/engine.js ADDED
@@ -0,0 +1,383 @@
1
+ /**
2
+ * Engine discovery: what the project file asks for, what is actually installed,
3
+ * and what the running editor reports.
4
+ *
5
+ * The three answers are deliberately kept apart. A project pinned to `5.8` can
6
+ * open in an editor built from `5.7`, and Epic publishes the Python API for one
7
+ * engine version only, so merging them into a single "version" would hide the
8
+ * exact mismatch this module exists to report.
9
+ *
10
+ * @module
11
+ */
12
+
13
+ import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'
14
+ import { join } from 'node:path'
15
+ import { engineVersionFromBuildString } from './monolith.js'
16
+
17
+ /** Versions whose Python API inventory Epic publishes. Verified 2026-11-30. */
18
+ export const DOCUMENTED_ENGINE_VERSIONS = ['5.8']
19
+
20
+ /** Where the Launcher records installed engines on Windows. */
21
+ export const LAUNCHER_MANIFEST_PATH = 'C:\\ProgramData\\Epic\\UnrealEngineLauncher\\LauncherInstalled.dat'
22
+
23
+ /**
24
+ * Strip `//` and block comments that Unreal tolerates in its JSON assets.
25
+ *
26
+ * @param {string} text
27
+ */
28
+ export function stripJsonComments(text) {
29
+ let out = ''
30
+ let inString = false
31
+ let inLine = false
32
+ let inBlock = false
33
+ for (let index = 0; index < text.length; index += 1) {
34
+ const char = text[index]
35
+ const next = text[index + 1]
36
+ if (inLine) {
37
+ if (char === '\n') {
38
+ inLine = false
39
+ out += char
40
+ }
41
+ continue
42
+ }
43
+ if (inBlock) {
44
+ if (char === '*' && next === '/') {
45
+ inBlock = false
46
+ index += 1
47
+ }
48
+ continue
49
+ }
50
+ if (inString) {
51
+ out += char
52
+ if (char === '\\') {
53
+ out += next ?? ''
54
+ index += 1
55
+ } else if (char === '"') {
56
+ inString = false
57
+ }
58
+ continue
59
+ }
60
+ if (char === '"') {
61
+ inString = true
62
+ out += char
63
+ continue
64
+ }
65
+ if (char === '/' && next === '/') {
66
+ inLine = true
67
+ index += 1
68
+ continue
69
+ }
70
+ if (char === '/' && next === '*') {
71
+ inBlock = true
72
+ index += 1
73
+ continue
74
+ }
75
+ out += char
76
+ }
77
+ return out
78
+ }
79
+
80
+ /**
81
+ * Parse a `.uproject` document.
82
+ *
83
+ * @param {string} text
84
+ * @param {string} [file] Used in error messages.
85
+ */
86
+ export function parseUproject(text, file = '.uproject') {
87
+ let document
88
+ try {
89
+ document = JSON.parse(stripJsonComments(text).trim())
90
+ } catch (error) {
91
+ throw new Error(`cannot parse ${file}: ${error instanceof Error ? error.message : String(error)}`)
92
+ }
93
+ if (document === null || typeof document !== 'object' || Array.isArray(document)) {
94
+ throw new Error(`cannot parse ${file}: the root is not an object`)
95
+ }
96
+ return {
97
+ file,
98
+ fileVersion: typeof document.FileVersion === 'number' ? document.FileVersion : null,
99
+ engineAssociation:
100
+ typeof document.EngineAssociation === 'string' && document.EngineAssociation !== ''
101
+ ? document.EngineAssociation
102
+ : null,
103
+ description: typeof document.Description === 'string' ? document.Description : '',
104
+ modules: Array.isArray(document.Modules)
105
+ ? document.Modules.filter((entry) => entry && typeof entry.Name === 'string').map((entry) => ({
106
+ name: entry.Name,
107
+ type: typeof entry.Type === 'string' ? entry.Type : null,
108
+ loadingPhase: typeof entry.LoadingPhase === 'string' ? entry.LoadingPhase : null,
109
+ }))
110
+ : [],
111
+ plugins: Array.isArray(document.Plugins)
112
+ ? document.Plugins.filter((entry) => entry && typeof entry.Name === 'string').map((entry) => ({
113
+ name: entry.Name,
114
+ enabled: entry.Enabled !== false,
115
+ }))
116
+ : [],
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Find the `.uproject` in a directory, preferring one named after the directory.
122
+ *
123
+ * @param {string} directory
124
+ * @returns {string | null}
125
+ */
126
+ export function findProjectFile(directory) {
127
+ let entries
128
+ try {
129
+ entries = readdirSync(directory, { withFileTypes: true })
130
+ } catch {
131
+ return null
132
+ }
133
+ const candidates = entries
134
+ .filter((entry) => entry.isFile() && entry.name.toLowerCase().endsWith('.uproject'))
135
+ .map((entry) => entry.name)
136
+ if (candidates.length === 0) return null
137
+ const base = directory.replace(/[\\/]+$/, '').split(/[\\/]/).pop() ?? ''
138
+ const preferred = candidates.find((name) => name.toLowerCase() === `${base.toLowerCase()}.uproject`)
139
+ return join(directory, preferred ?? candidates[0])
140
+ }
141
+
142
+ /**
143
+ * Read a `.uproject` from disk.
144
+ *
145
+ * @param {string} file
146
+ */
147
+ export function readUproject(file) {
148
+ return parseUproject(readFileSync(file, 'utf8'), file)
149
+ }
150
+
151
+ /**
152
+ * Map `5.8.4` from an `AppVersion` such as `5.8.4-58902052+++UE5+Release-5.8-Windows`.
153
+ *
154
+ * @param {unknown} appVersion
155
+ * @returns {string | null}
156
+ */
157
+ export function versionFromAppVersion(appVersion) {
158
+ if (typeof appVersion !== 'string') return null
159
+ const match = /^(\d+\.\d+)/.exec(appVersion)
160
+ return match ? match[1] : null
161
+ }
162
+
163
+ /**
164
+ * Parse `LauncherInstalled.dat` into engine-version to install-location pairs.
165
+ *
166
+ * Only the engine artifacts themselves (an `ArtifactId` such as `UE_5.8`) count;
167
+ * the same file lists content packs and plugins that share an install location.
168
+ *
169
+ * @param {string} text
170
+ */
171
+ export function parseLauncherManifest(text) {
172
+ let document
173
+ try {
174
+ document = JSON.parse(text)
175
+ } catch (error) {
176
+ throw new Error(`cannot parse the Launcher manifest: ${error instanceof Error ? error.message : String(error)}`)
177
+ }
178
+ const list = Array.isArray(document?.InstallationList) ? document.InstallationList : []
179
+ /** @type {Record<string, { location: string, appVersion: string | null }>} */
180
+ const engines = {}
181
+ for (const entry of list) {
182
+ if (!entry || typeof entry.InstallLocation !== 'string') continue
183
+ const artifact = typeof entry.ArtifactId === 'string' ? entry.ArtifactId : ''
184
+ const appName = typeof entry.AppName === 'string' ? entry.AppName : ''
185
+ const match = /^UE_(\d+\.\d+)$/.exec(artifact) ?? /^UE_(\d+\.\d+)$/.exec(appName)
186
+ if (!match) continue
187
+ const version = match[1]
188
+ const existing = engines[version]
189
+ engines[version] = {
190
+ location: entry.InstallLocation,
191
+ appVersion: typeof entry.AppVersion === 'string' ? entry.AppVersion : (existing?.appVersion ?? null),
192
+ }
193
+ }
194
+ return engines
195
+ }
196
+
197
+ /**
198
+ * Read `Engine/Build/Build.version` from an install.
199
+ *
200
+ * @param {string} engineDirectory
201
+ */
202
+ export function readBuildVersion(engineDirectory) {
203
+ const file = join(engineDirectory, 'Engine', 'Build', 'Build.version')
204
+ if (!existsSync(file)) return null
205
+ try {
206
+ const document = JSON.parse(readFileSync(file, 'utf8'))
207
+ return {
208
+ file,
209
+ major: document.MajorVersion ?? null,
210
+ minor: document.MinorVersion ?? null,
211
+ patch: document.PatchVersion ?? null,
212
+ changelist: document.Changelist ?? null,
213
+ branch: typeof document.BranchName === 'string' ? document.BranchName : null,
214
+ version:
215
+ typeof document.MajorVersion === 'number' && typeof document.MinorVersion === 'number'
216
+ ? `${document.MajorVersion}.${document.MinorVersion}`
217
+ : null,
218
+ }
219
+ } catch {
220
+ return null
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Resolve the installation a project's `EngineAssociation` points at.
226
+ *
227
+ * @param {string | null} association
228
+ * @param {{ engines?: Record<string, string>, launcher?: Record<string, { location: string }> }} [sources]
229
+ */
230
+ export function resolveInstallation(association, sources = {}) {
231
+ if (!association) return null
232
+ const configured = sources.engines?.[association]
233
+ if (typeof configured === 'string' && configured !== '') {
234
+ return { version: association, path: configured, source: 'config' }
235
+ }
236
+ const launcher = sources.launcher?.[association]
237
+ if (launcher?.location) {
238
+ return { version: association, path: launcher.location, source: 'launcher' }
239
+ }
240
+ return null
241
+ }
242
+
243
+ /**
244
+ * Which engine versions Epic publishes a Python API inventory for.
245
+ *
246
+ * @param {string | null} version
247
+ * @param {string} docBaseUrl
248
+ */
249
+ export function documentationCoverage(version, docBaseUrl) {
250
+ const supported = version !== null && DOCUMENTED_ENGINE_VERSIONS.includes(version)
251
+ return {
252
+ status: supported ? 'available' : 'unavailable_for_version',
253
+ version,
254
+ documentedVersions: [...DOCUMENTED_ENGINE_VERSIONS],
255
+ url: docBaseUrl,
256
+ note: supported
257
+ ? 'Epic publishes the Python API inventory for this version.'
258
+ : version === null
259
+ ? 'No engine version was detected, so no documented version can be matched.'
260
+ : `Epic publishes the Python API inventory for ${DOCUMENTED_ENGINE_VERSIONS.join(', ')} only; ${version} has no inventory. Do not treat ${DOCUMENTED_ENGINE_VERSIONS.join(', ')} answers as ${version} answers.`,
261
+ }
262
+ }
263
+
264
+ /**
265
+ * Report every place the three version sources disagree.
266
+ *
267
+ * @param {{ association: string | null, installation: { version: string } | null, editor: { version: string | null } | null }} sources
268
+ * @returns {string[]}
269
+ */
270
+ export function detectConflicts(sources) {
271
+ const conflicts = []
272
+ const { association, installation, editor } = sources
273
+ if (association && installation && association !== installation.version) {
274
+ conflicts.push(
275
+ `the project asks for ${association} but the resolved installation is ${installation.version}`,
276
+ )
277
+ }
278
+ const editorVersion = editor?.version ?? null
279
+ if (installation && editorVersion && installation.version !== editorVersion) {
280
+ conflicts.push(
281
+ `the installation is ${installation.version} but the running editor reports ${editorVersion}`,
282
+ )
283
+ }
284
+ if (association && editorVersion && association !== editorVersion) {
285
+ conflicts.push(`the project asks for ${association} but the running editor reports ${editorVersion}`)
286
+ }
287
+ return conflicts
288
+ }
289
+
290
+ /**
291
+ * Collect the project, installation and editor facts in one record.
292
+ *
293
+ * @param {{
294
+ * directory: string,
295
+ * engines?: Record<string, string>,
296
+ * launcherManifestPath?: string,
297
+ * docBaseUrl: string,
298
+ * client: ReturnType<import('./monolith.js').createMonolithClient>,
299
+ * }} input
300
+ */
301
+ export async function detectEngine(input) {
302
+ const directory = input.directory
303
+ const file = findProjectFile(directory)
304
+ const project = file ? readUproject(file) : null
305
+
306
+ let launcher = {}
307
+ const manifestPath = input.launcherManifestPath ?? LAUNCHER_MANIFEST_PATH
308
+ if (existsSync(manifestPath)) {
309
+ try {
310
+ launcher = parseLauncherManifest(readFileSync(manifestPath, 'utf8'))
311
+ } catch {
312
+ launcher = {}
313
+ }
314
+ }
315
+
316
+ const installation = resolveInstallation(project?.engineAssociation ?? null, {
317
+ engines: input.engines,
318
+ launcher,
319
+ })
320
+ const buildVersion = installation ? readBuildVersion(installation.path) : null
321
+
322
+ /** @type {{ connected: boolean, version: string | null, projectName: string | null, serverVersion: string | null, port: number | null, actions: number | null, error: { code: string, message: string } | null }} */
323
+ let editor = {
324
+ connected: false,
325
+ version: null,
326
+ projectName: null,
327
+ serverVersion: null,
328
+ port: null,
329
+ actions: null,
330
+ error: null,
331
+ }
332
+ try {
333
+ const status = await input.client.status()
334
+ const version = engineVersionFromBuildString(status?.engine_version ?? status?.engineVersion)
335
+ editor = {
336
+ connected: true,
337
+ version,
338
+ projectName: typeof status?.project_name === 'string' ? status.project_name : null,
339
+ serverVersion: typeof status?.version === 'string' ? status.version : null,
340
+ port: typeof status?.server_port === 'number' ? status.server_port : null,
341
+ actions: typeof status?.total_actions === 'number' ? status.total_actions : null,
342
+ error: null,
343
+ }
344
+ } catch (error) {
345
+ editor.error = {
346
+ code: error?.code ?? 'error',
347
+ message: error instanceof Error ? error.message : String(error),
348
+ }
349
+ }
350
+
351
+ const documentation = documentationCoverage(
352
+ editor.version ?? buildVersion?.version ?? installation?.version ?? project?.engineAssociation ?? null,
353
+ input.docBaseUrl,
354
+ )
355
+ const conflicts = detectConflicts({
356
+ association: project?.engineAssociation ?? null,
357
+ installation,
358
+ editor: editor.connected ? { version: editor.version } : null,
359
+ })
360
+
361
+ return {
362
+ directory,
363
+ project,
364
+ installation: installation ? { ...installation, build: buildVersion } : null,
365
+ editor,
366
+ documentation,
367
+ conflicts,
368
+ verified: {
369
+ fromProjectFile: project !== null,
370
+ fromInstallation: buildVersion !== null,
371
+ fromEditor: editor.connected,
372
+ },
373
+ }
374
+ }
375
+
376
+ /** True when a path exists and is a directory. */
377
+ export function isDirectory(path) {
378
+ try {
379
+ return statSync(path).isDirectory()
380
+ } catch {
381
+ return false
382
+ }
383
+ }
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Monolith adapter: the smallest MCP client that can read from the editor.
3
+ *
4
+ * The plugin deliberately does not own an editor bridge. Monolith already runs
5
+ * inside the Unreal Editor and speaks MCP over HTTP on port 9316, so this module
6
+ * only performs the MCP handshake and forwards a tool call. Nothing here can
7
+ * mutate a project on its own: read-only calls must pass `READ_ONLY_ACTIONS`,
8
+ * and every transport problem becomes a typed error with the endpoint in it.
9
+ *
10
+ * @module
11
+ */
12
+
13
+ /** The streamable-HTTP endpoint the Monolith plugin serves. */
14
+ export const DEFAULT_MONOLITH_URL = 'http://127.0.0.1:9316/mcp'
15
+
16
+ /** Monolith tools this plugin may call at all. */
17
+ const READ_ONLY_TOOLS = new Set([
18
+ 'monolith_status',
19
+ 'monolith_discover',
20
+ 'monolith_guide',
21
+ 'describe_query',
22
+ 'project_query',
23
+ 'source_query',
24
+ 'editor_query',
25
+ ])
26
+
27
+ /**
28
+ * Actions that only read state. A tool that is not listed here is either absent
29
+ * from `READ_ONLY_TOOLS` or passed without an action on purpose.
30
+ */
31
+ const READ_ONLY_ACTIONS = new Set([
32
+ 'get_stats',
33
+ 'search',
34
+ 'find_by_type',
35
+ 'find_references',
36
+ 'get_asset_details',
37
+ 'get_saved_asset_state',
38
+ 'list_gameplay_tags',
39
+ 'search_gameplay_tags',
40
+ 'get_module_info',
41
+ 'get_class_hierarchy',
42
+ 'get_signature',
43
+ 'read_source',
44
+ 'read_file',
45
+ 'search_source',
46
+ 'get_include_path',
47
+ 'verify_symbols',
48
+ 'check_deprecations',
49
+ 'find_example_usage',
50
+ 'find_callers',
51
+ 'find_callees',
52
+ 'audit_module_dep_reality',
53
+ 'suggest_build_cs_deps',
54
+ 'get_viewport_info',
55
+ 'get_log_stats',
56
+ 'get_log_categories',
57
+ 'get_recent_logs',
58
+ 'search_logs',
59
+ 'tail_log',
60
+ 'get_build_status',
61
+ 'get_build_summary',
62
+ 'list_dirty_packages',
63
+ 'list_errored_blueprints',
64
+ 'get_module_status',
65
+ 'list_automation_tests',
66
+ 'get_stat_group_values',
67
+ 'inspect_material_pbr',
68
+ 'inspect_texture_channels',
69
+ 'get_mesh_info',
70
+ 'get_actor_info',
71
+ 'get_actor_properties',
72
+ 'get_level_actors',
73
+ ])
74
+
75
+ /** A failure that names its cause instead of surfacing a raw fetch error. */
76
+ export class MonolithError extends Error {
77
+ /**
78
+ * @param {string} code One of `disconnected`, `timeout`, `http`, `rpc`, `not-read-only`, `protocol`.
79
+ * @param {string} message Human-readable explanation, including the endpoint.
80
+ * @param {ErrorOptions} [options]
81
+ */
82
+ constructor(code, message, options) {
83
+ super(message, options)
84
+ this.name = 'MonolithError'
85
+ this.code = code
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Build a client for one Monolith endpoint.
91
+ *
92
+ * @param {{ url?: string, timeoutMs?: number, clientName?: string }} [options]
93
+ */
94
+ export function createMonolithClient(options = {}) {
95
+ const url = options.url ?? DEFAULT_MONOLITH_URL
96
+ const timeoutMs = options.timeoutMs ?? 8000
97
+ const clientName = options.clientName ?? 'dsh-unreal-python-api'
98
+ let nextId = 0
99
+ let handshake = null
100
+
101
+ /**
102
+ * @param {string} method
103
+ * @param {Record<string, unknown> | undefined} params
104
+ * @param {AbortSignal | undefined} [signal]
105
+ */
106
+ async function rpc(method, params, signal) {
107
+ let response
108
+ try {
109
+ response = await fetch(url, {
110
+ method: 'POST',
111
+ headers: {
112
+ 'content-type': 'application/json',
113
+ accept: 'application/json, text/event-stream',
114
+ },
115
+ body: JSON.stringify({ jsonrpc: '2.0', id: ++nextId, method, params }),
116
+ signal: signal ?? AbortSignal.timeout(timeoutMs),
117
+ })
118
+ } catch (error) {
119
+ if (error?.name === 'TimeoutError') {
120
+ throw new MonolithError('timeout', `Monolith at ${url} did not answer within ${timeoutMs} ms.`)
121
+ }
122
+ const cause = error?.cause?.code ?? error?.code ?? error?.message ?? 'unknown error'
123
+ throw new MonolithError(
124
+ 'disconnected',
125
+ `Monolith is not reachable at ${url} (${cause}). Start the Unreal Editor with the Monolith plugin enabled.`,
126
+ { cause: error },
127
+ )
128
+ }
129
+
130
+ const text = await response.text()
131
+ if (!response.ok) {
132
+ throw new MonolithError('http', `Monolith at ${url} answered HTTP ${response.status}: ${text.slice(0, 200)}`)
133
+ }
134
+
135
+ let payload
136
+ try {
137
+ payload = JSON.parse(text)
138
+ } catch {
139
+ throw new MonolithError(
140
+ 'protocol',
141
+ `Monolith at ${url} answered something that is not JSON-RPC: ${text.slice(0, 160)}`,
142
+ )
143
+ }
144
+ if (payload.error) {
145
+ throw new MonolithError('rpc', `Monolith reported ${payload.error.code}: ${payload.error.message}`)
146
+ }
147
+ return payload.result
148
+ }
149
+
150
+ /** Perform the MCP handshake once per client. */
151
+ function initialize() {
152
+ handshake ??= (async () => {
153
+ const result = await rpc('initialize', {
154
+ protocolVersion: '2025-06-18',
155
+ capabilities: {},
156
+ clientInfo: { name: clientName, version: '1.0.0' },
157
+ })
158
+ // The transport is stateless; the notification is advisory.
159
+ try {
160
+ await fetch(url, {
161
+ method: 'POST',
162
+ headers: { 'content-type': 'application/json' },
163
+ body: JSON.stringify({ jsonrpc: '2.0', method: 'notifications/initialized' }),
164
+ signal: AbortSignal.timeout(timeoutMs),
165
+ })
166
+ } catch {
167
+ // A server that does not accept the notification still accepts calls.
168
+ }
169
+ return result
170
+ })()
171
+ return handshake
172
+ }
173
+
174
+ /**
175
+ * Call one Monolith tool and parse its JSON payload.
176
+ *
177
+ * @param {string} name
178
+ * @param {Record<string, unknown>} [args]
179
+ * @param {{ signal?: AbortSignal }} [options]
180
+ */
181
+ async function callTool(name, args = {}, callOptions = {}) {
182
+ await initialize()
183
+ const result = await rpc('tools/call', { name, arguments: args }, callOptions.signal)
184
+ const text = result?.content?.find?.((part) => part.type === 'text')?.text ?? ''
185
+ if (!text) {
186
+ throw new MonolithError('protocol', `Monolith tool ${name} returned no text content.`)
187
+ }
188
+ try {
189
+ return JSON.parse(text)
190
+ } catch {
191
+ return { text }
192
+ }
193
+ }
194
+
195
+ /**
196
+ * Call a tool only when it, and its action, are known read-only.
197
+ *
198
+ * @param {string} name
199
+ * @param {Record<string, unknown>} [args]
200
+ * @param {{ signal?: AbortSignal }} [options]
201
+ */
202
+ async function callReadOnly(name, args = {}, callOptions = {}) {
203
+ if (!READ_ONLY_TOOLS.has(name)) {
204
+ throw new MonolithError('not-read-only', `${name} is not on the read-only allowlist of this plugin.`)
205
+ }
206
+ const action = typeof args.action === 'string' ? args.action : undefined
207
+ if (action !== undefined && !READ_ONLY_ACTIONS.has(action)) {
208
+ throw new MonolithError(
209
+ 'not-read-only',
210
+ `${name}.${action} is not on the read-only allowlist of this plugin; this slice never mutates a project.`,
211
+ )
212
+ }
213
+ if (name === 'editor_query' && action !== undefined && READ_ONLY_ACTIONS.has(action) === false) {
214
+ throw new MonolithError('not-read-only', `editor_query.${action} is not read-only.`)
215
+ }
216
+ return callTool(name, args, callOptions)
217
+ }
218
+
219
+ /** Read the server's own status payload. */
220
+ async function status() {
221
+ return callReadOnly('monolith_status')
222
+ }
223
+
224
+ return { url, initialize, callTool, callReadOnly, status }
225
+ }
226
+
227
+ /**
228
+ * Turn a Monolith engine string such as `++UE5+Release-5.8-CL-58902052` into `5.8`.
229
+ *
230
+ * @param {unknown} value
231
+ * @returns {string | null}
232
+ */
233
+ export function engineVersionFromBuildString(value) {
234
+ if (typeof value !== 'string') return null
235
+ const match = /(\d+)\.(\d+)/.exec(value)
236
+ return match ? `${match[1]}.${match[2]}` : null
237
+ }