@@ -60,15 +60,39 @@ interface McpToolResult {
6060 isError?: boolean;
6161 }
6262
63-function apiError(body: string): string {
64- try {
65- const parsed = JSON.parse(body) as { error?: unknown };
66- if (typeof parsed.error === "string") return parsed.error;
63+function isRecord(value: unknown): value is Record<string, unknown> {
64+ return typeof value === "object" && value !== null && !Array.isArray(value);
65+}
66+
67+function isMcpToolResult(value: unknown): value is McpToolResult {
68+ if (!isRecord(value)) return false;
69+ if (value.content !== undefined) {
70+ if (!Array.isArray(value.content)) return false;
6771 if (
68- isRecord(parsed.error) &&
69- typeof parsed.error.message === "string"
72+ !value.content.every(
73+ (block) =>
74+ isRecord(block) &&
75+ typeof block.type === "string" &&
76+ (block.text === undefined || typeof block.text === "string"),
77+ )
7078 ) {
71- return parsed.error.message;
79+ return false;
80+ }
81+ }
82+ return value.isError === undefined || typeof value.isError === "boolean";
83+}
84+
85+function apiError(body: string): string {
86+ try {
87+ const parsed: unknown = JSON.parse(body);
88+ if (isRecord(parsed)) {
89+ if (typeof parsed.error === "string") return parsed.error;
90+ if (
91+ isRecord(parsed.error) &&
92+ typeof parsed.error.message === "string"
93+ ) {
94+ return parsed.error.message;
95+ }
7296 }
7397 } catch {
7498 // Fall back to the response body below.
@@ -76,10 +100,6 @@ function apiError(body: string): string {
76100 return body.trim() || "Empty response";
77101 }
78102
79-function isRecord(value: unknown): value is Record<string, unknown> {
80- return typeof value === "object" && value !== null && !Array.isArray(value);
81-}
82-
83103 function parseMcpResponse(
84104 body: string,
85105 contentType: string,
@@ -228,10 +248,10 @@ async function searchAnonymously(
228248 initialized.sessionId,
229249 signal,
230250 );
231- if (!isRecord(called.response.result)) {
251+ if (!isMcpToolResult(called.response.result)) {
232252 throw new Error("Exa MCP returned an invalid tool result");
233253 }
234- const result = called.response.result as McpToolResult;
254+ const result = called.response.result;
235255 const text = (result.content ?? [])
236256 .filter(
237257 (block): block is { type: string; text: string } =>