All files / src tool-result.ts

100% Statements 22/22
100% Branches 26/26
100% Functions 3/3
100% Lines 22/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71    3x     31x         3x 16x 1x     15x 4x 4x 2x   2x     11x 1x     10x 1x     9x 8x     1x     3x 18x 16x   16x                                   2x                    
import { AnwbApiError } from "./anwb-client.js";
 
export const toTextResult = (
  text: string,
  structuredContent?: Record<string, unknown>,
) => ({
  content: [{ type: "text" as const, text }],
  ...(structuredContent ? { structuredContent } : {}),
});
 
const getRecoverySuggestion = (status: number, message: string, _details: unknown): string | null => {
  if (status === 429) {
    return "Rate limit exceeded. Wait a moment and retry, or reduce the frequency of API calls.";
  }
 
  if (status === 404) {
    const lower = message.toLowerCase();
    if (lower.includes("route") || lower.includes("location")) {
      return "Route or location not found. Verify the coordinates or search query are correct.";
    }
    return "Resource not found. Verify the request parameters are correct.";
  }
 
  if (status === 401 || status === 403) {
    return "Authentication failed. The ANWB API may have changed its access requirements.";
  }
 
  if (status === 400) {
    return "Invalid request. Check that coordinates are valid (latitude,longitude format) and all parameters are in the correct format.";
  }
 
  if (status >= 500) {
    return "ANWB API server error. This is a temporary issue. Wait a moment and retry.";
  }
 
  return null;
};
 
export const toErrorResult = (error: unknown) => {
  if (error instanceof AnwbApiError) {
    const suggestion = getRecoverySuggestion(error.status, error.message, error.details);
 
    return {
      content: [
        {
          type: "text" as const,
          text: [
            `ANWB API error: ${error.message}`,
            `Status: ${error.status}`,
            error.details ? `Details: ${JSON.stringify(error.details, null, 2)}` : "",
            suggestion ? `\nRecovery: ${suggestion}` : "",
          ]
            .filter(Boolean)
            .join("\n"),
        },
      ],
      isError: true,
    };
  }
 
  return {
    content: [
      {
        type: "text" as const,
        text: error instanceof Error ? error.message : String(error),
      },
    ],
    isError: true,
  };
};