@unson/brainbase-mcp 0.50.27 → 0.50.29

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.
@@ -0,0 +1,54 @@
1
+ import type { Tool } from '@modelcontextprotocol/sdk/types.js';
2
+ export type McpToolSchemaProfile = 'standard' | 'gemini';
3
+ export type McpToolSchemaPortabilityIssueCode = 'root_not_object' | 'root_properties_missing' | 'object_properties_missing' | 'type_missing' | 'type_array_forbidden' | 'type_unsupported' | 'array_items_missing' | 'array_items_tuple_forbidden' | 'forbidden_keyword' | 'nullable_invalid' | 'enum_type_not_string' | 'enum_invalid' | 'required_not_array' | 'required_property_missing' | 'properties_invalid';
4
+ export interface McpToolSchemaPortabilityIssue {
5
+ readonly tool: string;
6
+ readonly path: string;
7
+ readonly code: McpToolSchemaPortabilityIssueCode;
8
+ readonly message: string;
9
+ }
10
+ /**
11
+ * Resolve the MCP tool schema profile from environment variables.
12
+ *
13
+ * Defaults to `'standard'` (lossless JSON Schema for Claude / OpenAI / Codex).
14
+ * Launchers targeting Gemini FunctionDeclaration opt in with
15
+ * `BRAINBASE_MCP_SCHEMA_PROFILE=gemini`.
16
+ */
17
+ export declare function resolveMcpToolSchemaProfile(env?: NodeJS.ProcessEnv): McpToolSchemaProfile;
18
+ /**
19
+ * Normalize an MCP tool `inputSchema` into the Gemini FunctionDeclaration
20
+ * (OpenAPI 3.0) compatible JSON Schema subset.
21
+ *
22
+ * Idempotent on already-portable schemas.
23
+ */
24
+ export declare function normalizeMcpToolInputSchemaForPortability(schema: Tool['inputSchema']): Tool['inputSchema'];
25
+ /**
26
+ * Normalize an MCP tool `inputSchema` according to the target host profile:
27
+ * - `'standard'`: returns a lossless deep clone (Claude / OpenAI / Codex).
28
+ * - `'gemini'`: normalizes into the Gemini FunctionDeclaration subset.
29
+ */
30
+ export declare function normalizeMcpToolInputSchemaForProfile(schema: Tool['inputSchema'], profile: McpToolSchemaProfile): Tool['inputSchema'];
31
+ /**
32
+ * Return a cloned MCP Tool definition with a Gemini-portable `inputSchema`.
33
+ */
34
+ export declare function normalizeMcpToolForPortability<T extends Tool>(tool: T): T;
35
+ /**
36
+ * Return an MCP Tool definition adapted for the requested host schema profile:
37
+ * - `'standard'`: returns `tool` unchanged (lossless standard JSON Schema).
38
+ * - `'gemini'`: returns a cloned tool normalized for Gemini FunctionDeclaration.
39
+ */
40
+ export declare function applyMcpToolSchemaProfile<T extends Tool>(tool: T, profile?: McpToolSchemaProfile): T;
41
+ /**
42
+ * Validate a raw JSON Schema object against Gemini FunctionDeclaration
43
+ * portability requirements. Returns an empty array when fully portable.
44
+ */
45
+ export declare function validateMcpToolInputSchemaPortability(schema: unknown, toolName?: string): McpToolSchemaPortabilityIssue[];
46
+ /**
47
+ * Validate a single MCP Tool's `inputSchema` against Gemini FunctionDeclaration
48
+ * portability requirements. Returns an empty array when fully portable.
49
+ */
50
+ export declare function validateMcpToolSchemaPortability(tool: Pick<Tool, 'name' | 'inputSchema'>): McpToolSchemaPortabilityIssue[];
51
+ /**
52
+ * Assert that every MCP Tool in `tools` satisfies Gemini schema portability.
53
+ */
54
+ export declare function assertMcpToolSchemasPortable(tools: readonly Pick<Tool, 'name' | 'inputSchema'>[]): void;
@@ -0,0 +1,1013 @@
1
+ const SUPPORTED_TYPES = new Set(['object', 'array', 'string', 'number', 'integer', 'boolean']);
2
+ const NULL_NOTE = 'null is also accepted.';
3
+ const CLOSED_EMPTY_OBJECT_NOTE = 'Must be an empty object ({}); additionalProperties: false was relaxed to additionalProperties: true for Gemini schema compatibility.';
4
+ const EMPTY_ENUM_INTERSECTION_NOTE = 'No string value satisfies the intersected enum constraints (empty enum intersection).';
5
+ /**
6
+ * JSON Schema keywords rejected or mis-rendered by Gemini FunctionDeclaration
7
+ * (OpenAPI 3.0 subset). Note that OpenAPI boolean `nullable` is allowed by
8
+ * Gemini and validated separately.
9
+ */
10
+ const FORBIDDEN_KEYWORDS = new Set([
11
+ 'prefixItems',
12
+ 'const',
13
+ 'oneOf',
14
+ 'anyOf',
15
+ 'allOf',
16
+ 'not',
17
+ '$ref',
18
+ '$defs',
19
+ 'definitions',
20
+ '$schema',
21
+ '$id',
22
+ '$anchor',
23
+ '$dynamicRef',
24
+ '$comment',
25
+ 'additionalItems',
26
+ 'dependentSchemas',
27
+ 'dependentRequired',
28
+ 'dependencies',
29
+ 'if',
30
+ 'then',
31
+ 'else',
32
+ 'patternProperties',
33
+ 'propertyNames',
34
+ 'unevaluatedProperties',
35
+ 'unevaluatedItems',
36
+ 'contains',
37
+ 'minContains',
38
+ 'maxContains',
39
+ ]);
40
+ function isPlainObject(value) {
41
+ return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
42
+ }
43
+ function setOwnProperty(target, key, value) {
44
+ Object.defineProperty(target, key, {
45
+ value,
46
+ enumerable: true,
47
+ writable: true,
48
+ configurable: true,
49
+ });
50
+ }
51
+ function appendDescription(existing, addition) {
52
+ const base = typeof existing === 'string' ? existing.trim() : '';
53
+ if (!base)
54
+ return addition;
55
+ if (base.includes(addition))
56
+ return base;
57
+ return `${base} ${addition}`;
58
+ }
59
+ function appendDescriptions(existing, additions) {
60
+ let result = typeof existing === 'string' ? existing.trim() : '';
61
+ for (const addition of additions) {
62
+ if (!addition)
63
+ continue;
64
+ result = appendDescription(result, addition);
65
+ }
66
+ return result || undefined;
67
+ }
68
+ function uniqueStrings(values) {
69
+ return [...new Set(values)];
70
+ }
71
+ function resolvePointer(root, ref) {
72
+ if (!ref.startsWith('#/'))
73
+ return null;
74
+ const parts = ref
75
+ .slice(2)
76
+ .split('/')
77
+ .map((segment) => segment.replaceAll('~1', '/').replaceAll('~0', '~'));
78
+ let current = root;
79
+ for (const part of parts) {
80
+ if (!isPlainObject(current) || !Object.hasOwn(current, part))
81
+ return null;
82
+ current = current[part];
83
+ }
84
+ return isPlainObject(current) ? current : null;
85
+ }
86
+ function isPureNullSchema(node) {
87
+ if (!isPlainObject(node))
88
+ return false;
89
+ if (node.type === 'null')
90
+ return true;
91
+ if (Array.isArray(node.type) && node.type.length > 0 && node.type.every((entry) => entry === 'null'))
92
+ return true;
93
+ if (Object.hasOwn(node, 'const') && node.const === null)
94
+ return true;
95
+ if (Array.isArray(node.enum) && node.enum.length > 0 && node.enum.every((entry) => entry === null))
96
+ return true;
97
+ return false;
98
+ }
99
+ function inferTypeFromValue(value) {
100
+ if (typeof value === 'string')
101
+ return 'string';
102
+ if (typeof value === 'boolean')
103
+ return 'boolean';
104
+ if (typeof value === 'number')
105
+ return Number.isInteger(value) ? 'integer' : 'number';
106
+ if (Array.isArray(value))
107
+ return 'array';
108
+ if (isPlainObject(value))
109
+ return 'object';
110
+ return 'string';
111
+ }
112
+ function finalizeNormalizedSchema(node, isRoot) {
113
+ if (isPlainObject(node.properties)) {
114
+ for (const child of Object.values(node.properties)) {
115
+ if (isPlainObject(child)) {
116
+ finalizeNormalizedSchema(child, false);
117
+ }
118
+ }
119
+ }
120
+ if (isPlainObject(node.items)) {
121
+ finalizeNormalizedSchema(node.items, false);
122
+ }
123
+ if (isPlainObject(node.additionalProperties)) {
124
+ finalizeNormalizedSchema(node.additionalProperties, false);
125
+ }
126
+ if (node.type === 'object') {
127
+ if (Array.isArray(node.required)) {
128
+ const props = isPlainObject(node.properties) ? node.properties : {};
129
+ const filtered = uniqueStrings(node.required.filter((key) => typeof key === 'string' && Object.hasOwn(props, key)));
130
+ if (filtered.length > 0) {
131
+ node.required = filtered;
132
+ }
133
+ else {
134
+ delete node.required;
135
+ }
136
+ }
137
+ if (!isRoot) {
138
+ const hasProperties = isPlainObject(node.properties) && Object.keys(node.properties).length > 0;
139
+ if (!hasProperties && !isPlainObject(node.additionalProperties) && node.additionalProperties !== true) {
140
+ const wasClosedEmpty = node.additionalProperties === false;
141
+ node.additionalProperties = true;
142
+ if (wasClosedEmpty) {
143
+ node.maxProperties = 0;
144
+ node.description = appendDescription(node.description, CLOSED_EMPTY_OBJECT_NOTE);
145
+ }
146
+ }
147
+ }
148
+ }
149
+ }
150
+ function pruneUndeclaredRequired(node) {
151
+ if (isPlainObject(node.properties)) {
152
+ for (const child of Object.values(node.properties)) {
153
+ if (isPlainObject(child)) {
154
+ pruneUndeclaredRequired(child);
155
+ }
156
+ }
157
+ }
158
+ if (isPlainObject(node.items)) {
159
+ pruneUndeclaredRequired(node.items);
160
+ }
161
+ if (isPlainObject(node.additionalProperties)) {
162
+ pruneUndeclaredRequired(node.additionalProperties);
163
+ }
164
+ if (node.type === 'object' && Array.isArray(node.required)) {
165
+ const props = isPlainObject(node.properties) ? node.properties : {};
166
+ const filtered = uniqueStrings(node.required.filter((key) => typeof key === 'string' && Object.hasOwn(props, key)));
167
+ if (filtered.length > 0) {
168
+ node.required = filtered;
169
+ }
170
+ else {
171
+ delete node.required;
172
+ }
173
+ }
174
+ }
175
+ function mergeNormalizedSchemas(branches, mode, preserveUndeclaredRequired = false) {
176
+ const nonNull = branches.filter((branch) => !isPureNullSchema(branch));
177
+ if (nonNull.length === 0)
178
+ return { schema: { type: 'string' }, notes: [] };
179
+ if (nonNull.length === 1) {
180
+ const single = structuredClone(nonNull[0]);
181
+ if (!preserveUndeclaredRequired) {
182
+ pruneUndeclaredRequired(single);
183
+ }
184
+ return { schema: single, notes: [] };
185
+ }
186
+ const anyNullable = mode === 'union' && nonNull.some((branch) => branch.nullable === true);
187
+ const types = new Set(nonNull.map((branch) => String(branch.type ?? 'string')));
188
+ if (types.size === 1) {
189
+ const singleType = [...types][0];
190
+ if (singleType === 'object') {
191
+ const mergedObject = mergeObjectSchemas(nonNull, mode, preserveUndeclaredRequired);
192
+ if (anyNullable) {
193
+ mergedObject.nullable = true;
194
+ mergedObject.description = appendDescription(mergedObject.description, NULL_NOTE);
195
+ }
196
+ return { schema: mergedObject, notes: [] };
197
+ }
198
+ if (singleType === 'string') {
199
+ const result = { type: 'string' };
200
+ const notes = [];
201
+ const description = nonNull.find((branch) => typeof branch.description === 'string')?.description;
202
+ if (typeof description === 'string')
203
+ result.description = description;
204
+ if (mode === 'intersection') {
205
+ const minLengths = nonNull
206
+ .map((branch) => branch.minLength)
207
+ .filter((value) => typeof value === 'number');
208
+ if (minLengths.length > 0)
209
+ result.minLength = Math.max(...minLengths);
210
+ const maxLengths = nonNull
211
+ .map((branch) => branch.maxLength)
212
+ .filter((value) => typeof value === 'number');
213
+ if (maxLengths.length > 0)
214
+ result.maxLength = Math.min(...maxLengths);
215
+ const format = nonNull.find((branch) => typeof branch.format === 'string')?.format;
216
+ if (typeof format === 'string')
217
+ result.format = format;
218
+ const patterns = uniqueStrings(nonNull
219
+ .map((branch) => branch.pattern)
220
+ .filter((value) => typeof value === 'string'));
221
+ if (patterns.length > 0) {
222
+ result.pattern = patterns[0];
223
+ if (patterns.length > 1) {
224
+ const patternNote = `Must also match pattern: ${patterns.slice(1).map((p) => JSON.stringify(p)).join(', ')}.`;
225
+ notes.push(patternNote);
226
+ result.description = appendDescription(result.description, patternNote);
227
+ }
228
+ }
229
+ const enumLists = nonNull
230
+ .filter((branch) => Array.isArray(branch.enum) && branch.enum.length > 0)
231
+ .map((branch) => branch.enum.filter((item) => typeof item === 'string'));
232
+ if (enumLists.length > 0) {
233
+ const [firstEnum, ...restEnums] = enumLists;
234
+ const intersectedEnums = uniqueStrings(firstEnum.filter((value) => restEnums.every((list) => list.includes(value))));
235
+ if (intersectedEnums.length > 0) {
236
+ result.enum = intersectedEnums;
237
+ }
238
+ else {
239
+ result.minLength = Math.max(typeof result.minLength === 'number' ? result.minLength : 0, 1);
240
+ result.maxLength = 0;
241
+ notes.push(EMPTY_ENUM_INTERSECTION_NOTE);
242
+ result.description = appendDescription(result.description, EMPTY_ENUM_INTERSECTION_NOTE);
243
+ }
244
+ }
245
+ }
246
+ else {
247
+ const allHaveEnum = nonNull.every((branch) => Array.isArray(branch.enum) && branch.enum.length > 0);
248
+ if (allHaveEnum) {
249
+ const mergedEnums = uniqueStrings(nonNull.flatMap((branch) => branch.enum.filter((item) => typeof item === 'string')));
250
+ if (mergedEnums.length > 0) {
251
+ if (anyNullable) {
252
+ const note = `Allowed values: ${mergedEnums.map((value) => JSON.stringify(value)).join(', ')}.`;
253
+ notes.push(note);
254
+ result.description = appendDescription(result.description, note);
255
+ }
256
+ else {
257
+ result.enum = mergedEnums;
258
+ }
259
+ }
260
+ }
261
+ }
262
+ if (anyNullable) {
263
+ result.nullable = true;
264
+ result.description = appendDescription(result.description, NULL_NOTE);
265
+ }
266
+ return { schema: result, notes };
267
+ }
268
+ if (singleType === 'array') {
269
+ const itemSchemas = nonNull
270
+ .map((branch) => branch.items)
271
+ .filter((item) => isPlainObject(item));
272
+ const mergedItems = itemSchemas.length > 0
273
+ ? mergeNormalizedSchemas(itemSchemas, mode, preserveUndeclaredRequired).schema
274
+ : { type: 'string' };
275
+ const result = { type: 'array', items: mergedItems };
276
+ if (mode === 'intersection') {
277
+ const minItemsList = nonNull
278
+ .map((branch) => branch.minItems)
279
+ .filter((value) => typeof value === 'number');
280
+ if (minItemsList.length > 0)
281
+ result.minItems = Math.max(...minItemsList);
282
+ const maxItemsList = nonNull
283
+ .map((branch) => branch.maxItems)
284
+ .filter((value) => typeof value === 'number');
285
+ if (maxItemsList.length > 0)
286
+ result.maxItems = Math.min(...maxItemsList);
287
+ if (nonNull.some((branch) => branch.uniqueItems === true)) {
288
+ result.uniqueItems = true;
289
+ }
290
+ }
291
+ const description = nonNull.find((branch) => typeof branch.description === 'string')?.description;
292
+ if (typeof description === 'string')
293
+ result.description = description;
294
+ if (anyNullable) {
295
+ result.nullable = true;
296
+ result.description = appendDescription(result.description, NULL_NOTE);
297
+ }
298
+ return { schema: result, notes: [] };
299
+ }
300
+ const base = structuredClone(nonNull[0]);
301
+ if (mode === 'intersection' && (singleType === 'number' || singleType === 'integer')) {
302
+ const minimums = nonNull
303
+ .map((branch) => branch.minimum)
304
+ .filter((value) => typeof value === 'number');
305
+ if (minimums.length > 0)
306
+ base.minimum = Math.max(...minimums);
307
+ const maximums = nonNull
308
+ .map((branch) => branch.maximum)
309
+ .filter((value) => typeof value === 'number');
310
+ if (maximums.length > 0)
311
+ base.maximum = Math.min(...maximums);
312
+ const exclusiveMinimums = nonNull
313
+ .map((branch) => branch.exclusiveMinimum)
314
+ .filter((value) => typeof value === 'number');
315
+ if (exclusiveMinimums.length > 0)
316
+ base.exclusiveMinimum = Math.max(...exclusiveMinimums);
317
+ const exclusiveMaximums = nonNull
318
+ .map((branch) => branch.exclusiveMaximum)
319
+ .filter((value) => typeof value === 'number');
320
+ if (exclusiveMaximums.length > 0)
321
+ base.exclusiveMaximum = Math.min(...exclusiveMaximums);
322
+ }
323
+ if (anyNullable) {
324
+ base.nullable = true;
325
+ base.description = appendDescription(base.description, NULL_NOTE);
326
+ }
327
+ return { schema: base, notes: [] };
328
+ }
329
+ if (types.size === 2 && types.has('integer') && types.has('number')) {
330
+ const description = nonNull.find((branch) => typeof branch.description === 'string')?.description;
331
+ const result = {
332
+ type: mode === 'intersection' ? 'integer' : 'number',
333
+ ...(typeof description === 'string' ? { description } : {}),
334
+ };
335
+ if (mode === 'intersection') {
336
+ const minimums = nonNull
337
+ .map((branch) => branch.minimum)
338
+ .filter((value) => typeof value === 'number');
339
+ if (minimums.length > 0)
340
+ result.minimum = Math.max(...minimums);
341
+ const maximums = nonNull
342
+ .map((branch) => branch.maximum)
343
+ .filter((value) => typeof value === 'number');
344
+ if (maximums.length > 0)
345
+ result.maximum = Math.min(...maximums);
346
+ const exclusiveMinimums = nonNull
347
+ .map((branch) => branch.exclusiveMinimum)
348
+ .filter((value) => typeof value === 'number');
349
+ if (exclusiveMinimums.length > 0)
350
+ result.exclusiveMinimum = Math.max(...exclusiveMinimums);
351
+ const exclusiveMaximums = nonNull
352
+ .map((branch) => branch.exclusiveMaximum)
353
+ .filter((value) => typeof value === 'number');
354
+ if (exclusiveMaximums.length > 0)
355
+ result.exclusiveMaximum = Math.min(...exclusiveMaximums);
356
+ }
357
+ if (anyNullable) {
358
+ result.nullable = true;
359
+ result.description = appendDescription(result.description, NULL_NOTE);
360
+ }
361
+ return { schema: result, notes: [] };
362
+ }
363
+ const [first, ...rest] = nonNull;
364
+ const merged = structuredClone(first);
365
+ if (!preserveUndeclaredRequired) {
366
+ pruneUndeclaredRequired(merged);
367
+ }
368
+ const firstType = String(merged.type ?? 'value');
369
+ const otherShapes = uniqueStrings(rest
370
+ .map((branch) => String(branch.type ?? 'value'))
371
+ .filter((shape) => shape !== firstType));
372
+ const notes = [];
373
+ if (otherShapes.length > 0) {
374
+ const shapeNote = `Other accepted shapes: ${otherShapes.join(', ')}.`;
375
+ notes.push(shapeNote);
376
+ merged.description = appendDescription(merged.description, shapeNote);
377
+ }
378
+ if (anyNullable) {
379
+ merged.nullable = true;
380
+ merged.description = appendDescription(merged.description, NULL_NOTE);
381
+ }
382
+ return { schema: merged, notes };
383
+ }
384
+ function mergeObjectSchemas(branches, mode, preserveUndeclaredRequired = false) {
385
+ const properties = {};
386
+ const propertyBranches = new Map();
387
+ for (const branch of branches) {
388
+ if (!isPlainObject(branch.properties))
389
+ continue;
390
+ for (const [key, propSchema] of Object.entries(branch.properties)) {
391
+ if (!isPlainObject(propSchema))
392
+ continue;
393
+ const list = propertyBranches.get(key) ?? [];
394
+ list.push(propSchema);
395
+ propertyBranches.set(key, list);
396
+ }
397
+ }
398
+ const closedBranches = mode === 'intersection'
399
+ ? branches.filter((branch) => branch.additionalProperties === false)
400
+ : [];
401
+ for (const [key, list] of propertyBranches.entries()) {
402
+ if (closedBranches.length > 0
403
+ && closedBranches.some((branch) => !isPlainObject(branch.properties) || !Object.hasOwn(branch.properties, key))) {
404
+ continue;
405
+ }
406
+ const effectiveList = mode === 'intersection'
407
+ ? [
408
+ ...list,
409
+ ...branches
410
+ .filter((branch) => isPlainObject(branch.additionalProperties)
411
+ && (!isPlainObject(branch.properties) || !Object.hasOwn(branch.properties, key)))
412
+ .map((branch) => branch.additionalProperties),
413
+ ]
414
+ : list;
415
+ let mergedProp;
416
+ if (effectiveList.length === 1) {
417
+ mergedProp = structuredClone(effectiveList[0]);
418
+ if (!preserveUndeclaredRequired) {
419
+ pruneUndeclaredRequired(mergedProp);
420
+ }
421
+ }
422
+ else {
423
+ mergedProp = mergeNormalizedSchemas(effectiveList, mode, preserveUndeclaredRequired).schema;
424
+ }
425
+ setOwnProperty(properties, key, mergedProp);
426
+ }
427
+ const branchRequiredLists = branches.map((branch) => Array.isArray(branch.required)
428
+ ? branch.required.filter((entry) => typeof entry === 'string')
429
+ : []);
430
+ let required;
431
+ if (mode === 'intersection') {
432
+ required = uniqueStrings(branchRequiredLists.flat());
433
+ }
434
+ else {
435
+ const first = branchRequiredLists[0] ?? [];
436
+ required = uniqueStrings(first.filter((key) => branchRequiredLists.every((list) => list.includes(key))));
437
+ }
438
+ if (!preserveUndeclaredRequired) {
439
+ required = required.filter((key) => Object.hasOwn(properties, key));
440
+ }
441
+ const disallowAdditional = mode === 'intersection'
442
+ ? branches.some((branch) => branch.additionalProperties === false)
443
+ : branches.every((branch) => branch.additionalProperties === false);
444
+ const additionalSchemas = branches
445
+ .map((branch) => branch.additionalProperties)
446
+ .filter((entry) => isPlainObject(entry));
447
+ let mergedAdditionalProperties;
448
+ if (disallowAdditional) {
449
+ mergedAdditionalProperties = false;
450
+ }
451
+ else if (additionalSchemas.length > 0
452
+ && (mode === 'intersection'
453
+ || branches.every((branch) => isPlainObject(branch.additionalProperties) || branch.additionalProperties === false))) {
454
+ if (additionalSchemas.length === 1) {
455
+ mergedAdditionalProperties = structuredClone(additionalSchemas[0]);
456
+ if (!preserveUndeclaredRequired) {
457
+ pruneUndeclaredRequired(mergedAdditionalProperties);
458
+ }
459
+ }
460
+ else {
461
+ mergedAdditionalProperties = mergeNormalizedSchemas(additionalSchemas, mode, preserveUndeclaredRequired).schema;
462
+ }
463
+ }
464
+ const description = branches.find((branch) => typeof branch.description === 'string')?.description;
465
+ const merged = {
466
+ type: 'object',
467
+ ...(Object.keys(properties).length > 0 ? { properties } : {}),
468
+ ...(required.length > 0 ? { required } : {}),
469
+ ...(mergedAdditionalProperties !== undefined ? { additionalProperties: mergedAdditionalProperties } : {}),
470
+ ...(typeof description === 'string' ? { description } : {}),
471
+ };
472
+ return merged;
473
+ }
474
+ function normalizeSchemaNode(rawNode, root, seenRefs, isRoot = false, preserveUndeclaredRequired = false) {
475
+ if (!isPlainObject(rawNode)) {
476
+ return isRoot ? { type: 'object', properties: {} } : { type: 'string' };
477
+ }
478
+ // Resolve internal $ref first (with cycle protection).
479
+ let working = { ...rawNode };
480
+ if (typeof working.$ref === 'string') {
481
+ const ref = working.$ref;
482
+ delete working.$ref;
483
+ if (!seenRefs.has(ref)) {
484
+ const target = resolvePointer(root, ref);
485
+ if (target) {
486
+ const nextSeen = new Set(seenRefs);
487
+ nextSeen.add(ref);
488
+ const resolvedTarget = normalizeSchemaNode(target, root, nextSeen, false, preserveUndeclaredRequired || isPlainObject(working.properties));
489
+ working = { ...resolvedTarget, ...working };
490
+ }
491
+ }
492
+ }
493
+ // Flatten combinators (oneOf / anyOf / allOf) before finalizing node type.
494
+ const combinatorKeys = ['oneOf', 'anyOf', 'allOf'];
495
+ for (const combinatorKey of combinatorKeys) {
496
+ const rawBranches = working[combinatorKey];
497
+ if (!Array.isArray(rawBranches))
498
+ continue;
499
+ delete working[combinatorKey];
500
+ const mode = combinatorKey === 'allOf' ? 'intersection' : 'union';
501
+ const hasOuterObjectFields = isPlainObject(working.properties)
502
+ || Array.isArray(working.required)
503
+ || isPlainObject(working.additionalProperties)
504
+ || working.additionalProperties === false;
505
+ const hasOuterArrayItems = isPlainObject(working.items);
506
+ const preserveBranchRequired = preserveUndeclaredRequired || mode === 'intersection';
507
+ const preserveMergedRequired = preserveUndeclaredRequired
508
+ || (mode === 'intersection' && (hasOuterObjectFields || hasOuterArrayItems));
509
+ const hasNullBranch = rawBranches.some((branch) => isPureNullSchema(branch));
510
+ const normalizedBranches = rawBranches
511
+ .filter((branch) => !isPureNullSchema(branch))
512
+ .map((branch) => normalizeSchemaNode(branch, root, seenRefs, false, preserveBranchRequired));
513
+ const { schema: mergedBranch, notes: mergedNotes } = mergeNormalizedSchemas(normalizedBranches, mode, preserveMergedRequired);
514
+ const shouldBeNullable = working.nullable === true
515
+ || mergedBranch.nullable === true
516
+ || (mode === 'union' && hasNullBranch)
517
+ || (hasNullBranch && normalizedBranches.length === 0);
518
+ // Merge outer sibling properties/required/additionalProperties or array items if present.
519
+ const outerDescription = typeof working.description === 'string' ? working.description : undefined;
520
+ if (mergedBranch.type === 'object' && hasOuterObjectFields) {
521
+ const outerCandidate = { type: 'object' };
522
+ if (isPlainObject(working.properties)) {
523
+ const normalizedOuterProps = {};
524
+ for (const [k, v] of Object.entries(working.properties)) {
525
+ setOwnProperty(normalizedOuterProps, k, normalizeSchemaNode(v, root, seenRefs, false, preserveUndeclaredRequired || mode === 'intersection'));
526
+ }
527
+ outerCandidate.properties = normalizedOuterProps;
528
+ }
529
+ if (Array.isArray(working.required))
530
+ outerCandidate.required = working.required;
531
+ if (isPlainObject(working.additionalProperties)) {
532
+ outerCandidate.additionalProperties = normalizeSchemaNode(working.additionalProperties, root, seenRefs, false, preserveUndeclaredRequired || mode === 'intersection');
533
+ }
534
+ else if (working.additionalProperties === false) {
535
+ outerCandidate.additionalProperties = false;
536
+ }
537
+ const combined = mergeObjectSchemas([outerCandidate, mergedBranch], 'intersection', preserveUndeclaredRequired);
538
+ const finalDescription = outerDescription !== undefined
539
+ ? appendDescriptions(outerDescription, mergedNotes)
540
+ : (typeof combined.description === 'string' ? combined.description : undefined);
541
+ const nextWorking = { ...working };
542
+ delete nextWorking.properties;
543
+ delete nextWorking.required;
544
+ if (isPlainObject(nextWorking.additionalProperties) || nextWorking.additionalProperties === false) {
545
+ delete nextWorking.additionalProperties;
546
+ }
547
+ working = {
548
+ ...nextWorking,
549
+ ...combined,
550
+ ...(finalDescription !== undefined ? { description: finalDescription } : {}),
551
+ };
552
+ }
553
+ else if (mergedBranch.type === 'array' && hasOuterArrayItems) {
554
+ const outerArrayCandidate = {
555
+ type: 'array',
556
+ items: normalizeSchemaNode(working.items, root, seenRefs, false, preserveUndeclaredRequired || mode === 'intersection'),
557
+ };
558
+ const combined = mergeNormalizedSchemas([outerArrayCandidate, mergedBranch], 'intersection', preserveUndeclaredRequired).schema;
559
+ const finalDescription = outerDescription !== undefined
560
+ ? appendDescriptions(outerDescription, mergedNotes)
561
+ : (typeof combined.description === 'string' ? combined.description : undefined);
562
+ working = {
563
+ ...working,
564
+ ...combined,
565
+ ...(finalDescription !== undefined ? { description: finalDescription } : {}),
566
+ };
567
+ }
568
+ else {
569
+ const finalDescription = outerDescription !== undefined
570
+ ? appendDescriptions(outerDescription, mergedNotes)
571
+ : (typeof mergedBranch.description === 'string' ? mergedBranch.description : undefined);
572
+ working = {
573
+ ...working,
574
+ ...mergedBranch,
575
+ ...(finalDescription !== undefined ? { description: finalDescription } : {}),
576
+ };
577
+ }
578
+ if (shouldBeNullable) {
579
+ working.nullable = true;
580
+ }
581
+ }
582
+ // Convert `const` to portable `enum` (string) or scalar type + description.
583
+ if (Object.hasOwn(working, 'const')) {
584
+ const constValue = working.const;
585
+ delete working.const;
586
+ if (typeof constValue === 'string') {
587
+ working.type = 'string';
588
+ working.enum = [constValue];
589
+ }
590
+ else if (constValue === null) {
591
+ working.type = typeof working.type === 'string' && SUPPORTED_TYPES.has(working.type)
592
+ ? working.type
593
+ : 'string';
594
+ working.nullable = true;
595
+ working.description = appendDescription(working.description, 'Must be null.');
596
+ }
597
+ else {
598
+ working.type = inferTypeFromValue(constValue);
599
+ working.description = appendDescription(working.description, `Must be ${JSON.stringify(constValue)}.`);
600
+ }
601
+ }
602
+ // Normalize array-valued `type` (e.g. `['string', 'null']` or `['string', 'integer', 'null']`).
603
+ if (Array.isArray(working.type)) {
604
+ const hasNull = working.type.includes('null');
605
+ if (hasNull)
606
+ working.nullable = true;
607
+ const candidates = uniqueStrings(working.type.filter((entry) => typeof entry === 'string' && entry !== 'null' && SUPPORTED_TYPES.has(entry)));
608
+ if (candidates.length === 1) {
609
+ working.type = candidates[0];
610
+ }
611
+ else if (candidates.length === 2 && candidates.includes('integer') && candidates.includes('number')) {
612
+ working.type = 'number';
613
+ }
614
+ else if (candidates.length > 1) {
615
+ working.type = candidates[0];
616
+ working.description = appendDescription(working.description, `Other accepted shapes: ${candidates.slice(1).join(', ')}.`);
617
+ }
618
+ else {
619
+ working.type = 'string';
620
+ }
621
+ }
622
+ else if (working.type === 'null') {
623
+ working.nullable = true;
624
+ }
625
+ // Handle `enum`: Gemini FunctionDeclaration requires `type: 'string'` and string values,
626
+ // and nullable enums move allowed values into `description` so `null` is not rejected.
627
+ if (Array.isArray(working.enum)) {
628
+ if (working.enum.includes(null)) {
629
+ working.nullable = true;
630
+ }
631
+ const nonNullValues = working.enum.filter((entry) => entry !== null && entry !== undefined);
632
+ if (working.nullable !== true
633
+ && nonNullValues.length > 0
634
+ && nonNullValues.every((entry) => typeof entry === 'string')) {
635
+ working.type = 'string';
636
+ working.enum = uniqueStrings(nonNullValues);
637
+ }
638
+ else {
639
+ delete working.enum;
640
+ if (typeof working.type !== 'string' || !SUPPORTED_TYPES.has(working.type)) {
641
+ const inferredTypes = new Set(nonNullValues.map(inferTypeFromValue));
642
+ working.type = inferredTypes.size === 1 ? [...inferredTypes][0] : 'string';
643
+ }
644
+ if (nonNullValues.length > 0) {
645
+ working.description = appendDescription(working.description, `Allowed values: ${nonNullValues.map((v) => JSON.stringify(v)).join(', ')}.`);
646
+ }
647
+ }
648
+ }
649
+ // Infer missing `type`.
650
+ if (typeof working.type !== 'string' || !SUPPORTED_TYPES.has(working.type)) {
651
+ if (isRoot) {
652
+ working.type = 'object';
653
+ }
654
+ else if (isPlainObject(working.properties)
655
+ || Array.isArray(working.required)
656
+ || isPlainObject(working.additionalProperties)
657
+ || typeof working.additionalProperties === 'boolean') {
658
+ working.type = 'object';
659
+ }
660
+ else if (working.items !== undefined || Array.isArray(working.prefixItems)) {
661
+ working.type = 'array';
662
+ }
663
+ else {
664
+ working.type = 'string';
665
+ }
666
+ }
667
+ if (isRoot) {
668
+ working.type = 'object';
669
+ }
670
+ // Normalize array schemas: convert prefixItems / tuple items to portable `items`.
671
+ if (working.type === 'array') {
672
+ const rawPrefixItems = Array.isArray(working.prefixItems) ? working.prefixItems : null;
673
+ const rawItems = working.items;
674
+ delete working.prefixItems;
675
+ if (rawPrefixItems && rawPrefixItems.length > 0) {
676
+ const hasExplicitItems = isPlainObject(rawItems) && Object.keys(rawItems).length > 0;
677
+ if (hasExplicitItems) {
678
+ working.items = normalizeSchemaNode(rawItems, root, seenRefs, false, preserveUndeclaredRequired);
679
+ }
680
+ else {
681
+ const tupleBranches = rawPrefixItems.map((entry) => normalizeSchemaNode(entry, root, seenRefs, false, preserveUndeclaredRequired));
682
+ if (rawItems === false && working.maxItems === undefined) {
683
+ working.maxItems = rawPrefixItems.length;
684
+ }
685
+ const fixedOrderValues = tupleBranches.every((entry) => entry.type === 'string' && Array.isArray(entry.enum) && entry.enum.length === 1)
686
+ ? tupleBranches.map((entry) => entry.enum[0])
687
+ : null;
688
+ working.items = mergeNormalizedSchemas(tupleBranches, 'union', preserveUndeclaredRequired).schema;
689
+ if (fixedOrderValues && fixedOrderValues.length > 0) {
690
+ working.description = appendDescription(working.description, `In this order: ${fixedOrderValues.map((value) => JSON.stringify(value)).join(', ')}.`);
691
+ }
692
+ }
693
+ }
694
+ else if (Array.isArray(rawItems)) {
695
+ const tupleBranches = rawItems.map((entry) => normalizeSchemaNode(entry, root, seenRefs, false, preserveUndeclaredRequired));
696
+ if (isPlainObject(working.additionalItems)) {
697
+ tupleBranches.push(normalizeSchemaNode(working.additionalItems, root, seenRefs, false, preserveUndeclaredRequired));
698
+ }
699
+ else if (working.additionalItems === false && working.maxItems === undefined) {
700
+ working.maxItems = rawItems.length;
701
+ }
702
+ working.items = tupleBranches.length > 0
703
+ ? mergeNormalizedSchemas(tupleBranches, 'union', preserveUndeclaredRequired).schema
704
+ : { type: 'string' };
705
+ }
706
+ else if (isPlainObject(rawItems)) {
707
+ working.items = normalizeSchemaNode(rawItems, root, seenRefs, false, preserveUndeclaredRequired);
708
+ }
709
+ else {
710
+ working.items = { type: 'string' };
711
+ }
712
+ }
713
+ // Normalize object schemas: recurse into properties and additionalProperties,
714
+ // keep `required` consistent, and mark nested free-form objects explicitly.
715
+ if (working.type === 'object') {
716
+ if (isPlainObject(working.properties)) {
717
+ const normalizedProperties = {};
718
+ for (const [key, child] of Object.entries(working.properties)) {
719
+ setOwnProperty(normalizedProperties, key, normalizeSchemaNode(child, root, seenRefs, false, preserveUndeclaredRequired));
720
+ }
721
+ working.properties = normalizedProperties;
722
+ }
723
+ else if (isRoot) {
724
+ working.properties = {};
725
+ }
726
+ if (isPlainObject(working.additionalProperties)) {
727
+ working.additionalProperties = normalizeSchemaNode(working.additionalProperties, root, seenRefs, false, preserveUndeclaredRequired);
728
+ }
729
+ if (Array.isArray(working.required)) {
730
+ const props = isPlainObject(working.properties) ? working.properties : {};
731
+ const filtered = uniqueStrings(working.required.filter((key) => typeof key === 'string' && (preserveUndeclaredRequired || Object.hasOwn(props, key))));
732
+ if (filtered.length > 0) {
733
+ working.required = filtered;
734
+ }
735
+ else {
736
+ delete working.required;
737
+ }
738
+ }
739
+ else if (working.required !== undefined) {
740
+ delete working.required;
741
+ }
742
+ }
743
+ // Normalize `nullable`: preserve OpenAPI boolean `nullable` (and note `null` in description),
744
+ // strip invalid non-boolean values.
745
+ if (working.nullable === true) {
746
+ working.description = appendDescription(working.description, NULL_NOTE);
747
+ }
748
+ else if (working.nullable !== false && Object.hasOwn(working, 'nullable')) {
749
+ delete working.nullable;
750
+ }
751
+ // Strip any remaining forbidden keywords.
752
+ for (const key of Object.keys(working)) {
753
+ if (FORBIDDEN_KEYWORDS.has(key)) {
754
+ delete working[key];
755
+ }
756
+ }
757
+ return working;
758
+ }
759
+ /**
760
+ * Resolve the MCP tool schema profile from environment variables.
761
+ *
762
+ * Defaults to `'standard'` (lossless JSON Schema for Claude / OpenAI / Codex).
763
+ * Launchers targeting Gemini FunctionDeclaration opt in with
764
+ * `BRAINBASE_MCP_SCHEMA_PROFILE=gemini`.
765
+ */
766
+ export function resolveMcpToolSchemaProfile(env = process.env) {
767
+ return env.BRAINBASE_MCP_SCHEMA_PROFILE?.trim().toLowerCase() === 'gemini' ? 'gemini' : 'standard';
768
+ }
769
+ /**
770
+ * Normalize an MCP tool `inputSchema` into the Gemini FunctionDeclaration
771
+ * (OpenAPI 3.0) compatible JSON Schema subset.
772
+ *
773
+ * Idempotent on already-portable schemas.
774
+ */
775
+ export function normalizeMcpToolInputSchemaForPortability(schema) {
776
+ const cloned = isPlainObject(schema) ? structuredClone(schema) : { type: 'object', properties: {} };
777
+ const normalized = normalizeSchemaNode(cloned, cloned, new Set(), true);
778
+ finalizeNormalizedSchema(normalized, true);
779
+ return normalized;
780
+ }
781
+ /**
782
+ * Normalize an MCP tool `inputSchema` according to the target host profile:
783
+ * - `'standard'`: returns a lossless deep clone (Claude / OpenAI / Codex).
784
+ * - `'gemini'`: normalizes into the Gemini FunctionDeclaration subset.
785
+ */
786
+ export function normalizeMcpToolInputSchemaForProfile(schema, profile) {
787
+ if (profile === 'gemini') {
788
+ return normalizeMcpToolInputSchemaForPortability(schema);
789
+ }
790
+ return structuredClone(schema);
791
+ }
792
+ /**
793
+ * Return a cloned MCP Tool definition with a Gemini-portable `inputSchema`.
794
+ */
795
+ export function normalizeMcpToolForPortability(tool) {
796
+ const cloned = structuredClone(tool);
797
+ return {
798
+ ...cloned,
799
+ inputSchema: normalizeMcpToolInputSchemaForPortability(cloned.inputSchema),
800
+ };
801
+ }
802
+ /**
803
+ * Return an MCP Tool definition adapted for the requested host schema profile:
804
+ * - `'standard'`: returns `tool` unchanged (lossless standard JSON Schema).
805
+ * - `'gemini'`: returns a cloned tool normalized for Gemini FunctionDeclaration.
806
+ */
807
+ export function applyMcpToolSchemaProfile(tool, profile = resolveMcpToolSchemaProfile()) {
808
+ return profile === 'gemini' ? normalizeMcpToolForPortability(tool) : tool;
809
+ }
810
+ function validateSchemaNode(toolName, node, path, issues, isRoot = false) {
811
+ if (!isPlainObject(node)) {
812
+ issues.push({
813
+ tool: toolName,
814
+ path,
815
+ code: isRoot ? 'root_not_object' : 'type_missing',
816
+ message: `${path} must be a JSON Schema object.`,
817
+ });
818
+ return;
819
+ }
820
+ for (const key of Object.keys(node)) {
821
+ if (FORBIDDEN_KEYWORDS.has(key)) {
822
+ issues.push({
823
+ tool: toolName,
824
+ path: `${path}.${key}`,
825
+ code: 'forbidden_keyword',
826
+ message: `${path} uses non-portable JSON Schema keyword "${key}".`,
827
+ });
828
+ }
829
+ }
830
+ if (Object.hasOwn(node, 'nullable') && typeof node.nullable !== 'boolean') {
831
+ issues.push({
832
+ tool: toolName,
833
+ path: `${path}.nullable`,
834
+ code: 'nullable_invalid',
835
+ message: `${path}.nullable must be a boolean.`,
836
+ });
837
+ }
838
+ if (Array.isArray(node.type)) {
839
+ issues.push({
840
+ tool: toolName,
841
+ path: `${path}.type`,
842
+ code: 'type_array_forbidden',
843
+ message: `${path}.type must be a single type string, not an array (${JSON.stringify(node.type)}).`,
844
+ });
845
+ }
846
+ else if (typeof node.type !== 'string') {
847
+ issues.push({
848
+ tool: toolName,
849
+ path: `${path}.type`,
850
+ code: 'type_missing',
851
+ message: `${path} is missing a string "type" field.`,
852
+ });
853
+ }
854
+ else if (!SUPPORTED_TYPES.has(node.type)) {
855
+ issues.push({
856
+ tool: toolName,
857
+ path: `${path}.type`,
858
+ code: 'type_unsupported',
859
+ message: `${path}.type "${node.type}" is not supported across Gemini/OpenAI/Claude tool schemas.`,
860
+ });
861
+ }
862
+ if (isRoot) {
863
+ if (node.type !== 'object') {
864
+ issues.push({
865
+ tool: toolName,
866
+ path: `${path}.type`,
867
+ code: 'root_not_object',
868
+ message: `Root inputSchema must have type "object".`,
869
+ });
870
+ }
871
+ if (!isPlainObject(node.properties)) {
872
+ issues.push({
873
+ tool: toolName,
874
+ path: `${path}.properties`,
875
+ code: 'root_properties_missing',
876
+ message: `Root inputSchema must declare a "properties" object.`,
877
+ });
878
+ }
879
+ }
880
+ if (Object.hasOwn(node, 'enum')) {
881
+ if (node.type !== 'string') {
882
+ issues.push({
883
+ tool: toolName,
884
+ path: `${path}.enum`,
885
+ code: 'enum_type_not_string',
886
+ message: `${path} declares "enum" without type: "string" (Gemini only accepts string enums).`,
887
+ });
888
+ }
889
+ if (!Array.isArray(node.enum)
890
+ || node.enum.length === 0
891
+ || node.enum.some((entry) => typeof entry !== 'string')
892
+ || new Set(node.enum).size !== node.enum.length) {
893
+ issues.push({
894
+ tool: toolName,
895
+ path: `${path}.enum`,
896
+ code: 'enum_invalid',
897
+ message: `${path}.enum must be a non-empty array of unique strings.`,
898
+ });
899
+ }
900
+ }
901
+ if (node.type === 'array') {
902
+ if (Array.isArray(node.items)) {
903
+ issues.push({
904
+ tool: toolName,
905
+ path: `${path}.items`,
906
+ code: 'array_items_tuple_forbidden',
907
+ message: `${path}.items must be a single schema object, not a tuple array.`,
908
+ });
909
+ }
910
+ else if (!isPlainObject(node.items) || Object.keys(node.items).length === 0) {
911
+ issues.push({
912
+ tool: toolName,
913
+ path: `${path}.items`,
914
+ code: 'array_items_missing',
915
+ message: `${path} has type "array" without a non-empty "items" schema (causes Gemini 400 INVALID_ARGUMENT).`,
916
+ });
917
+ }
918
+ else {
919
+ validateSchemaNode(toolName, node.items, `${path}.items`, issues, false);
920
+ }
921
+ }
922
+ else if (isPlainObject(node.items)) {
923
+ validateSchemaNode(toolName, node.items, `${path}.items`, issues, false);
924
+ }
925
+ if (node.type === 'object') {
926
+ if (node.properties !== undefined && !isPlainObject(node.properties)) {
927
+ issues.push({
928
+ tool: toolName,
929
+ path: `${path}.properties`,
930
+ code: 'properties_invalid',
931
+ message: `${path}.properties must be a plain object.`,
932
+ });
933
+ }
934
+ const properties = isPlainObject(node.properties) ? node.properties : undefined;
935
+ if (!isRoot) {
936
+ const hasProperties = Boolean(properties) && Object.keys(properties).length > 0;
937
+ if (!hasProperties && !isPlainObject(node.additionalProperties) && node.additionalProperties !== true) {
938
+ issues.push({
939
+ tool: toolName,
940
+ path,
941
+ code: 'object_properties_missing',
942
+ message: `${path} has type "object" without non-empty "properties" or "additionalProperties" (causes Gemini 400 INVALID_ARGUMENT).`,
943
+ });
944
+ }
945
+ }
946
+ if (node.required !== undefined) {
947
+ if (!Array.isArray(node.required) || node.required.some((entry) => typeof entry !== 'string')) {
948
+ issues.push({
949
+ tool: toolName,
950
+ path: `${path}.required`,
951
+ code: 'required_not_array',
952
+ message: `${path}.required must be an array of strings.`,
953
+ });
954
+ }
955
+ else {
956
+ for (const requiredKey of node.required) {
957
+ if (!properties || !Object.hasOwn(properties, requiredKey)) {
958
+ issues.push({
959
+ tool: toolName,
960
+ path: `${path}.required`,
961
+ code: 'required_property_missing',
962
+ message: `${path}.required lists "${requiredKey}" which is not declared in ${path}.properties.`,
963
+ });
964
+ }
965
+ }
966
+ }
967
+ }
968
+ }
969
+ if (isPlainObject(node.properties)) {
970
+ for (const [key, child] of Object.entries(node.properties)) {
971
+ validateSchemaNode(toolName, child, `${path}.properties.${key}`, issues, false);
972
+ }
973
+ }
974
+ if (isPlainObject(node.additionalProperties)) {
975
+ validateSchemaNode(toolName, node.additionalProperties, `${path}.additionalProperties`, issues, false);
976
+ }
977
+ for (const key of ['anyOf', 'oneOf', 'allOf', 'prefixItems']) {
978
+ const list = node[key];
979
+ if (Array.isArray(list)) {
980
+ list.forEach((child, index) => {
981
+ validateSchemaNode(toolName, child, `${path}.${key}[${index}]`, issues, false);
982
+ });
983
+ }
984
+ }
985
+ }
986
+ /**
987
+ * Validate a raw JSON Schema object against Gemini FunctionDeclaration
988
+ * portability requirements. Returns an empty array when fully portable.
989
+ */
990
+ export function validateMcpToolInputSchemaPortability(schema, toolName = '<schema>') {
991
+ const issues = [];
992
+ validateSchemaNode(toolName, schema, 'inputSchema', issues, true);
993
+ return issues;
994
+ }
995
+ /**
996
+ * Validate a single MCP Tool's `inputSchema` against Gemini FunctionDeclaration
997
+ * portability requirements. Returns an empty array when fully portable.
998
+ */
999
+ export function validateMcpToolSchemaPortability(tool) {
1000
+ return validateMcpToolInputSchemaPortability(tool.inputSchema, tool.name);
1001
+ }
1002
+ /**
1003
+ * Assert that every MCP Tool in `tools` satisfies Gemini schema portability.
1004
+ */
1005
+ export function assertMcpToolSchemasPortable(tools) {
1006
+ const issues = tools.flatMap((tool) => validateMcpToolSchemaPortability(tool));
1007
+ if (issues.length === 0)
1008
+ return;
1009
+ const formatted = issues
1010
+ .map((issue) => `- ${issue.tool} (${issue.path}) [${issue.code}]: ${issue.message}`)
1011
+ .join('\n');
1012
+ throw new Error(`MCP tool inputSchema portability violations detected:\n${formatted}`);
1013
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@unson/brainbase-mcp",
3
- "version": "0.50.27",
3
+ "version": "0.50.29",
4
4
  "description": "Local-first Brainbase judgment OS that lets supported AI agents reuse a user's approved goals, priorities, decisions, and judgment criteria.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -375,6 +375,10 @@
375
375
  "types": "./dist/mcp-runtime.d.ts",
376
376
  "import": "./dist/mcp-runtime.js"
377
377
  },
