validate method
raw, checked and narrowed to the declared keys.
An unknown key is refused rather than ignored. A silently dropped argument is the failure this exists to prevent: a caller that misspells an argument gets a refusal naming the word it typed, not a tool that ran against something else.
A null value reads as absence, because a caller assembling a map from
optional fields writes nulls and means "not stated".
Implementation
Map<String, Object?> validate(Map<String, Object?> raw) {
final declared = {for (final a in arguments) a.name: a};
for (final key in raw.keys) {
if (!declared.containsKey(key)) {
throw AgentToolException(
AgentToolErrorCode.invalidArgument,
'Unknown argument "$key". Declared: ${declared.keys.join(', ')}.',
argument: key,
);
}
}
final out = <String, Object?>{};
for (final argument in arguments) {
final value = raw[argument.name];
if (value == null) {
if (argument.required) {
throw AgentToolException(
AgentToolErrorCode.invalidArgument,
'Argument "${argument.name}" is required.',
argument: argument.name,
);
}
continue;
}
if (!argument.type.accepts(value)) {
throw AgentToolException(
AgentToolErrorCode.invalidArgument,
'Argument "${argument.name}" must be a '
'${argument.type.jsonName}, found ${value.runtimeType}.',
argument: argument.name,
);
}
final allowed = argument.allowed;
if (allowed != null && !allowed.contains(value)) {
throw AgentToolException(
AgentToolErrorCode.invalidArgument,
'Argument "${argument.name}" must be one of ${allowed.join(', ')}.',
argument: argument.name,
);
}
out[argument.name] = value;
}
return out;
}