-
-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmodels.js
More file actions
201 lines (194 loc) · 6.87 KB
/
Copy pathmodels.js
File metadata and controls
201 lines (194 loc) · 6.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
import { limits } from '../../_lib/rate-limit.js';
import { fetchModel, FetchModelError } from '../../_lib/fetch-model.js';
import { inspectModel, suggestOptimizations } from '../../_lib/model-inspect.js';
import { validateBytes } from 'gltf-validator';
function rpcError(code, message, data) {
const e = new Error(message);
e.code = code;
e.data = data;
return e;
}
async function safeFetchModel(url) {
try {
return await fetchModel(url);
} catch (e) {
if (e instanceof FetchModelError) throw new Error(`fetch failed: ${e.message} (${e.code})`);
throw e;
}
}
// MCP tool annotations (2025-06-18 spec): all three tools are deterministic,
// pure inspections of a caller-supplied URL — same file, same report.
// destructiveHint defaults to TRUE when omitted, so it is set explicitly.
const INSPECTION_ANNOTATIONS = {
readOnlyHint: true,
destructiveHint: false,
idempotentHint: true,
openWorldHint: true,
};
function formatValidationSummary(s, messages) {
const head =
`glTF-Validator report for ${s.filename} (${(s.fileSize / 1024).toFixed(1)} KB)\n` +
`Errors: ${s.numErrors}, Warnings: ${s.numWarnings}, Infos: ${s.numInfos}, Hints: ${s.numHints}` +
(s.truncated ? ' (truncated)' : '');
if (!messages.length) return head;
const lines = messages.slice(0, 40).map((m) => {
const sev = ['ERR', 'WRN', 'INF', 'HNT'][m.severity] || '?';
const ptr = m.pointer ? ` @ ${m.pointer}` : '';
return ` [${sev}] ${m.code}: ${m.message}${ptr}`;
});
const more = messages.length > 40 ? `\n … ${messages.length - 40} more` : '';
return `${head}\n${lines.join('\n')}${more}`;
}
function formatInspection(info) {
const c = info.counts;
const tex = info.textures.length
? info.textures
.map(
(t) =>
` • ${t.name || '(unnamed)'} — ${t.mimeType} ${t.width}×${t.height}, ${(t.byteSize / 1024).toFixed(1)} KB`,
)
.join('\n')
: ' (none)';
return [
`Model: ${info.filename} (${(info.fileSize / 1024 / 1024).toFixed(2)} MB, ${info.container})`,
`Generator: ${info.generator || 'unknown'} · glTF ${info.version || '?'}`,
`Scenes: ${c.scenes}, Nodes: ${c.nodes}, Meshes: ${c.meshes}, Materials: ${c.materials}, Textures: ${c.textures}`,
`Animations: ${c.animations}, Skins: ${c.skins}`,
`Vertices: ${c.totalVertices.toLocaleString()}, Triangles: ${c.totalTriangles.toLocaleString()}`,
`Indexed primitives: ${c.indexedPrimitives}, Non-indexed: ${c.nonIndexedPrimitives}`,
`Extensions used: ${info.extensionsUsed.join(', ') || '(none)'}`,
`Textures:\n${tex}`,
].join('\n');
}
function formatSuggestions(suggestions) {
if (!suggestions.length) return 'No suggestions.';
return suggestions
.map((s) => {
const tag =
{ info: 'INFO', warn: 'WARN', critical: 'CRIT' }[s.severity] ||
s.severity.toUpperCase();
const est = s.estimate ? ` — ${s.estimate}` : '';
return `[${tag}] ${s.id}: ${s.message}${est}`;
})
.join('\n');
}
export const toolDefs = [
{
name: 'validate_model',
title: 'Validate glTF/GLB model',
annotations: INSPECTION_ANNOTATIONS,
description:
'Run the Khronos glTF-Validator against a remote GLB or glTF URL. Returns a structured report of errors, warnings, infos, and hints — the authoritative answer to "is this file spec-compliant?". SSRF-hardened: only public https URLs are fetched.',
inputSchema: {
type: 'object',
properties: {
url: {
type: 'string',
format: 'uri',
description: 'Public https URL of a .glb or .gltf file.',
},
max_issues: { type: 'integer', minimum: 1, maximum: 500, default: 100 },
},
required: ['url'],
additionalProperties: false,
},
async handler(args, auth) {
const rl = await limits.mcpValidate(auth.userId || auth.rateKey);
if (!rl.success)
throw rpcError(-32000, 'rate_limited', {
retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
});
const { bytes, url, filename } = await safeFetchModel(args.url);
const max = Math.min(Math.max(args.max_issues || 100, 1), 500);
const report = await validateBytes(bytes, { maxIssues: max, uri: filename });
const issues = report?.issues || {};
const summary = {
url,
filename,
fileSize: bytes.byteLength,
validatorVersion: report?.validatorVersion,
mimeType: report?.mimeType,
numErrors: issues.numErrors ?? 0,
numWarnings: issues.numWarnings ?? 0,
numInfos: issues.numInfos ?? 0,
numHints: issues.numHints ?? 0,
truncated: !!issues.truncated,
};
return {
content: [
{ type: 'text', text: formatValidationSummary(summary, issues.messages || []) },
],
structuredContent: {
...summary,
messages: issues.messages || [],
info: report?.info || null,
},
};
},
},
{
name: 'inspect_model',
title: 'Inspect glTF/GLB model',
annotations: INSPECTION_ANNOTATIONS,
description:
'Parse a remote GLB or glTF and return structural stats: scene/node/mesh counts, vertex and triangle totals, material and texture summaries, extensions used. Pure inspection — no optimization advice.',
inputSchema: {
type: 'object',
properties: {
url: {
type: 'string',
format: 'uri',
description: 'Public https URL of a .glb or .gltf file.',
},
},
required: ['url'],
additionalProperties: false,
},
async handler(args, auth) {
const rl = await limits.mcpInspect(auth.userId || auth.rateKey);
if (!rl.success)
throw rpcError(-32000, 'rate_limited', {
retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
});
const { bytes, url, filename } = await safeFetchModel(args.url);
const info = await inspectModel(bytes, { fileSize: bytes.byteLength });
return {
content: [{ type: 'text', text: formatInspection({ url, filename, ...info }) }],
structuredContent: { url, filename, ...info },
};
},
},
{
name: 'optimize_model',
title: 'Suggest optimizations for a glTF/GLB model',
annotations: INSPECTION_ANNOTATIONS,
description:
'Inspect the model and return actionable suggestions for reducing size and draw-call overhead: triangle budget, Draco/Meshopt compression, oversized textures, KTX2 transcoding, non-indexed primitives, redundant materials, and more.',
inputSchema: {
type: 'object',
properties: {
url: {
type: 'string',
format: 'uri',
description: 'Public https URL of a .glb or .gltf file.',
},
},
required: ['url'],
additionalProperties: false,
},
async handler(args, auth) {
const rl = await limits.mcpOptimize(auth.userId || auth.rateKey);
if (!rl.success)
throw rpcError(-32000, 'rate_limited', {
retry_after: Math.ceil((rl.reset - Date.now()) / 1000),
});
const { bytes, url, filename } = await safeFetchModel(args.url);
const info = await inspectModel(bytes, { fileSize: bytes.byteLength });
const suggestions = suggestOptimizations(info);
return {
content: [{ type: 'text', text: formatSuggestions(suggestions) }],
structuredContent: { url, filename, suggestions, info },
};
},
},
];