import { CapabilityActor, CapabilityPolicy } from '@domain/services/capability-access'; /** * Sous-ensemble de JSON Schema utilise par les capacites. * * Le schema est ecrit une seule fois : il sert a la fois de contrat annonce aux * clients MCP (`inputSchema`) et de regle de validation a l'entree. Deux * sources auraient fini par diverger, et c'est la validation qui aurait perdu. */ export interface SchemaProperty { type: 'string' | 'number' | 'integer' | 'boolean' | 'array'; description: string; enum?: readonly string[]; minimum?: number; maximum?: number; minLength?: number; maxLength?: number; /** Pour `type: 'array'` uniquement. */ items?: { type: 'string' | 'number' }; default?: unknown; } export interface CapabilitySchema { type: 'object'; properties: Record; required?: readonly string[]; additionalProperties: false; } export interface Capability { policy: CapabilityPolicy; /** Une phrase : ce que fait l'action, du point de vue de l'utilisateur. */ description: string; inputSchema: CapabilitySchema; handler: (input: Record, actor: CapabilityActor) => Promise; } /** Schema sans aucun parametre, pour les capacites qui n'en prennent pas. */ export const NO_INPUT: CapabilitySchema = { type: 'object', properties: {}, additionalProperties: false, }; export class CapabilityInputError extends Error {} /** * Valide et normalise une entree contre son schema. * * Les entrees viennent d'un modele de langage : elles sont plausibles, pas * fiables. Un nombre arrive en chaine, un champ facultatif arrive a `null`, un * champ invente arrive en plus. La validation est donc stricte sur ce qui * compte (types, valeurs autorisees, bornes) et refuse ce qu'elle ne connait * pas, plutot que de le transmettre au service. */ export function parseInput( schema: CapabilitySchema, raw: Record | undefined ): Record { const input = raw ?? {}; const parsed: Record = {}; for (const key of Object.keys(input)) { if (!(key in schema.properties)) { throw new CapabilityInputError(`Unknown parameter "${key}".`); } } for (const [key, property] of Object.entries(schema.properties)) { const required = schema.required?.includes(key) ?? false; const value = input[key]; if (value === undefined || value === null || value === '') { if (required) throw new CapabilityInputError(`Missing required parameter "${key}".`); if (property.default !== undefined) parsed[key] = property.default; continue; } parsed[key] = coerce(key, property, value); } return parsed; } function coerce(key: string, property: SchemaProperty, value: unknown): unknown { switch (property.type) { case 'string': { if (typeof value !== 'string') { throw new CapabilityInputError(`Parameter "${key}" must be a string.`); } const text = value.trim(); if (property.enum && !property.enum.includes(text)) { throw new CapabilityInputError( `Parameter "${key}" must be one of: ${property.enum.join(', ')}.` ); } if (property.minLength !== undefined && text.length < property.minLength) { throw new CapabilityInputError( `Parameter "${key}" must be at least ${property.minLength} characters.` ); } if (property.maxLength !== undefined && text.length > property.maxLength) { throw new CapabilityInputError( `Parameter "${key}" must be at most ${property.maxLength} characters.` ); } return text; } case 'number': case 'integer': { // Un modele ecrit volontiers « 12.5 » plutot que 12.5 : la chaine // numerique est acceptee, le texte non numerique refuse. const numeric = typeof value === 'number' ? value : Number(String(value).trim()); if (!Number.isFinite(numeric)) { throw new CapabilityInputError(`Parameter "${key}" must be a number.`); } if (property.type === 'integer' && !Number.isInteger(numeric)) { throw new CapabilityInputError(`Parameter "${key}" must be a whole number.`); } if (property.minimum !== undefined && numeric < property.minimum) { throw new CapabilityInputError(`Parameter "${key}" must be >= ${property.minimum}.`); } if (property.maximum !== undefined && numeric > property.maximum) { throw new CapabilityInputError(`Parameter "${key}" must be <= ${property.maximum}.`); } return numeric; } case 'boolean': { if (typeof value === 'boolean') return value; const text = String(value).trim().toLowerCase(); if (text === 'true') return true; if (text === 'false') return false; throw new CapabilityInputError(`Parameter "${key}" must be true or false.`); } case 'array': { if (!Array.isArray(value)) { throw new CapabilityInputError(`Parameter "${key}" must be an array.`); } const itemType = property.items?.type ?? 'string'; return value.map(item => coerce(`${key}[]`, { type: itemType, description: '' }, item)); } } }