378
+ "./mcp-tool-schema-portability": {
379
+ "types": "./dist/mcp-tool-schema-portability.d.ts",
380
+ "import": "./dist/mcp-tool-schema-portability.js"
381
+ },
378
382
  "./resource-reservations": {
379
383
  "types": "./dist/resource-reservations.d.ts",
380
384
  "import": "./dist/resource-reservations.js"
@@ -669,5 +673,5 @@
669
673
  "url": "https://github.com/Unson-LLC/brainbase/issues"
670
674
  },
671
675
  "homepage": "https://github.com/Unson-LLC/brainbase#readme",
672
- "gitHead": "207222270ff06f599f058734eb7ef2ee2f7d87c8"
676
+ "gitHead": "912df89b1695249b1a31d9846b5e3e7e213e53ea"
673
677
  }
@@ -881,7 +881,7 @@ export function createMeetingMinutesUI({
881
881
  detailTools.replaceChildren(detailNotice);
882
882
  const native = selected && typeof selected.body === 'string' && !isRecord(selected.source_ref);
883
883
  const latest = documentRecord.current_version_id === selected?.version_id;
884
- if (!native || !latest || documentRecord.withdrawal || !canEdit()) return;
884
+ if (!native || !latest || documentRecord.withdrawal || !canEdit(detail, documentRecord)) return;
885
885
  const editing = state.editingMinutesId === documentRecord.minutes_id;
886
886
  const toggle = workspaceKit.workspaceButton(doc, {
887
887
  attrs: { 'aria-label': editing ? '編集をやめる' : '本文を編集する', title: editing ? '編集をやめる' : '本文を編集する' },
@@ -1082,15 +1082,23 @@ export function createMeetingMinutesUI({
1082
1082
  );
1083
1083
  }
1084
1084
 
1085
- function canEdit() {
1085
+ function editDecision(detail, documentRecord) {
1086
1086
  if (typeof canEditMinutes === 'function') {
1087
1087
  try {
1088
- return canEditMinutes() === true;
1088
+ const result = canEditMinutes({ meeting: detail?.meeting ?? null, document: documentRecord ?? null });
1089
+ if (isRecord(result)) {
1090
+ return { allowed: result.allowed === true, reason: result.reason };
1091
+ }
1092
+ return { allowed: result === true };
1089
1093
  } catch {
1090
- return false;
1094
+ return { allowed: false };
1091
1095
  }
1092
1096
  }
1093
- return canEditMinutes !== false;
1097
+ return { allowed: canEditMinutes !== false };
1098
+ }
1099
+
1100
+ function canEdit(detail, documentRecord) {
1101
+ return editDecision(detail, documentRecord).allowed;
1094
1102
  }
1095
1103
 
1096
1104
  function viewerId() {
@@ -1121,17 +1129,21 @@ export function createMeetingMinutesUI({
1121
1129
  line.append(node);
1122
1130
  }
1123
1131
 
1124
- // One gray notice per detail, only when something cannot be done here.
1125
- function appendReadOnlyNotice(parent, version) {
1132
+ // Keep source notices compact; each denied document still explains its own edit decision.
1133
+ function appendReadOnlyNotice(parent, version, detail, documentRecord) {
1126
1134
  const source = isRecord(version?.source_ref) ? version.source_ref : null;
1127
- const editable = canEdit();
1135
+ const decision = editDecision(detail, documentRecord);
1136
+ const editable = decision.allowed;
1137
+ const needsProject = decision.reason === 'project_selection_required';
1128
1138
  if (editable && !source) return false;
1129
1139
  const url = httpUrl(source?.locator);
1130
1140
  const provider = text(source?.provider, '元の記録');
1131
1141
  const notice = makeElement(doc, 'div', { className: 'bb-minutes-edit-guard is-info' });
1132
1142
  if (!editable) {
1133
1143
  notice.append(makeElement(doc, 'p', {
1134
- textContent: 'この画面では読むことだけができます。確認はプロジェクトの編集権限がある人が行います。',
1144
+ textContent: needsProject
1145
+ ? '確認・編集するには、プロジェクトを1つ選んでください。'
1146
+ : 'この画面では読むことだけができます。確認はプロジェクトの編集権限がある人が行います。',
1135
1147
  }));
1136
1148
  }
1137
1149
  if (url) {
@@ -1144,7 +1156,7 @@ export function createMeetingMinutesUI({
1144
1156
  notice.append(line);
1145
1157
  } else if (source) {
1146
1158
  notice.append(makeElement(doc, 'p', { textContent: '本文を直すときは、議事録を取り込んだ元で編集してください。' }));
1147
- } else {
1159
+ } else if (!needsProject) {
1148
1160
  notice.append(makeElement(doc, 'p', { textContent: '本文を直すのも、プロジェクトの編集権限がある人です。' }));
1149
1161
  }
1150
1162
  parent.append(notice);
@@ -1690,7 +1702,7 @@ export function createMeetingMinutesUI({
1690
1702
  const viewingOld = Boolean(selected && latest && selected.version_id !== latest.version_id);
1691
1703
  const withdrawal = isRecord(documentRecord.withdrawal) ? documentRecord.withdrawal : null;
1692
1704
  const native = isRecord(selected) && typeof selected.body === 'string' && !isRecord(selected.source_ref);
1693
- const editing = state.editingMinutesId === documentRecord.minutes_id && native && !viewingOld && !withdrawal && canEdit();
1705
+ const editing = state.editingMinutesId === documentRecord.minutes_id && native && !viewingOld && !withdrawal && canEdit(detail, documentRecord);
1694
1706
  const section = makeElement(doc, 'section', { className: tablePage ? 'mp-detail-section' : 'bb-minutes-document' });
1695
1707
  if (tablePage) decorateDetailTools(documentRecord, selected, versions, detail);
1696
1708
  if (withdrawal) {
@@ -1714,9 +1726,9 @@ export function createMeetingMinutesUI({
1714
1726
  const actions = makeElement(doc, 'div', { className: 'bb-minutes-version-actions' });
1715
1727
  actions.append(stateChip(selectedState, { detailed: true }));
1716
1728
  if (!withdrawal && !editing) {
1717
- if (selected && canEdit() && !isRecord(selected.confirmation) && selectedState.code !== 'unknown' && selectedState.code !== 'creating') {
1729
+ if (selected && canEdit(detail, documentRecord) && !isRecord(selected.confirmation) && selectedState.code !== 'unknown' && selectedState.code !== 'creating') {
1718
1730
  const confirm = button(doc, 'この版を確認済みにする', async () => {
1719
- if (!canEdit()) {
1731
+ if (!canEdit(detail, documentRecord)) {
1720
1732
  rerender(detail, documentRecord, selected);
1721
1733
  return;
1722
1734
  }
@@ -1737,14 +1749,14 @@ export function createMeetingMinutesUI({
1737
1749
  }, { className: 'bb-minutes-button is-primary' });
1738
1750
  actions.append(confirm);
1739
1751
  }
1740
- if (!tablePage && native && !viewingOld && canEdit()) {
1752
+ if (!tablePage && native && !viewingOld && canEdit(detail, documentRecord)) {
1741
1753
  actions.append(button(doc, '編集', () => {
1742
1754
  state.editingMinutesId = documentRecord.minutes_id;
1743
1755
  state.withdrawingMinutesId = null;
1744
1756
  rerender(detail, documentRecord, selected);
1745
1757
  }));
1746
1758
  }
1747
- if (canEdit() && mayWithdraw(documentRecord)) {
1759
+ if (canEdit(detail, documentRecord) && mayWithdraw(documentRecord)) {
1748
1760
  actions.append(button(doc, '取り下げる', () => {
1749
1761
  state.withdrawingMinutesId = documentRecord.minutes_id;
1750
1762
  state.editingMinutesId = null;
@@ -1754,13 +1766,13 @@ export function createMeetingMinutesUI({
1754
1766
  }
1755
1767
  if (tablePage) { detailDrawer.footer.replaceChildren(...actions.children); }
1756
1768
  else section.append(actions);
1757
- if (!withdrawal && canEdit() && !mayWithdraw(documentRecord)) {
1769
+ if (!withdrawal && canEdit(detail, documentRecord) && !mayWithdraw(documentRecord)) {
1758
1770
  section.append(makeElement(doc, 'p', { className: 'bb-minutes-withdraw-guard', textContent: '取り下げられるのは、この議事録を作った人だけです。' }));
1759
1771
  }
1760
- if (!withdrawal && state.withdrawingMinutesId === documentRecord.minutes_id && canEdit() && mayWithdraw(documentRecord)) {
1772
+ if (!withdrawal && state.withdrawingMinutesId === documentRecord.minutes_id && canEdit(detail, documentRecord) && mayWithdraw(documentRecord)) {
1761
1773
  section.append(renderWithdrawConfirm(detail, documentRecord, selected));
1762
1774
  }
1763
- if (!noticeState.placed && appendReadOnlyNotice(section, selected)) noticeState.placed = true;
1775
+ if ((!noticeState.placed || !canEdit(detail, documentRecord)) && appendReadOnlyNotice(section, selected, detail, documentRecord)) noticeState.placed = true;
1764
1776
  const content = makeElement(doc, 'div', { className: 'bb-minutes-version-content' });
1765
1777
  const bodyRoot = makeElement(doc, 'div', {
1766
1778
  className: 'bb-minutes-external-body-slot',
@@ -1876,7 +1888,7 @@ export function createMeetingMinutesUI({
1876
1888
  } else { row.append(save, cancel); form.append(row); }
1877
1889
  form.addEventListener('submit', async (event) => {
1878
1890
  event.preventDefault();
1879
- if (!canEdit()) {
1891
+ if (!canEdit(detail, documentRecord)) {
1880
1892
  state.editingMinutesId = null;
1881
1893
  rerender(detail, documentRecord, selected);
1882
1894
  return;
@@ -1922,7 +1934,7 @@ export function createMeetingMinutesUI({
1922
1934
  panel.append(facts);
1923
1935
  const row = makeElement(doc, 'div', { className: 'bb-minutes-actions' });
1924
1936
  const confirm = button(doc, '取り下げる', async () => {
1925
- if (!canEdit() || !mayWithdraw(documentRecord)) {
1937
+ if (!canEdit(detail, documentRecord) || !mayWithdraw(documentRecord)) {
1926
1938
  state.withdrawingMinutesId = null;
1927
1939
  rerender(detail, documentRecord, selected);
1928
1940
  return;
@@ -2035,7 +2047,7 @@ export function createMeetingMinutesUI({
2035
2047
  const noticeState = { placed: false };
2036
2048
  if (documents.length === 0) {
2037
2049
  detailPane.append(makeElement(doc, 'p', { className: 'bb-minutes-warning', textContent: '議事録文書を読み取れません。' }));
2038
- appendReadOnlyNotice(detailPane, null);
2050
+ appendReadOnlyNotice(detailPane, null, detail, null);
2039
2051
  noticeState.placed = true;
2040
2052
  }
2041
2053
  if (tablePage && documents.length > 1) {