{"record":{"id":"8a08dcca79d0e0c0","repo":"mastra-ai/mastra","slug":"invalid-filter-format-error-instanceof-error","errorCode":null,"errorMessage":"Invalid filter format: ${error instanceof Error ? error.message : String(error)}","messagePattern":"Invalid filter format: (.+?)","errorType":"validation","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/rag/src/utils/tool-helpers.ts","lineNumber":185,"sourceCode":" * @param filter - The filter value to parse (string or object)\n * @param logger - Optional logger for error reporting\n * @returns Parsed filter object\n * @throws Error if filter is a string that cannot be parsed as JSON or if filter is not a plain object\n */\nexport function parseFilterValue(filter: unknown, logger?: Logger | null): Record<string, any> {\n  if (!filter) {\n    return {};\n  }\n\n  let parsedFilter = filter;\n  if (typeof filter === 'string') {\n    try {\n      parsedFilter = JSON.parse(filter);\n    } catch (error) {\n      if (logger) {\n        logger.error('Invalid filter', { filter, error });\n      }\n      throw new Error(`Invalid filter format: ${error instanceof Error ? error.message : String(error)}`);\n    }\n  }\n\n  // Validate that non-string filter is a plain object\n  if (typeof parsedFilter !== 'object' || parsedFilter === null || Array.isArray(parsedFilter)) {\n    const receivedType = Array.isArray(parsedFilter) ? 'array' : typeof parsedFilter;\n    if (logger) {\n      logger.error('Invalid filter', { filter, error: 'Filter must be a plain object' });\n    }\n    throw new Error(`Invalid filter format: expected a plain object, got ${receivedType}`);\n  }\n\n  return parsedFilter as Record<string, any>;\n}\n","sourceCodeStart":167,"sourceCodeEnd":200,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/rag/src/utils/tool-helpers.ts#L167-L200","documentation":"parseFilterValue accepts a filter either as a string (parsed with JSON.parse) or as an object. When a string filter fails JSON.parse, this error is thrown wrapping the JSON parse message. It exists to give RAG tool callers a clear error instead of a raw SyntaxError.","triggerScenarios":"Passing a string to the `filter` option of a vector query tool that is not valid JSON — e.g. `\"category == 'news'\"`, `\"{category: 'news'}\"` (unquoted key), or a truncated JSON string.","commonSituations":"LLM-generated tool call arguments where the model emits a JS-style filter expression instead of JSON; users hand-writing filters in playground/config with single quotes or trailing commas; template strings interpolated with malformed values.","solutions":["Make the string valid JSON: double-quoted keys and string values, e.g. '{\"category\":\"news\"}'.","Better, pass the filter as a plain JavaScript object instead of a string so no parsing occurs.","Validate with JSON.parse in your own code before passing, and surface the parse error to the user.","If an LLM produces the filter, instruct it in the tool description to emit strict JSON filters."],"exampleFix":"// before\nawait tool.execute({ filter: \"{category: 'news'}\" });\n// after\nawait tool.execute({ filter: { category: 'news' } });","handlingStrategy":"validation","validationCode":"function parseFilterInput(raw: string): Record<string, unknown> {\n  let parsed: unknown;\n  try { parsed = JSON.parse(raw); } catch (e) {\n    throw new TypeError(`filter must be strict JSON: ${(e as Error).message}`);\n  }\n  return parsed as Record<string, unknown>;\n}","typeGuard":null,"tryCatchPattern":"try {\n  await tool.execute({ filter: filterString });\n} catch (e) {\n  if ((e as Error).message.startsWith('Invalid filter format')) {\n    // fall back to a default filter or re-prompt for a strict JSON filter\n    return runWithDefaultFilter();\n  }\n  throw e;\n}","preventionTips":["Pass filter objects, not strings, whenever possible.","Document/require strict JSON (double quotes, no trailing commas) in tool descriptions for LLM callers.","Validate filters at config load time with JSON.parse."],"tags":["json","parsing","rag"],"backgroundTag":"invalid-json","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}