// ABOUTME: Input validation helpers for MCP tool requests.
// ABOUTME: Ensures required fields and coordinate bounds are valid.
export class ValidationError extends Error {
constructor(message: string) {
super(message);
this.name = "ValidationError";
}
}
export type Coordinates = { x: number; y: number };
export function requireString(value: unknown, label: string): string {
if (typeof value !== "string" || value.trim() === "") {
throw new ValidationError(`${label} must be a non-empty string`);
}
return value;
}
export function requireStringOrEnv(
value: unknown,
label: string,
envValue: string | undefined,
envLabel: string
): string {
if (typeof value === "string" && value.trim() !== "") {
return value;
}
if (typeof envValue === "string" && envValue.trim() !== "") {
return envValue;
}
throw new ValidationError(`${label} must be provided or set via ${envLabel}`);
}
export function requireCoordinates(input: unknown): Coordinates {
if (!input || typeof input !== "object") {
throw new ValidationError("x and y are required");
}
const { x, y } = input as { x?: unknown; y?: unknown };
if (!Number.isInteger(x) || !Number.isInteger(y)) {
throw new ValidationError("x and y must be integers");
}
const xValue = x as number;
const yValue = y as number;
if (xValue < 0 || xValue > 8 || yValue < 0 || yValue > 8) {
throw new ValidationError("x and y must be between 0 and 8");
}
return { x: xValue, y: yValue };
}