@openfairygui/mcp 0.6.3 → 0.7.1

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.
@@ -1,107 +0,0 @@
1
- import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
2
- import type { z } from 'zod';
3
- import {
4
- BACKEND_CAPABILITY_SCHEMA_VERSION,
5
- BACKEND_CONTRACT_VERSION,
6
- type BackendRuntime,
7
- type BackendMethodName,
8
- } from '@openfairygui/backend';
9
- import {
10
- isOpenFairyGuiMcpPayloadWithinBudget,
11
- OPENFAIRYGUI_BACKEND_TOOL_DEFINITIONS,
12
- type OpenFairyGuiBackendToolName,
13
- } from './tool-definitions.js';
14
-
15
- import { decodeToolBytes, CONTRACT_SNAPSHOT } from './contract-schema.js';
16
- import type { McpUnhandledFailure, McpResponseBudgetFailure } from './tool-metadata.js';
17
-
18
- export type OpenFairyGuiBackendRuntime = Pick<BackendRuntime, BackendMethodName>;
19
-
20
- /** Host policy runs after input validation, before the single Backend invocation. */
21
- export interface OpenFairyGuiMcpToolPolicy {
22
- /** Explicit Host-owned failure envelope, carried in structuredContent.backendResult. */
23
- failureSchema: z.ZodType<{ ok: false }>;
24
- /** Return a declared failure to stop, or undefined to call Backend with the original input. */
25
- beforeCall(input: Readonly<Record<string, unknown>>): { ok: false } | undefined | Promise<{ ok: false } | undefined>;
26
- }
27
-
28
- function jsonResult(payload: unknown, isError = false, compact = false): CallToolResult {
29
- const text = JSON.stringify(payload, (_key, value) => value instanceof Uint8Array ? [...value] : value, compact ? undefined : 2);
30
- const wirePayload = JSON.parse(text) as unknown;
31
- return {
32
- content: [
33
- {
34
- type: 'text',
35
- text,
36
- },
37
- ],
38
- structuredContent: {
39
- backendResult: wirePayload,
40
- },
41
- isError,
42
- };
43
- }
44
-
45
- function isBackendFailure(value: unknown): boolean {
46
- return typeof value === 'object'
47
- && value !== null
48
- && 'ok' in value
49
- && (value as { ok?: unknown }).ok === false;
50
- }
51
-
52
- function unhandledBackendFailure(startedAt: number): McpUnhandledFailure {
53
- return {
54
- ok: false,
55
- meta: {
56
- requestId: crypto.randomUUID(),
57
- durationMs: Math.max(0, Date.now() - startedAt),
58
- warnings: [],
59
- diagnostics: [],
60
- stage: 'runtime',
61
- contractVersion: BACKEND_CONTRACT_VERSION,
62
- capabilitySchemaVersion: BACKEND_CAPABILITY_SCHEMA_VERSION,
63
- },
64
- error: {
65
- code: 'backend_unhandled_error',
66
- message: 'Backend tool execution failed.',
67
- },
68
- };
69
- }
70
-
71
- export async function callOpenFairyGuiBackendTool(
72
- runtime: OpenFairyGuiBackendRuntime,
73
- name: OpenFairyGuiBackendToolName,
74
- input: Record<string, unknown>,
75
- policy?: OpenFairyGuiMcpToolPolicy,
76
- ): Promise<CallToolResult> {
77
- const definition = OPENFAIRYGUI_BACKEND_TOOL_DEFINITIONS.find((entry) => entry.name === name);
78
- if (!definition) throw new RangeError(`Unknown OpenFairyGUI backend MCP tool: ${name}`);
79
- const bytePaths = CONTRACT_SNAPSHOT.tools[definition.backendMethod].bytePaths;
80
- if (!isOpenFairyGuiMcpPayloadWithinBudget(input, bytePaths)) {
81
- throw new RangeError('MCP input exceeds the depth, node, key, string, or byte budget.');
82
- }
83
- const parsed = definition.inputSchema.parse(input) as Record<string, unknown>;
84
- const decoded = decodeToolBytes(parsed, bytePaths);
85
- const startedAt = Date.now();
86
- try {
87
- let hostFailure = await policy?.beforeCall(structuredClone(parsed));
88
- if (hostFailure !== undefined) {
89
- hostFailure = policy!.failureSchema.parse(hostFailure);
90
- if (!isBackendFailure(hostFailure)) throw new TypeError('Host policy must return a failure or undefined.');
91
- }
92
- const result = hostFailure ?? await Reflect.apply(runtime[definition.backendMethod], runtime, definition.backendMethod === 'getCapabilities' ? [] : [decoded]);
93
- let response = jsonResult(result, isBackendFailure(result), definition.maxResponseBytes !== undefined);
94
- if (definition.maxResponseBytes !== undefined && new TextEncoder().encode(JSON.stringify(response)).byteLength > definition.maxResponseBytes) {
95
- response = jsonResult({
96
- ...unhandledBackendFailure(startedAt),
97
- error: { code: 'mcp_response_budget_exceeded', message: 'The complete MCP tool response exceeds its byte limit.', maxBytes: definition.maxResponseBytes },
98
- } satisfies McpResponseBudgetFailure, true);
99
- hostFailure = undefined;
100
- }
101
- if (hostFailure === undefined) definition.outputSchema.parse(response.structuredContent);
102
- else policy!.failureSchema.parse(response.structuredContent?.backendResult);
103
- return response;
104
- } catch {
105
- return jsonResult(unhandledBackendFailure(startedAt), true);
106
- }
107
- }
@@ -1,160 +0,0 @@
1
- import type { BackendMethodName, BackendResponseMeta } from '@openfairygui/backend';
2
-
3
- export interface BackendToolMetadata {
4
- name: `openfairygui_backend_${string}`;
5
- backendMethod: BackendMethodName;
6
- title: string;
7
- description: string;
8
- /** Bound the complete CallToolResult JSON; bounded reads use compact text JSON. */
9
- maxResponseBytes?: number;
10
- annotations: {
11
- readOnlyHint?: boolean;
12
- destructiveHint?: boolean;
13
- idempotentHint?: boolean;
14
- openWorldHint?: boolean;
15
- };
16
- }
17
-
18
- /** MCP transport failure, not a Backend domain error. */
19
- export interface McpUnhandledFailure {
20
- ok: false;
21
- meta: BackendResponseMeta;
22
- error: { code: 'backend_unhandled_error'; message: string };
23
- }
24
-
25
- export interface McpResponseBudgetFailure {
26
- ok: false;
27
- meta: BackendResponseMeta;
28
- error: { code: 'mcp_response_budget_exceeded'; message: string; maxBytes: number };
29
- }
30
-
31
- /** Host objects cannot cross JSON; materialize keeps its existing MCP target boundary. */
32
- export const MCP_OMITTED_INPUT_FIELDS = {
33
- openProjectSession: ['storage'],
34
- saveSession: ['fileSystem'],
35
- materializeSession: ['storage', 'fileSystem', 'targetPath'],
36
- } as const;
37
-
38
- export const OPENFAIRYGUI_BACKEND_TOOL_METADATA = [
39
- {
40
- name: 'openfairygui_backend_get_capabilities',
41
- backendMethod: 'getCapabilities',
42
- title: 'Get Backend Capabilities',
43
- description: 'Return the OpenFairyGUI backend capability, version, and service-plane snapshot.',
44
- annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
45
- },
46
- {
47
- name: 'openfairygui_backend_open_session',
48
- backendMethod: 'openSession',
49
- title: 'Open Backend Session',
50
- description: 'Open a FairyGUI project through BackendRuntime and acquire its backend-local session lock.',
51
- annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: false },
52
- },
53
- {
54
- name: 'openfairygui_backend_open_project_session',
55
- backendMethod: 'openProjectSession',
56
- title: 'Open Project Session',
57
- description: 'Open a browser-safe backend session from an already loaded UAM project without filesystem access.',
58
- annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: false },
59
- },
60
- {
61
- name: 'openfairygui_backend_get_session',
62
- backendMethod: 'getSession',
63
- title: 'Get Backend Session',
64
- description: 'Return a backend session snapshot by session id.',
65
- annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
66
- },
67
- {
68
- name: 'openfairygui_backend_get_project_outline',
69
- backendMethod: 'getProjectOutline',
70
- title: 'Get Project Outline',
71
- description: 'Return a revision-bound project/package/resource/component identity outline without source bytes or full property payloads.',
72
- annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
73
- },
74
- {
75
- name: 'openfairygui_backend_query_entity',
76
- backendMethod: 'queryEntity',
77
- title: 'Query Entity Properties',
78
- description: 'Read revision-bound project/package settings, resource, component-property, display-node, controller (including pages/actions), or transition (including items) snapshots. Project queries use only kind; other queries use formal selectors. Settings snapshots include the complete settings payload for updateProjectSettings/updatePackageSettings. No source bytes; fixed projection with explicit response limits.',
79
- annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
80
- },
81
- {
82
- name: 'openfairygui_backend_read_session_state',
83
- backendMethod: 'readSessionState',
84
- title: 'Read Session State',
85
- description: 'Read a detached copy of the currently committed public UAM model without primary asset sourceBytes, with revision, dirty state and source-read diagnostics. Optional expectedRevision rejects stale reads. Does not hydrate, write, reserve history or guarantee downstream usability. Complete tool response is limited to 16 MiB.',
86
- maxResponseBytes: 16777216,
87
- annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
88
- },
89
- {
90
- name: 'openfairygui_backend_read_resource_bytes',
91
- backendMethod: 'readResourceBytes',
92
- title: 'Read Resource Bytes',
93
- description: 'Read a detached copy of one asset resource primary sourceBytes already held in the session, using exact packageId/resourceId and the required model edit revision. No filesystem hydration or auxiliary-file discovery. Stale reads require restarting the model/bytes read. Complete tool response is limited to 16 MiB.',
94
- maxResponseBytes: 16777216,
95
- annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
96
- },
97
- {
98
- name: 'openfairygui_backend_validate_session',
99
- backendMethod: 'validateSession',
100
- title: 'Validate Project Session',
101
- description: 'Validate the current session project structure, references, paths, and available source bytes without writing files.',
102
- annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
103
- },
104
- {
105
- name: 'openfairygui_backend_preflight_transaction',
106
- backendMethod: 'preflightTransaction',
107
- title: 'Preview UAM Transaction',
108
- description: 'Execute a revision-checked operation batch on an isolated project snapshot and discard the result. Returns the base revision and Core diagnostics; does not write, reserve a revision, or guarantee a later apply/save.',
109
- annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
110
- },
111
- {
112
- name: 'openfairygui_backend_apply_transaction',
113
- backendMethod: 'applyTransaction',
114
- title: 'Apply UAM Transaction',
115
- description: 'Apply a bounded, revision-checked UAM operation batch using the Core transaction discriminants.',
116
- annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
117
- },
118
- {
119
- name: 'openfairygui_backend_save_session',
120
- backendMethod: 'saveSession',
121
- title: 'Save Backend Session',
122
- description: 'Write the current backend session through its coordinated save path; Node uses an atomic staged directory swap.',
123
- annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
124
- },
125
- {
126
- name: 'openfairygui_backend_materialize_session',
127
- backendMethod: 'materializeSession',
128
- title: 'Materialize Backend Session',
129
- description: 'Force materialize the current backend session project through the configured project storage without requiring a dirty edit revision.',
130
- annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: false },
131
- },
132
- {
133
- name: 'openfairygui_backend_close_session',
134
- backendMethod: 'closeSession',
135
- title: 'Close Backend Session',
136
- description: 'Close a backend session and release its backend-local session lock.',
137
- annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: false },
138
- },
139
- {
140
- name: 'openfairygui_backend_get_events',
141
- backendMethod: 'getEvents',
142
- title: 'Get Runtime Events',
143
- description: 'Poll backend runtime events for a session using the backend P2 event cursor contract.',
144
- annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
145
- },
146
- {
147
- name: 'openfairygui_backend_get_cache_snapshot',
148
- backendMethod: 'getCacheSnapshot',
149
- title: 'Get Cache Snapshot',
150
- description: 'Return the backend P2 derived read-only cache snapshot for a session.',
151
- annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false },
152
- },
153
- {
154
- name: 'openfairygui_backend_refresh_cache',
155
- backendMethod: 'refreshCache',
156
- title: 'Refresh Cache',
157
- description: 'Synchronously refresh the derived session cache and return its revision-bound snapshot.',
158
- annotations: { readOnlyHint: false, idempotentHint: false, openWorldHint: false },
159
- },
160
- ] as const satisfies readonly BackendToolMetadata[];