@descix/platform-api 1.0.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.
- package/LICENSE.md +671 -0
- package/README.md +53 -0
- package/package.json +39 -0
- package/src/auth/emailVerification.js +108 -0
- package/src/auth/index.js +9 -0
- package/src/auth/migration.js +96 -0
- package/src/auth/session.js +33 -0
- package/src/email/index.js +259 -0
- package/src/entitlements/index.js +86 -0
- package/src/fabric/index.js +8 -0
- package/src/fabric/vocab.js +1402 -0
- package/src/index.js +107 -0
- package/src/manifest/index.js +13 -0
- package/src/mcp-tools/chatMedia.js +387 -0
- package/src/mcp-tools/evidence-contract.js +324 -0
- package/src/mcp-tools/handshake.js +69 -0
- package/src/mcp-tools/index.js +107 -0
- package/src/mcp-tools/nativeTools.js +902 -0
- package/src/mcp-tools/paramValidation.js +562 -0
- package/src/mcp-tools/recordFilter.js +88 -0
- package/src/mcp-tools/setup-playbook.js +277 -0
- package/src/models/index.js +1901 -0
- package/src/naming/index.js +13 -0
- package/src/permissions/index.js +157 -0
- package/src/service-bootstrap/index.js +13 -0
|
@@ -0,0 +1,562 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* paramValidation.js — strict, fail-loud parameter validation for the MCP surface
|
|
3
|
+
* (ws-mcp-surface-basics, CEO-D-2026-08-14-MCP-BASICS).
|
|
4
|
+
*
|
|
5
|
+
* THE PROBLEM this closes: a tool's `inputSchema` was used ONLY to ADVERTISE at tools/list.
|
|
6
|
+
* At tools/call the arguments object was spread verbatim into the handler, which destructured
|
|
7
|
+
* the keys it knew and silently dropped the rest. So a well-formed-looking call carrying a
|
|
8
|
+
* WRONG-BUT-PLAUSIBLE param name executed against the DEFAULT instead of failing:
|
|
9
|
+
*
|
|
10
|
+
* ask_question_to_app({ app_id:'unk-beast', kb_id:'Org', user_input:'...' })
|
|
11
|
+
* -> kb_id is not in ask_question_to_app's schema (it is query_knowledge_base's name for
|
|
12
|
+
* the same concept), so it was dropped, the default KB was used, and the caller got
|
|
13
|
+
* "KnowledgeBase 'General' not found" — an error naming a KB it never asked for.
|
|
14
|
+
*
|
|
15
|
+
* That is the silent-failure class. The schema IS the published contract, so anything not in
|
|
16
|
+
* it is an ERROR, named out loud, with the nearest valid parameter suggested.
|
|
17
|
+
*
|
|
18
|
+
* Dependency-free leaf: imported by BOTH the Cloud MCP router (apiFront tools/call + the
|
|
19
|
+
* execute_remote_command gateway, which feed it the per-command commandMeta inputSchema) and
|
|
20
|
+
* the CLI stdio MCP server (which feeds it the NATIVE_MCP_TOOLS inputSchema). ONE validator,
|
|
21
|
+
* one message format, no parallel implementations.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Curated cross-tool confusions. Edit distance alone cannot connect these — they are different
|
|
26
|
+
* WORDS for the same concept on ADJACENT tools, which is exactly why callers get them wrong.
|
|
27
|
+
* Each entry maps a wrong-but-plausible key to the canonical key(s) it is usually meant to be.
|
|
28
|
+
*/
|
|
29
|
+
export const PARAM_ALIASES = Object.freeze({
|
|
30
|
+
// The one that bit JARVIS: query_knowledge_base says kb_id, ask_question_to_app says
|
|
31
|
+
// knowledgebase_name, and both take an app_id — so the call looks right and dies wrong.
|
|
32
|
+
kb_id: ['knowledgebase_name'],
|
|
33
|
+
kb_ids: ['knowledgebase_names'],
|
|
34
|
+
kb: ['knowledgebase_name', 'kb_id'],
|
|
35
|
+
kb_name: ['knowledgebase_name', 'kb_id'],
|
|
36
|
+
knowledgebase: ['knowledgebase_name', 'kb_id'],
|
|
37
|
+
knowledgebase_id: ['knowledgebase_name', 'kb_id'],
|
|
38
|
+
knowledgebase_name: ['kb_id'],
|
|
39
|
+
knowledgebase_names: ['kb_ids'],
|
|
40
|
+
// Ask-vs-search phrasing.
|
|
41
|
+
query: ['user_input'],
|
|
42
|
+
user_input: ['query'],
|
|
43
|
+
question: ['user_input', 'query'],
|
|
44
|
+
prompt: ['user_input', 'query'],
|
|
45
|
+
text: ['user_input', 'query'],
|
|
46
|
+
// Identity shorthands.
|
|
47
|
+
app: ['app_id'],
|
|
48
|
+
appId: ['app_id'],
|
|
49
|
+
community: ['community_id'],
|
|
50
|
+
communityId: ['community_id'],
|
|
51
|
+
// Thread continuation.
|
|
52
|
+
interaction_id: ['previous_interaction_id'],
|
|
53
|
+
previous_interaction: ['previous_interaction_id'],
|
|
54
|
+
thread_id: ['previous_interaction_id'],
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* THE ONE OWNER of "which keys does the PLATFORM ITSELF put into a params bag?".
|
|
59
|
+
*
|
|
60
|
+
* WHY ONE OWNER. Two derivations of this fact disagreed silently, and the Powch microservice
|
|
61
|
+
* built its closed per-command schemas against one of them — so the platform's own signed
|
|
62
|
+
* `_descix` envelope, injected downstream of every boundary check by serviceManifestManager.js
|
|
63
|
+
* proxyToExternalService, was refused at Powch's door and DEV login went down. Every surface that
|
|
64
|
+
* needs the answer reads it here; nobody re-derives it.
|
|
65
|
+
*
|
|
66
|
+
* WHAT QUALIFIES. A key belongs here iff PLATFORM code WRITES it into a params bag after the
|
|
67
|
+
* caller's bag has been taken, i.e. there is an INJECTOR. Two consumers read this list and they
|
|
68
|
+
* sit on opposite sides of that write:
|
|
69
|
+
* - the BOUNDARY validators (`validateParamsAgainstSchema`, reached from MCP tools/call and the
|
|
70
|
+
* execute_remote_command gateway) run BEFORE injection, so the list is what keeps a
|
|
71
|
+
* RE-validation of an already-decorated bag from failing;
|
|
72
|
+
* - the HANDLER-level guard (Cloud `assertKnownParams`) and every downstream mesh service run
|
|
73
|
+
* AFTER injection, so the list is what stops a framework key being reported as an unknown
|
|
74
|
+
* parameter the caller never sent.
|
|
75
|
+
*
|
|
76
|
+
* WHAT DOES NOT QUALIFY — and this is the rule that keeps the list honest. It is NOT a parking
|
|
77
|
+
* space for caller-facing params. Anything listed here is waved past the published contract on
|
|
78
|
+
* EVERY command IN THE POST-INJECTION VIEW, so a key that a caller can legitimately send is
|
|
79
|
+
* exactly the wrong thing to add: it converts a named refusal ("unknown parameter 'kb_id'") back
|
|
80
|
+
* into the silent drop this module exists to kill. A key the platform injects but ALSO
|
|
81
|
+
* deliberately refuses from callers (`interaction_owner_id`, stripped by
|
|
82
|
+
* interactionSession.stripClientRoomOwner precisely so the boundary can refuse it by name) is
|
|
83
|
+
* likewise excluded — allow-listing it would pre-empt that refusal.
|
|
84
|
+
*
|
|
85
|
+
* THE 24 -> 21 NARROWING. The superseded second derivation (DeSciX_Cloud commandParamGuard's
|
|
86
|
+
* deleted RESERVED_PARAM_KEYS) carried 24 names. Three of them are NOT platform writes and are
|
|
87
|
+
* dropped here: `target_community_id`, `target_user_id` and `reactor_id` are CALLER-SENT fallback
|
|
88
|
+
* READS on the Discord bot's own bag (apiFront.js:1150 `params.user_id || params.target_user_id ||
|
|
89
|
+
* params.reactor_id`; apiFront.js:1234 `params.community_id || params.target_community_id`) — the
|
|
90
|
+
* platform reads them, it never writes them, so listing them would wave three caller-authored keys
|
|
91
|
+
* past every command's contract. The remaining 21 each have a named injector site below.
|
|
92
|
+
*
|
|
93
|
+
* THE GROUPS, and why each exists. Injector sites are DeSciX_Cloud/microservice/services/.
|
|
94
|
+
*/
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* (A) REQUEST ENVELOPE — spread into EVERY params bag at construction on the /apifront door
|
|
98
|
+
* (apiFront.js `const params = { ...requestJSON.params, user_id_from_req, wallet_address_from_req,
|
|
99
|
+
* signature_from_req, guild_id }`). Present on every call, which is why omitting them once
|
|
100
|
+
* refused every live call on the platform.
|
|
101
|
+
*/
|
|
102
|
+
const ENVELOPE_KEYS = ['user_id_from_req', 'wallet_address_from_req', 'signature_from_req', 'guild_id'];
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* (B) RESOLVED IDENTITY / AUTH — what the auth middleware decided the caller IS, written over
|
|
106
|
+
* anything the client sent (apiFront.js: `params.user`, `params.user_id`, `params.wallet_address`,
|
|
107
|
+
* `params.signature`, `params.delegate`, `params.service_account`, `params.master_wallet_address`;
|
|
108
|
+
* commandHandlers/serviceCommands.js `execute_remote_command` re-forwards `user`, `community_id`,
|
|
109
|
+
* `access_token`, `service_account` onto the inner bag so the inner command runs as the SAME
|
|
110
|
+
* caller). These are the platform's answer to "who is calling", never the caller's.
|
|
111
|
+
*/
|
|
112
|
+
const IDENTITY_KEYS = [
|
|
113
|
+
'user', 'user_id', 'community_id', 'access_token', 'wallet_address', 'signature',
|
|
114
|
+
'delegate', 'service_account', 'master_wallet_address',
|
|
115
|
+
];
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* (C) SERVER-DERIVED REQUEST CONTEXT — read from headers/session and written onto params
|
|
119
|
+
* (apiFront.js `params.currentLoginStatus`, `params.source_guild_id`, `params.server_origin` from
|
|
120
|
+
* the Origin/Referer headers). Deliberately server-derived: `server_origin` exists BECAUSE a
|
|
121
|
+
* client-supplied origin would be a redirect-URI injection, and the same line deletes any
|
|
122
|
+
* `client_origin` the caller sent.
|
|
123
|
+
*/
|
|
124
|
+
const REQUEST_CONTEXT_KEYS = ['currentLoginStatus', 'source_guild_id', 'server_origin'];
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* (D) DISCORD COMMAND ADAPTER — apiFront rewrites `replyToDiscordUserCloudFunction` into a RAG
|
|
128
|
+
* call and writes the resolved routing onto params (apiFront.js `params.user_input`,
|
|
129
|
+
* `params.app_id`, `params.streaming`, `params.messageData`). The bot never sends these under
|
|
130
|
+
* these names; the adapter manufactures them.
|
|
131
|
+
*/
|
|
132
|
+
const DISCORD_ADAPTER_KEYS = ['user_input', 'app_id', 'streaming', 'messageData'];
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* (E) MESH CALLER-AUTH ENVELOPE — the signed caller context apifront attaches to every outbound
|
|
136
|
+
* mesh call (serviceManifestManager.js: `enrichedParams._descix = { user, entitlements, serviceId,
|
|
137
|
+
* timestamp }`, then `enrichedParams._descix = signedContext`). It is added AFTER both boundary
|
|
138
|
+
* validators have run and travels as a sibling of the caller's own params in the proxied body, so
|
|
139
|
+
* a downstream service that validates its body sees it. This is the key whose absence from this
|
|
140
|
+
* list took DEV login down.
|
|
141
|
+
*/
|
|
142
|
+
const MESH_CONTEXT_KEYS = ['_descix'];
|
|
143
|
+
|
|
144
|
+
export const PLATFORM_INJECTED_PARAMS = Object.freeze([
|
|
145
|
+
...ENVELOPE_KEYS,
|
|
146
|
+
...IDENTITY_KEYS,
|
|
147
|
+
...REQUEST_CONTEXT_KEYS,
|
|
148
|
+
...DISCORD_ADAPTER_KEYS,
|
|
149
|
+
...MESH_CONTEXT_KEYS,
|
|
150
|
+
]);
|
|
151
|
+
|
|
152
|
+
/** Membership set, derived once from the list. Nothing else may build a second one. */
|
|
153
|
+
const PLATFORM_INJECTED_PARAM_SET = new Set(PLATFORM_INJECTED_PARAMS);
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* THE membership contract. Consumers ask this instead of constructing their own Set from the
|
|
157
|
+
* array — a hand-built Set beside the list is the same mirror this module exists to remove.
|
|
158
|
+
* @param {string} key
|
|
159
|
+
* @returns {boolean}
|
|
160
|
+
*/
|
|
161
|
+
export function isPlatformInjectedParam(key) {
|
|
162
|
+
return PLATFORM_INJECTED_PARAM_SET.has(key);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* THE TWO VIEWS OF THE OWNER, and the PHASE that selects one (CEO ruling 2026-08-26, option B).
|
|
167
|
+
*
|
|
168
|
+
* ONE SOURCE (the list above), TWO DERIVED VIEWS. The list answers "did the PLATFORM write this
|
|
169
|
+
* key?". That is a DIFFERENT question from "may this caller send this key HERE?", and the answer
|
|
170
|
+
* to the second depends entirely on where the validator is standing relative to the injector:
|
|
171
|
+
*
|
|
172
|
+
* 'pre-injection' — the bag is CALLER-AUTHORED and nothing has been written into it yet, so
|
|
173
|
+
* NOTHING is waved. Every key the published schema does not declare is
|
|
174
|
+
* refused BY NAME, the owner's own keys INCLUDED. The strict view.
|
|
175
|
+
* 'post-injection' — the bag has already passed the injector, so the owner's keys are the
|
|
176
|
+
* PLATFORM's own writes and are waved; everything else is still refused by
|
|
177
|
+
* name.
|
|
178
|
+
*
|
|
179
|
+
* WHY THE PHASE IS PART OF THE CALL AND IS NEVER INFERRED (measured 2026-08-26). BOTH MCP doors
|
|
180
|
+
* validate BEFORE injection — apiFront.js tools/call against the caller's `arguments`, and
|
|
181
|
+
* serviceCommands.js `execute_remote_command` against the caller's inner bag. Waving the owner's
|
|
182
|
+
* keys THERE let a caller-authored `_descix: { user: { id: 'VICTIM' } }` ride a schema that
|
|
183
|
+
* declares no such property straight through the boundary, and `_descix.user` is read AS IDENTITY
|
|
184
|
+
* downstream (leaseAuthority.js `params?.user || params?._descix?.user`). One view cannot be
|
|
185
|
+
* correct at both places, and a validator that GUESSES which side of the injector it is on guesses
|
|
186
|
+
* wrong exactly where guessing is most expensive.
|
|
187
|
+
*
|
|
188
|
+
* SO: OMITTED MEANS STRICT — a forgotten phase over-refuses (loudly, at the call site's own door)
|
|
189
|
+
* and can never under-refuse — and an UNKNOWN phase word is REFUSED BY NAME rather than quietly
|
|
190
|
+
* resolved to either view. There is no third view and no per-command exception list; a surface
|
|
191
|
+
* that needs a key waved DECLARES it in its schema.
|
|
192
|
+
*/
|
|
193
|
+
export const VALIDATION_PHASE = Object.freeze({
|
|
194
|
+
PRE_INJECTION: 'pre-injection',
|
|
195
|
+
POST_INJECTION: 'post-injection',
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* phase word -> the predicate that decides whether a key is WAVED past the unknown-parameter gate.
|
|
200
|
+
* THE one owner of that mapping; nobody builds a second waiver.
|
|
201
|
+
*
|
|
202
|
+
* A Map, not an object literal: `PHASE_WAIVERS['constructor']` on a plain object returns a truthy
|
|
203
|
+
* INHERITED function, which would make a prototype key name a "valid" phase and silently wave the
|
|
204
|
+
* whole owner through — a gate that cannot fail on the one input class designed to attack it.
|
|
205
|
+
*/
|
|
206
|
+
const PHASE_WAIVERS = new Map([
|
|
207
|
+
[VALIDATION_PHASE.PRE_INJECTION, () => false],
|
|
208
|
+
[VALIDATION_PHASE.POST_INJECTION, isPlatformInjectedParam],
|
|
209
|
+
]);
|
|
210
|
+
|
|
211
|
+
/** The phase words this validator accepts. Derived from the table; never hand-listed. */
|
|
212
|
+
export const VALIDATION_PHASES = Object.freeze([...PHASE_WAIVERS.keys()]);
|
|
213
|
+
|
|
214
|
+
/** The view a call gets when it names no phase. Strict, on purpose. */
|
|
215
|
+
export const DEFAULT_VALIDATION_PHASE = VALIDATION_PHASE.PRE_INJECTION;
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Refuse a call site that STATES NO PHASE, by name.
|
|
219
|
+
*
|
|
220
|
+
* Distinct from `paramWaiverForPhase`, which defaults an omitted phase to the strict view. That
|
|
221
|
+
* default is right for a PUBLISHED library entry point (a third-party consumer that forgets the
|
|
222
|
+
* argument over-refuses rather than under-refuses). It is wrong for an INTERNAL choke point with a
|
|
223
|
+
* known, small set of callers — there an unstated phase means a door was added without anybody
|
|
224
|
+
* measuring which side of the injector it stands on, and inheriting "strict" would hide that.
|
|
225
|
+
*
|
|
226
|
+
* Owned here rather than written at each choke point: two copies of this refusal is the same
|
|
227
|
+
* mirror-drift the phase contract exists to remove, one layer up.
|
|
228
|
+
*
|
|
229
|
+
* @param {string|undefined} phase
|
|
230
|
+
* @param {object} [opts] { commandName, surface, guidance }
|
|
231
|
+
* @throws {Error} `code:'INVALID_VALIDATION_PHASE'` (statusCode 500) when `phase` is undefined
|
|
232
|
+
*/
|
|
233
|
+
export function requireValidationPhase(phase, opts = {}) {
|
|
234
|
+
if (phase !== undefined) return;
|
|
235
|
+
const { commandName = 'command', surface = null, guidance = '' } = opts;
|
|
236
|
+
const err = new Error(
|
|
237
|
+
`${commandName}: called${surface ? ` from '${surface}'` : ''} without a validation phase. `
|
|
238
|
+
+ `Pass one of: ${VALIDATION_PHASES.join(', ')}. A door holding a CALLER-AUTHORED bag is `
|
|
239
|
+
+ `'${VALIDATION_PHASE.PRE_INJECTION}' (nothing waved; platform keys refused by name); a door `
|
|
240
|
+
+ `downstream of the platform's parameter injector is '${VALIDATION_PHASE.POST_INJECTION}'. `
|
|
241
|
+
+ `Refusing rather than guessing — the phase decides whether a caller-authored '_descix' is `
|
|
242
|
+
+ `waved past this command's published contract.${guidance ? ' ' + guidance : ''}`
|
|
243
|
+
);
|
|
244
|
+
err.code = 'INVALID_VALIDATION_PHASE';
|
|
245
|
+
err.statusCode = 500;
|
|
246
|
+
err.data = { command: commandName, phase, accepted_phases: [...VALIDATION_PHASES], ...(surface ? { surface } : {}) };
|
|
247
|
+
throw err;
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Resolve a phase word to its waiver predicate. Consumers that do their own unknown-key loop
|
|
252
|
+
* (DeSciX_Cloud `assertKnownParams`) ask HERE rather than branching on the phase themselves —
|
|
253
|
+
* a hand-written `phase === 'post-injection' ? isPlatformInjectedParam : ...` at a consumer is the
|
|
254
|
+
* second derivation this whole module exists to prevent.
|
|
255
|
+
*
|
|
256
|
+
* @param {string} [phase] one of VALIDATION_PHASES; `undefined` => DEFAULT_VALIDATION_PHASE
|
|
257
|
+
* @param {object} [opts] { commandName, surface } for the refusal message
|
|
258
|
+
* @returns {(key:string)=>boolean} true when the key is waved past the unknown-parameter gate
|
|
259
|
+
* @throws {Error} `code:'INVALID_VALIDATION_PHASE'` (statusCode 500) on any other value
|
|
260
|
+
*/
|
|
261
|
+
export function paramWaiverForPhase(phase, opts = {}) {
|
|
262
|
+
const resolved = phase === undefined ? DEFAULT_VALIDATION_PHASE : phase;
|
|
263
|
+
const waiver = PHASE_WAIVERS.get(resolved);
|
|
264
|
+
if (!waiver) {
|
|
265
|
+
const { commandName = 'command', surface = 'MCP' } = opts;
|
|
266
|
+
const err = new Error(
|
|
267
|
+
`${commandName}: unknown validation phase ${JSON.stringify(phase)} at the ${surface} boundary. `
|
|
268
|
+
+ `Accepted phases: ${VALIDATION_PHASES.join(', ')}. Omit the phase to get the STRICT `
|
|
269
|
+
+ `('${DEFAULT_VALIDATION_PHASE}') view. This is a WIRING defect at the CALL SITE, not a caller `
|
|
270
|
+
+ `error: the phase states which side of the platform's parameter injector this validator is `
|
|
271
|
+
+ `standing on, and guessing it is how a caller-authored '_descix' reaches an identity read.`
|
|
272
|
+
);
|
|
273
|
+
err.code = 'INVALID_VALIDATION_PHASE';
|
|
274
|
+
err.statusCode = 500;
|
|
275
|
+
err.data = { command: commandName, phase, accepted_phases: [...VALIDATION_PHASES], surface };
|
|
276
|
+
throw err;
|
|
277
|
+
}
|
|
278
|
+
return waiver;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* JSON-Schema `type` word -> the predicate that decides whether a runtime value IS that type.
|
|
283
|
+
* THE ONE OWNER of "what does this type word mean" for the whole platform boundary: the validator,
|
|
284
|
+
* the error message and the conformance test all read this table, so no surface can re-derive a
|
|
285
|
+
* second, differently-worded answer.
|
|
286
|
+
*
|
|
287
|
+
* `integer` is a distinct word from `number` in JSON Schema and is enforced as such — a manifest
|
|
288
|
+
* that declares `integer` and receives 1.5 has been lied to.
|
|
289
|
+
*/
|
|
290
|
+
export const SCHEMA_TYPE_PREDICATES = Object.freeze({
|
|
291
|
+
string: v => typeof v === 'string',
|
|
292
|
+
number: v => typeof v === 'number' && Number.isFinite(v),
|
|
293
|
+
integer: v => typeof v === 'number' && Number.isInteger(v),
|
|
294
|
+
boolean: v => typeof v === 'boolean',
|
|
295
|
+
array: v => Array.isArray(v),
|
|
296
|
+
object: v => v !== null && typeof v === 'object' && !Array.isArray(v),
|
|
297
|
+
null: v => v === null,
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
/** The declared type words this validator can enforce. Derived from the table; never hand-listed. */
|
|
301
|
+
export const SUPPORTED_SCHEMA_TYPES = Object.freeze(Object.keys(SCHEMA_TYPE_PREDICATES));
|
|
302
|
+
|
|
303
|
+
/**
|
|
304
|
+
* "Absent" has ONE definition on this boundary, shared by the required-parameter check and the
|
|
305
|
+
* type check. `null` counts as absent because that is the definition the required check has always
|
|
306
|
+
* used, and two definitions of absence in one function is the mirror-drift bug in miniature.
|
|
307
|
+
*/
|
|
308
|
+
function isAbsent(value) {
|
|
309
|
+
return value === undefined || value === null;
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/** The runtime type word for a value, in the SAME vocabulary the schema uses. */
|
|
313
|
+
export function runtimeTypeOf(value) {
|
|
314
|
+
if (value === null) return 'null';
|
|
315
|
+
if (Array.isArray(value)) return 'array';
|
|
316
|
+
const t = typeof value;
|
|
317
|
+
return t === 'number' && !Number.isFinite(value) ? 'number (non-finite)' : t;
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* Normalise a property's declared `type` to the list of accepted type words.
|
|
322
|
+
* JSON Schema allows a single word or a union array; both are answered here so no caller branches.
|
|
323
|
+
* @returns {string[]} [] when the property declares no type (=> nothing to enforce).
|
|
324
|
+
*/
|
|
325
|
+
export function declaredTypesOf(propertySchema) {
|
|
326
|
+
const declared = propertySchema && typeof propertySchema === 'object' ? propertySchema.type : undefined;
|
|
327
|
+
if (typeof declared === 'string') return [declared];
|
|
328
|
+
if (Array.isArray(declared)) return declared.filter(t => typeof t === 'string');
|
|
329
|
+
return [];
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Does a value satisfy a property's declared `type`?
|
|
334
|
+
* A type word this validator does not know is NOT enforced — we make no claim we cannot justify.
|
|
335
|
+
* An unknown word is a SCHEMA-authoring defect, and it is caught by the schema conformance test
|
|
336
|
+
* (which asserts every declared type is in SUPPORTED_SCHEMA_TYPES) rather than by refusing a live
|
|
337
|
+
* call, so a typo in a manifest surfaces in CI instead of as a runtime outage.
|
|
338
|
+
*/
|
|
339
|
+
export function valueMatchesDeclaredType(value, propertySchema) {
|
|
340
|
+
const types = declaredTypesOf(propertySchema);
|
|
341
|
+
if (types.length === 0) return true;
|
|
342
|
+
const enforceable = types.filter(t => t in SCHEMA_TYPE_PREDICATES);
|
|
343
|
+
if (enforceable.length === 0) return true;
|
|
344
|
+
return enforceable.some(t => SCHEMA_TYPE_PREDICATES[t](value));
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
/**
|
|
348
|
+
* A NON-REVEALING description of what arrived: its SHAPE, never its contents.
|
|
349
|
+
*
|
|
350
|
+
* The refusal must say what was received without becoming an exfiltration path. Declared-string
|
|
351
|
+
* parameters are exactly the ones that carry secrets — `seat_token`, `signature`,
|
|
352
|
+
* `walletSignature`, `invite_token` are all `type:'string'` in the registered manifests — and a
|
|
353
|
+
* validation error is a string that gets logged, relayed and pasted into agent context. Echoing a
|
|
354
|
+
* rejected value would put those bytes on that path for free.
|
|
355
|
+
*
|
|
356
|
+
* Nothing diagnostic is lost: "declared 'number' but received string (length 1)" already tells the
|
|
357
|
+
* caller they sent "3" instead of 3, which is the whole confusion this error exists to resolve.
|
|
358
|
+
*/
|
|
359
|
+
function describeShape(value) {
|
|
360
|
+
if (typeof value === 'string') return `length ${value.length}`;
|
|
361
|
+
if (Array.isArray(value)) return `${value.length} element${value.length === 1 ? '' : 's'}`;
|
|
362
|
+
if (typeof value === 'number' || typeof value === 'boolean') return String(value);
|
|
363
|
+
if (value !== null && typeof value === 'object') {
|
|
364
|
+
const keys = Object.keys(value);
|
|
365
|
+
return `${keys.length} key${keys.length === 1 ? '' : 's'}`;
|
|
366
|
+
}
|
|
367
|
+
return String(value);
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** Levenshtein distance — small inputs (parameter names), so the simple DP is fine. */
|
|
371
|
+
function editDistance(a, b) {
|
|
372
|
+
const m = a.length;
|
|
373
|
+
const n = b.length;
|
|
374
|
+
if (!m) return n;
|
|
375
|
+
if (!n) return m;
|
|
376
|
+
let prev = Array.from({ length: n + 1 }, (_, j) => j);
|
|
377
|
+
const curr = new Array(n + 1);
|
|
378
|
+
for (let i = 1; i <= m; i++) {
|
|
379
|
+
curr[0] = i;
|
|
380
|
+
for (let j = 1; j <= n; j++) {
|
|
381
|
+
const cost = a[i - 1] === b[j - 1] ? 0 : 1;
|
|
382
|
+
curr[j] = Math.min(curr[j - 1] + 1, prev[j] + 1, prev[j - 1] + cost);
|
|
383
|
+
}
|
|
384
|
+
prev = curr.slice();
|
|
385
|
+
}
|
|
386
|
+
return prev[n];
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/**
|
|
390
|
+
* Best canonical parameter for an unknown key: curated alias first (the confusions edit
|
|
391
|
+
* distance cannot see), then nearest neighbour within a conservative distance.
|
|
392
|
+
* @returns {string|null} the suggestion, or null when nothing is close enough to claim.
|
|
393
|
+
*/
|
|
394
|
+
export function suggestParam(unknownKey, validNames) {
|
|
395
|
+
if (!unknownKey || !Array.isArray(validNames) || validNames.length === 0) return null;
|
|
396
|
+
const valid = new Set(validNames);
|
|
397
|
+
|
|
398
|
+
for (const candidate of PARAM_ALIASES[unknownKey] || []) {
|
|
399
|
+
if (valid.has(candidate)) return candidate;
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
const lowerKey = String(unknownKey).toLowerCase();
|
|
403
|
+
for (const name of validNames) {
|
|
404
|
+
if (name.toLowerCase() === lowerKey) return name; // pure case mismatch
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
let best = null;
|
|
408
|
+
let bestDist = Infinity;
|
|
409
|
+
for (const name of validNames) {
|
|
410
|
+
const d = editDistance(lowerKey, name.toLowerCase());
|
|
411
|
+
if (d < bestDist) { bestDist = d; best = name; }
|
|
412
|
+
}
|
|
413
|
+
// Only claim a typo when the edit is small relative to the name — otherwise stay silent
|
|
414
|
+
// rather than send the caller somewhere unrelated.
|
|
415
|
+
const threshold = Math.max(2, Math.floor(Math.max(lowerKey.length, best ? best.length : 0) / 3));
|
|
416
|
+
return bestDist <= threshold ? best : null;
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Validate a caller-supplied params bag against a plain JSON-Schema `inputSchema`.
|
|
421
|
+
*
|
|
422
|
+
* FAIL-LOUD, NO COERCION: unknown parameters, missing required parameters and parameters whose
|
|
423
|
+
* value contradicts the DECLARED `type` all THROW, naming the offending key and (for unknowns) the
|
|
424
|
+
* nearest valid one. Nothing is silently dropped, defaulted or coerced — that behaviour is the bug
|
|
425
|
+
* this exists to kill.
|
|
426
|
+
*
|
|
427
|
+
* TYPE IS PART OF THE PUBLISHED CONTRACT. A schema that says `type:'string'` and accepts a number
|
|
428
|
+
* has advertised something untrue; the caller then debugs a downstream symptom (`.trim is not a
|
|
429
|
+
* function`, a Firestore doc keyed by `[object Object]`) instead of reading a refusal that names
|
|
430
|
+
* the parameter. Only the property's own top-level `type` is enforced here — nested `items`/
|
|
431
|
+
* sub-schemas are NOT, so this never silently claims more validation than it performs.
|
|
432
|
+
*
|
|
433
|
+
* NO-SCHEMA => NO CLAIM: when the command has no declared `properties`, we cannot know what is
|
|
434
|
+
* valid, so we validate nothing rather than fabricate a contract (a hardcoded guess here would
|
|
435
|
+
* be the same anti-pattern in a new place). Commands are onboarded by DECLARING a schema.
|
|
436
|
+
*
|
|
437
|
+
* PHASE IS PART OF THE CALL. `opts.phase` names which side of the platform's parameter injector
|
|
438
|
+
* this door stands on; see VALIDATION_PHASE above. It is resolved BEFORE the no-schema early
|
|
439
|
+
* return, so a mis-wired phase is refused on every command rather than only on the ones that
|
|
440
|
+
* happen to publish a schema — a gate that can be skipped by the shape of its input is not a gate.
|
|
441
|
+
*
|
|
442
|
+
* @param {object} schema plain JSON-Schema object ({ properties, required })
|
|
443
|
+
* @param {object} params the caller-supplied arguments
|
|
444
|
+
* @param {object} [opts]
|
|
445
|
+
* @param {string} [opts.commandName] name used in the error message
|
|
446
|
+
* @param {string} [opts.surface] e.g. 'MCP tools/call' — where the rejection happened
|
|
447
|
+
* @param {string} [opts.phase] VALIDATION_PHASE value; omitted => strict (pre-injection)
|
|
448
|
+
* @throws {Error} `code='INVALID_PARAMS'` on any violation; `code='INVALID_VALIDATION_PHASE'`
|
|
449
|
+
* when `opts.phase` is not a known phase word
|
|
450
|
+
*/
|
|
451
|
+
export function validateParamsAgainstSchema(schema, params, opts = {}) {
|
|
452
|
+
const { commandName = 'command', surface = 'MCP', phase } = opts;
|
|
453
|
+
// FIRST, and deliberately ahead of the no-schema early return: an unknown phase is a wiring
|
|
454
|
+
// defect and must not be reachable-but-silent on the commands that declare no schema.
|
|
455
|
+
const isWaived = paramWaiverForPhase(phase, { commandName, surface });
|
|
456
|
+
|
|
457
|
+
const properties = schema && typeof schema === 'object' ? schema.properties : null;
|
|
458
|
+
if (!properties || typeof properties !== 'object') return; // undeclared => nothing to check
|
|
459
|
+
|
|
460
|
+
const validNames = Object.keys(properties);
|
|
461
|
+
const supplied = params && typeof params === 'object' ? params : {};
|
|
462
|
+
const unknown = Object.keys(supplied).filter(k => !(k in properties) && !isWaived(k));
|
|
463
|
+
if (unknown.length > 0) {
|
|
464
|
+
// A refused key that the PLATFORM injects is a different mistake from a typo, and saying so
|
|
465
|
+
// is the difference between a caller hunting their own spelling and a caller learning they
|
|
466
|
+
// may not author that key AT ALL. Said ONCE, as a trailing clause naming the offenders:
|
|
467
|
+
// repeating it per key turns an 18-key refusal into a wall nobody reads. The annotation
|
|
468
|
+
// consumes the same membership predicate — it is not a second list.
|
|
469
|
+
const injectedOffenders = unknown.filter(isPlatformInjectedParam);
|
|
470
|
+
const details = unknown.map(k => {
|
|
471
|
+
if (isPlatformInjectedParam(k)) return `'${k}'`;
|
|
472
|
+
const hint = suggestParam(k, validNames);
|
|
473
|
+
return hint ? `'${k}' (did you mean '${hint}'?)` : `'${k}'`;
|
|
474
|
+
});
|
|
475
|
+
const injectedNote = injectedOffenders.length
|
|
476
|
+
? ` ${injectedOffenders.map(k => `'${k}'`).join(', ')} ${injectedOffenders.length > 1 ? 'are' : 'is'} `
|
|
477
|
+
+ `PLATFORM-INJECTED: the platform writes ${injectedOffenders.length > 1 ? 'them' : 'it'} itself, `
|
|
478
|
+
+ `DOWNSTREAM of this boundary — a caller may not supply ${injectedOffenders.length > 1 ? 'them' : 'it'}.`
|
|
479
|
+
: '';
|
|
480
|
+
const err = new Error(
|
|
481
|
+
`${commandName}: unknown parameter${unknown.length > 1 ? 's' : ''} ${details.join(', ')}. ` +
|
|
482
|
+
`Accepted parameters: ${validNames.join(', ')}. ` +
|
|
483
|
+
`Rejected at the ${surface} boundary — the parameter was NOT applied, and no default was substituted.` +
|
|
484
|
+
injectedNote
|
|
485
|
+
);
|
|
486
|
+
err.code = 'INVALID_PARAMS';
|
|
487
|
+
err.data = {
|
|
488
|
+
command: commandName,
|
|
489
|
+
unknown_parameters: unknown,
|
|
490
|
+
accepted_parameters: validNames,
|
|
491
|
+
validation_phase: phase === undefined ? DEFAULT_VALIDATION_PHASE : phase,
|
|
492
|
+
...(injectedOffenders.length ? { platform_injected_parameters: injectedOffenders } : {}),
|
|
493
|
+
};
|
|
494
|
+
throw err;
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const required = Array.isArray(schema.required) ? schema.required : [];
|
|
498
|
+
const missing = required.filter(k => isAbsent(supplied[k]));
|
|
499
|
+
if (missing.length > 0) {
|
|
500
|
+
const err = new Error(
|
|
501
|
+
`${commandName}: missing required parameter${missing.length > 1 ? 's' : ''} ` +
|
|
502
|
+
`${missing.map(k => `'${k}'`).join(', ')}. ` +
|
|
503
|
+
`Accepted parameters: ${validNames.join(', ')}.`
|
|
504
|
+
);
|
|
505
|
+
err.code = 'INVALID_PARAMS';
|
|
506
|
+
err.data = { command: commandName, missing_parameters: missing, accepted_parameters: validNames };
|
|
507
|
+
throw err;
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// THIRD GATE: the value must BE what the schema said it would be. Runs after the required
|
|
511
|
+
// check so a required parameter that is absent is reported as missing, not as a type error.
|
|
512
|
+
const mistyped = [];
|
|
513
|
+
for (const name of validNames) {
|
|
514
|
+
const value = supplied[name];
|
|
515
|
+
if (isAbsent(value)) continue; // absence is the required check's business, not ours
|
|
516
|
+
if (valueMatchesDeclaredType(value, properties[name])) continue;
|
|
517
|
+
mistyped.push({
|
|
518
|
+
parameter: name,
|
|
519
|
+
declared_type: declaredTypesOf(properties[name]).join(' | '),
|
|
520
|
+
received_type: runtimeTypeOf(value),
|
|
521
|
+
received_shape: describeShape(value),
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
if (mistyped.length > 0) {
|
|
525
|
+
const details = mistyped.map(m =>
|
|
526
|
+
`'${m.parameter}' is declared type '${m.declared_type}' but received ${m.received_type} (${m.received_shape})`
|
|
527
|
+
);
|
|
528
|
+
const err = new Error(
|
|
529
|
+
`${commandName}: wrong parameter type${mistyped.length > 1 ? 's' : ''} — ${details.join('; ')}. ` +
|
|
530
|
+
`Rejected at the ${surface} boundary — the value was NOT coerced and the command did NOT run. ` +
|
|
531
|
+
`Send each parameter as its declared type.`
|
|
532
|
+
);
|
|
533
|
+
err.code = 'INVALID_PARAMS';
|
|
534
|
+
err.data = { command: commandName, mistyped_parameters: mistyped, accepted_parameters: validNames };
|
|
535
|
+
throw err;
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Does `toolName` declare `paramName` in its schema? Used by the CLI stdio server so workspace
|
|
541
|
+
* context (app_id / community_id) is only auto-filled into tools that actually ACCEPT it —
|
|
542
|
+
* blind injection is what made the stdio path manufacture params the target tool never took.
|
|
543
|
+
*/
|
|
544
|
+
export function toolAcceptsParam(tools, toolName, paramName) {
|
|
545
|
+
const tool = Array.isArray(tools) ? tools.find(t => t && t.name === toolName) : null;
|
|
546
|
+
const properties = tool && tool.inputSchema ? tool.inputSchema.properties : null;
|
|
547
|
+
return !!(properties && Object.prototype.hasOwnProperty.call(properties, paramName));
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* Convenience: validate against a tool definition list (name -> inputSchema).
|
|
552
|
+
* `opts.phase` is ferried to the validator unchanged, and is resolved even when the tool is
|
|
553
|
+
* unknown so a mis-wired phase cannot hide behind a typo'd tool name.
|
|
554
|
+
*/
|
|
555
|
+
export function validateToolParams(tools, toolName, params, opts = {}) {
|
|
556
|
+
const tool = Array.isArray(tools) ? tools.find(t => t && t.name === toolName) : null;
|
|
557
|
+
if (!tool || !tool.inputSchema) {
|
|
558
|
+
paramWaiverForPhase(opts.phase, { commandName: toolName, surface: opts.surface });
|
|
559
|
+
return; // unknown tool is the dispatcher's error, not ours
|
|
560
|
+
}
|
|
561
|
+
validateParamsAgainstSchema(tool.inputSchema, params, { commandName: toolName, ...opts });
|
|
562
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The record-filter OPERATOR VOCABULARY — the ONE owner of which operators a structured record
|
|
3
|
+
* query accepts, and of what each operator expects the STORED value to be.
|
|
4
|
+
*
|
|
5
|
+
* WHY IT LIVES HERE AND NOT IN THE STORE (measured 2026-08-24, seat DEVPLANE, RESIDUAL 16):
|
|
6
|
+
* `app_records_query` filtered with `{"tags":"handoff"}` against records whose `tags` is an
|
|
7
|
+
* ARRAY answered `matched:0` and `success:true` — a silent empty success over records that
|
|
8
|
+
* plainly carried the tag. Two facts had to change together to fix that: the evaluator had to
|
|
9
|
+
* learn an array operator, and the advertised tool description had to say so. The description
|
|
10
|
+
* is published from `nativeTools.js` (this package) and the evaluator lives in the Cloud
|
|
11
|
+
* microservice, so a list kept in either one is a hand mirror of the other — the drift bug
|
|
12
|
+
* class. Both now import THIS module; neither re-lists an operator.
|
|
13
|
+
*
|
|
14
|
+
* Dependency-free leaf: the CLI stdio server imports the mcp-tools barrel without GCP infra.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Operators that compare against a SCALAR stored value (string / number / boolean / null).
|
|
19
|
+
* Against an ARRAY-valued field these can never match — Firestore `==` on an array field wants
|
|
20
|
+
* the WHOLE array, and the in-memory residual compares by identity — so the store REFUSES them
|
|
21
|
+
* there rather than counting the record as a miss.
|
|
22
|
+
*/
|
|
23
|
+
export const SCALAR_FILTER_OPERATORS = Object.freeze(['$eq', '$ne', '$in']);
|
|
24
|
+
|
|
25
|
+
/** Operators that test MEMBERSHIP in an ARRAY-valued field (Firestore `array-contains`). */
|
|
26
|
+
export const ARRAY_FILTER_OPERATORS = Object.freeze(['$contains']);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The COMPLETE accepted set. A bare (non-object) condition value is sugar for `$eq` and is
|
|
30
|
+
* therefore governed by the SCALAR rules above.
|
|
31
|
+
*
|
|
32
|
+
* Deliberately NOT the same list as any store's pushdown set: what a query engine can push
|
|
33
|
+
* DOWN to the database is an optimization subset, and "supported" vs "pushed down" are two
|
|
34
|
+
* different facts, not one duplicated fact.
|
|
35
|
+
*/
|
|
36
|
+
export const SUPPORTED_FILTER_OPERATORS = Object.freeze([
|
|
37
|
+
...SCALAR_FILTER_OPERATORS,
|
|
38
|
+
...ARRAY_FILTER_OPERATORS,
|
|
39
|
+
]);
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Which shape of STORED value an operator can evaluate.
|
|
43
|
+
*
|
|
44
|
+
* @param {string} operator - e.g. '$eq', '$contains'
|
|
45
|
+
* @returns {'scalar'|'array'|null} null when the operator is not supported at all
|
|
46
|
+
*/
|
|
47
|
+
export function operatorValueKind(operator) {
|
|
48
|
+
if (SCALAR_FILTER_OPERATORS.includes(operator)) return 'scalar';
|
|
49
|
+
if (ARRAY_FILTER_OPERATORS.includes(operator)) return 'array';
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* The operator a caller should have reached for, given what the field ACTUALLY holds. This is
|
|
55
|
+
* what makes a type refusal actionable instead of merely loud — the message names the remedy.
|
|
56
|
+
*
|
|
57
|
+
* @param {'scalar'|'array'} valueKind - the stored value's shape
|
|
58
|
+
* @returns {string} the canonical operator for that shape
|
|
59
|
+
*/
|
|
60
|
+
export function remedyOperatorFor(valueKind) {
|
|
61
|
+
if (valueKind === 'array') return ARRAY_FILTER_OPERATORS[0];
|
|
62
|
+
if (valueKind === 'scalar') return SCALAR_FILTER_OPERATORS[0];
|
|
63
|
+
throw new Error(`remedyOperatorFor: unknown value kind '${valueKind}' (expected 'scalar' or 'array')`);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* The operator clause for a tool description, GENERATED from the lists above.
|
|
68
|
+
*
|
|
69
|
+
* Every advertised description composes this rather than typing operator names, so an operator
|
|
70
|
+
* added to (or removed from) the vocabulary cannot leave the published contract behind. The
|
|
71
|
+
* conformance test `records-query-counts-contract.test.js` drives its assertions off the same
|
|
72
|
+
* exported lists, which is what makes a hand-typed operator name a CI failure.
|
|
73
|
+
*
|
|
74
|
+
* @returns {string}
|
|
75
|
+
*/
|
|
76
|
+
export function filterOperatorClause() {
|
|
77
|
+
const scalar = SCALAR_FILTER_OPERATORS.join('/');
|
|
78
|
+
const array = ARRAY_FILTER_OPERATORS.join('/');
|
|
79
|
+
return (
|
|
80
|
+
`Supports ${scalar} on SCALAR fields (a bare value means ${SCALAR_FILTER_OPERATORS[0]}) ` +
|
|
81
|
+
`and ${array} on ARRAY fields (membership, e.g. { "tags": { "${ARRAY_FILTER_OPERATORS[0]}": "handoff" } }) ` +
|
|
82
|
+
`+ field projection. OPERATOR AND VALUE TYPE MUST AGREE: a scalar comparison against a ` +
|
|
83
|
+
`field that holds an ARRAY, or ${array} against a field that holds a SCALAR, is REFUSED ` +
|
|
84
|
+
`with FILTER_UNSUPPORTED naming the field and the operator to use instead — it is never ` +
|
|
85
|
+
`answered as a zero-match success, because a predicate that CANNOT match must not be ` +
|
|
86
|
+
`reported as one that simply did not.`
|
|
87
|
+
);
|
|
88
|
+
}
|