-
Notifications
You must be signed in to change notification settings - Fork 1
Develop #101
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
- Updated node version in convex.json from "24" to "20". - Enhanced api.d.ts by adding internal API reference and improving type imports. - Fixed formatting in storage.ts by adding missing semicolons. - Defined mastraWorkflowSnapshotsTable in schema.ts to ensure proper indexing. - Updated package-lock.json and package.json to bump convex and @types/node versions. - Renamed E2bSandboxTool to E2bSandboxToolComponent for clarity in e2b-sandbox-tool.tsx. - Refactored output handling in web-scraper-tool.tsx to improve data extraction. - Commented out unused ConvertDataFormatUITool type in types.ts for clarity.
- Updated the "ai" package version from ^5.0.121 to ^6.0.37 in package.json. - Added "mathjs" package with version ^15.1.0 to package.json. - Imported "convexMemory" in copywriterAgent.ts for enhanced functionality. - Introduced a helper function `isErrCanceled` in arxiv.tool.ts to streamline error handling for cancellation. - Refactored error handling in arxivPdfParserTool to utilize the new `isErrCanceled` function. - Enhanced PDF data handling in arxivPdfParserTool to support various data types. - Updated temperature conversion error messages in calculator.tool.ts for better clarity. - Improved matrix multiplication error handling in calculator.tool.ts. - Refactored calendar-tool.ts to streamline logging and remove unnecessary mastra references. - Updated chartjs.tool.ts to ensure proper typing and handling of indicator data. - Enhanced code-analysis.tool.ts and code-search.tool.ts to replace mastra references with tracingContext. - Improved error handling and logging in code-chunking.ts for better debugging. - Enhanced weather-tool.ts and web-scraper-tool.ts to ensure proper tracing context usage. - Refactored data exporter logic in dataExporterTool to handle various data types more robustly. - Improved error messages and handling in various tools for better user feedback and debugging.
Learn moreAll Green is an AI agent that automatically: ✅ Addresses code review comments ✅ Fixes failing CI checks ✅ Resolves merge conflicts |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.
Summary by CodeRabbitRelease Notes
✏️ Tip: You can customize this high-level summary in your review settings. WalkthroughThis pull request updates Node.js version configuration, introduces a new mastraWorkflowSnapshotsTable to the Convex schema, refactors tool tracing context propagation across multiple mastra tools, adds mathjs dependency for calculator operations, improves type safety in components and tools, updates several dependencies including ai and convex, and enhances error handling and data serialization across various tool implementations. Changes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ❌ 3❌ Failed checks (1 warning, 2 inconclusive)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
🤖 Hi @ssdeanx, I've received your request, and I'm working on it now! You can track my progress in the logs for more details. |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
Summary of ChangesHello @ssdeanx, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed! This pull request primarily focuses on enhancing the stability, type safety, and maintainability of the application, particularly within its AI tooling and Convex backend integration. Key changes include updating core dependencies, refining data handling and serialization logic in web scraping and data export tools, and standardizing how tracing context is managed across various components. Additionally, the calculator tool was significantly improved by integrating a robust mathematical library, and the Convex schema definitions were made more explicit to ensure consistency and prevent potential issues. Highlights
Using Gemini Code AssistThe full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips. Invoking Gemini You can request assistance from Gemini at any point by creating a comment using either
Customization To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a Limitations & Feedback Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here. You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension. Footnotes
|
|
🤖 I'm sorry @ssdeanx, but I was unable to process your request. Please see the logs for more details. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Code Review
This pull request introduces a wide range of improvements across the codebase. Key changes include dependency updates (notably ai and convex), the introduction of mathjs to replace a potentially insecure custom expression evaluator, and significant refactoring for improved type safety and robustness. Many tools have been updated to handle different data types and error conditions more gracefully, and any types have been reduced. I've identified a logic bug in cancellation error handling in arxiv.tool.ts and a minor regression in an error message in text-analysis.tool.ts. Overall, these are great changes that enhance security, stability, and maintainability.
| const isCanceled = | ||
| (err && | ||
| typeof err === 'object' && | ||
| 'code' in err && | ||
| (err as any).code === 'ERR_CANCELED') ?? | ||
| (err instanceof Error && err.name === 'AbortError') |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The logic to detect a cancellation error here is flawed due to the use of the nullish coalescing operator (??) instead of a logical OR (||). This could lead to cancellation errors not being caught correctly. For consistency and correctness, please use the isErrCanceled helper function that was introduced in this same file.
| const isCanceled = | |
| (err && | |
| typeof err === 'object' && | |
| 'code' in err && | |
| (err as any).code === 'ERR_CANCELED') ?? | |
| (err instanceof Error && err.name === 'AbortError') | |
| const isCanceled = isErrCanceled(err) |
| break | ||
| default: | ||
| throw new Error(`Unknown operation: ${operation}`) | ||
| throw new Error(`Unknown operation: `) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 14
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (13)
src/components/ai-elements/tools/web-scraper-tool.tsx (1)
6-12: Unused import:Linkis imported but never used.The
Linkicon fromlucide-reactis imported but not referenced anywhere in the component. Remove it to reduce bundle size per coding guidelines on tree shaking.🧹 Proposed fix
import { ExternalLink, FileText, Globe, Image as ImageIcon, - Link, } from 'lucide-react'src/mastra/tools/arxiv.tool.ts (2)
1095-1108: Logic bug:??operator prevents AbortError detection; also usesanytype.The nullish coalescing (
??) operator on line 1100 causes a logic error. When the first expression evaluates tofalse(notnull/undefined),??does not fall through to the second check. This meansAbortErrorinstances won't be detected.Additionally,
(err as any).codeviolates the coding guideline to avoid explicitanytypes. Use theisErrCanceledhelper defined at the top of this file for consistency and correctness.🐛 Proposed fix
} catch (err: unknown) { - const isCanceled = - (err && - typeof err === 'object' && - 'code' in err && - (err as any).code === 'ERR_CANCELED') ?? - (err instanceof Error && err.name === 'AbortError') - if (isCanceled) { + if (isErrCanceled(err)) { throw new Error( `ArXiv metadata fetch cancelled for ${inputData.arxivId}` ) } throw err }
1309-1309: FIXME: Consider migrating to a proper XML parser.The FIXME comment correctly identifies that regex-based XML parsing is fragile. Libraries like
fast-xml-parserhandle edge cases (CDATA, nested tags, encoding) more robustly.Would you like me to generate an implementation using
fast-xml-parseror open an issue to track this improvement?src/mastra/tools/technical-analysis.tool.ts (2)
394-394: Useunknowninstead ofanyfor error type.This catch block uses
error: anywhile other tools in this file correctly useerror: unknown. The error is already handled correctly withinstanceof Errorchecks, so switching tounknownmaintains the same behavior with better type safety.♻️ Proposed fix
- } catch (error: any) { + } catch (error: unknown) {
606-606: Useunknowninstead ofanyfor error type.Same issue as
fibonacciTool- useunknownfor consistency with other tools in this file.♻️ Proposed fix
- } catch (error: any) { + } catch (error: unknown) {mdx-components.tsx (1)
120-127: Minor: Redundant nullish coalescing forsrc.
src ?? undefinedis redundant sincesrcis already typed asstring | undefined. The expression evaluates to the same value.♻️ Suggested simplification
img: ({ src, alt, title }: { src?: string; alt?: string; title?: string }) => ( <img - src={src ?? undefined} + src={src} alt={alt ?? ''} title={title} className="my-4 rounded-lg border border-border" /> ),src/mastra/tools/calendar-tool.ts (3)
273-282: MissingtracingContextingetTodayEventsspan creation.The
listEventstool was updated to includetracingContext: context?.tracingContextin thegetOrCreateSpancall, butgetTodayEventsis missing this update. This inconsistency may cause tracing gaps.🔧 Proposed fix
const span = getOrCreateSpan({ type: SpanType.TOOL_CALL, name: 'calendar-today-events', input: inputData, metadata: { 'tool.id': 'calendar-today-events', 'user.id': requestCtx?.userId, }, requestContext: context?.requestContext, + tracingContext: context?.tracingContext, })
405-416: MissingtracingContextingetUpcomingEventsspan creation.Similar to
getTodayEvents, thegetUpcomingEventstool is also missingtracingContext: context?.tracingContextin thegetOrCreateSpancall.🔧 Proposed fix
const span = getOrCreateSpan({ type: SpanType.TOOL_CALL, name: 'calendar-upcoming-events', input: inputData, metadata: { 'tool.id': 'calendar-upcoming-events', 'tool.input.days': inputData.days, 'tool.input.limit': inputData.limit, 'user.id': requestCtx?.userId, }, requestContext: context?.requestContext, + tracingContext: context?.tracingContext, })
535-545: MissingtracingContextinfindFreeSlotsspan creation.The
findFreeSlotstool is also missingtracingContext: context?.tracingContextin thegetOrCreateSpancall.🔧 Proposed fix
const span = getOrCreateSpan({ type: SpanType.TOOL_CALL, name: 'calendar-free-slots', input: inputData, metadata: { 'tool.id': 'calendar-free-slots', 'tool.input.date': inputData.date, 'user.id': requestCtx?.userId, }, requestContext: context?.requestContext, + tracingContext: context?.tracingContext, })src/mastra/tools/web-scraper-tool.ts (4)
2899-2912: Missing single quote XML escaping.The XML character escaping handles
<,>,&, and", but XML attribute values may also contain single quotes that need escaping as'or'. While the current context embeds values in element content (not attributes), adding single quote escaping would make this helper more robust for potential future attribute use.🔧 Suggested enhancement
- xmlContent += ` <${key}>${valueStr.replace(/[<>&"]/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"' })[c] ?? c)}</${key}>\n` + xmlContent += ` <${key}>${valueStr.replace(/[<>&"']/g, (c) => ({ '<': '<', '>': '>', '&': '&', '"': '"', "'": ''' })[c] ?? c)}</${key}>\n`
3854-3924: Path traversal vulnerability in dataExporterTool.The
dataExporterToolaccepts absolute paths directly from input (lines 3858-3859, 3884-3885, 3918-3919) without validating them against an allowed directory. Unlike other tools in this file that useValidationUtils.validateFilePath(), this tool allows writing to arbitrary filesystem locations.🔒 Proposed fix - add path validation
case 'json': { const jsonContent = JSON.stringify(inputData.data, null, 2) await ensureDataDir() filePath = path.isAbsolute(inputData.destination) ? inputData.destination : path.join(DATA_DIR, inputData.destination) + if (!ValidationUtils.validateFilePath(filePath, DATA_DIR)) { + throw new ScrapingError( + 'Invalid file path - must be within data directory', + 'INVALID_FILE_PATH' + ) + } await fs.mkdir(path.dirname(filePath), { recursive: true }) await fs.writeFile(filePath, jsonContent, 'utf-8') break } case 'csv': { // ... similar fix needed for csv case + if (!ValidationUtils.validateFilePath(filePath, DATA_DIR)) { + throw new ScrapingError( + 'Invalid file path - must be within data directory', + 'INVALID_FILE_PATH' + ) + } // ... } case 'xml': { // ... similar fix needed for xml case + if (!ValidationUtils.validateFilePath(filePath, DATA_DIR)) { + throw new ScrapingError( + 'Invalid file path - must be within data directory', + 'INVALID_FILE_PATH' + ) + } // ... }Additionally, consider disallowing absolute paths entirely to enforce consistent security boundaries:
- filePath = path.isAbsolute(inputData.destination) - ? inputData.destination - : path.join(DATA_DIR, inputData.destination) + if (path.isAbsolute(inputData.destination)) { + throw new ScrapingError( + 'Absolute paths are not allowed', + 'INVALID_FILE_PATH' + ) + } + filePath = path.join(DATA_DIR, inputData.destination)
2350-2368: Minor inconsistency: different file write pattern.This tool uses
fs.writeFiledirectly (line 2356) after path validation, while other tools in this file usefs.open+handle.writeFilepattern. Both are functionally correct since the path is validated, but consider aligning with thefs.openpattern for consistency.
2167-2168: Unused variabletracingContext.The
tracingContextvariable is extracted but never used directly. The tracing context is passed throughcontext?.tracingContexttogetOrCreateSpan()instead. Consider removing the unused variable declaration.🧹 Proposed fix
const writer = context?.writer const abortSignal = context?.abortSignal - const tracingContext: TracingContext | undefined = - context?.tracingContext const requestContext = context?.requestContext as ScraperToolContextNote: The same pattern appears at lines 741-742 and 1792-1793 - consider removing those as well.
🤖 Fix all issues with AI agents
In `@next.config.ts`:
- Around line 56-99: The current alias sanitization in the config.resolve block
(aliasObj -> normalized -> config.resolve) indiscriminately converts object and
function aliases to strings and replaces null/invalid entries with empty
strings, which breaks valid webpack alias types; instead, update the loop that
builds normalized to: detect and preserve valid webpack alias shapes (keep
objects that match { name, alias, onlyModule } or other object aliases), keep
functions (do not stringify) but mark them as non-cloneable so Turbopack gets a
placeholder/removed entry, and only remove or replace truly non-serializable
values (e.g., circular objects) by deleting the key or setting it to undefined;
also emit a warning (console.warn or processLogger.warn) mentioning the alias
key when you drop/replace an alias so failures aren’t silent. Ensure you update
the code paths referencing aliasObj, normalized, and config.resolve accordingly
so only unsupported values are stripped and valid objects/functions are
preserved.
In `@package.json`:
- Line 114: The package.json pin for "ai" was bumped to v6 but the codebase may
still use v5 patterns; run the official codemod (npx `@ai-sdk/codemod` v6), then
search and update all usages of ai APIs—notably replace or verify
createUIMessageStream, createUIMessageStreamResponse, and remove/replace any
experimental_generateObject calls—ensuring agent/tool calling and streaming APIs
follow v6 signatures; run tests and manual stream/tool flows, review codemod
changes, and fix any remaining type/signature mismatches reported by the
compiler or runtime.
In `@src/components/ai-elements/tools/types.ts`:
- Line 173: Remove the commented-out export line referencing
ConvertDataFormatUITool in types.ts; delete the line "//export type
ConvertDataFormatUITool = InferUITool<typeof convertDataFormatTool>" so no
stale/commented code remains (the symbol ConvertDataFormatUITool and the
now-unimported convertDataFormatTool should not be referenced); rely on VCS
history if this type needs restoring later.
In `@src/components/ai-elements/tools/web-scraper-tool.tsx`:
- Around line 77-78: Remove the unused destructured variable `structuredData`
from the destructuring of `output.analysis` (where `structuredData, } =
output.analysis || {}` appears) so the `no-unused-vars` rule is satisfied;
update the destructuring to only capture the used properties (or omit
`output.analysis` entirely if none are used) in the `web-scraper-tool`
component.
- Around line 67-78: The crash happens because destructuring from output.content
and output.analysis can yield undefined values (e.g., extractedData), so update
the destructuring where output.content and output.analysis are read to provide
safe defaults (for example: extractedData = [], rawContent = '', markdownContent
= '' and metadata = {}, images = [], structuredData = {}), and ensure any later
uses of .length or .map (references: extractedData, images) rely on these
defaults or have null checks before calling .length/.map so the code in
web-scraper-tool.tsx no longer throws when output.content or output.analysis are
missing.
In `@src/mastra/agents/copywriterAgent.ts`:
- Line 24: Remove the unused import convexMemory from the top of
copywriterAgent.ts; the file uses pgMemory for memory configuration (see
reference to pgMemory around line 77), so delete the import statement
"convexMemory" to eliminate the unused symbol and keep imports consistent.
In `@src/mastra/tools/arxiv.tool.ts`:
- Around line 795-797: The empty catch swallowing errors in the metadata fetch
should be replaced with a logged error to aid debugging: inside the catch(err)
block that surrounds the metadata fetch in arxiv.tool.ts, call the module's
logging facility (e.g., processLogger.error(...) or this.logger.error(...); if
neither exists use console.error) and include the error object plus context such
as the paper identifier/URL and a short message like "Metadata fetch failed" so
failures are recorded while still allowing the code to continue.
- Around line 22-30: Replace the inline cancellation checks inside
arxivPaperDownloaderTool with the existing helper isErrCanceled: locate the
error handling block in arxivPaperDownloaderTool where it currently inspects
err.name or err.code directly (the inline cancellation detection around the
download/abort catch), and call isErrCanceled(err) instead to decide
cancellation flow; ensure any branches that previously relied on the inline
checks behave identically (return/cancel/throw) and remove the duplicated inline
logic so only the isErrCanceled helper is used for consistency.
- Around line 706-725: The code currently falls back to Buffer.from(pdfData,
'utf-8') when pdfResp.data is a string, which can corrupt binary PDFs; in the
pdf handling block (pdfResp / pdfData / pdfBuffer in arxiv.tool.ts) replace the
string branch with a fail-fast behavior—throw an Error (or processLogger.error
then throw) that includes context (e.g., "Unexpected string PDF response" plus
pdfResp.headers['content-type'] or other response metadata) and remove the UTF-8
conversion; ensure the error message references pdfResp and pdfData so callers
can surface the issue and validate that the upstream httpFetch was invoked with
responseType: 'arraybuffer'.
In `@src/mastra/tools/calculator.tool.ts`:
- Line 7: The mathjs evaluate usage must be hardened: before calling evaluate()
in the Calculator tool, explicitly override high-risk functions (import,
createUnit, parse, simplify, derivative) in the evaluation context to
no-op/throw; verify the installed mathjs version at runtime or in package
metadata is not a vulnerable release; enforce expression validation by checking
CalculatorToolContext.maxExpressionLength and rejecting expressions containing
identifiers not in your whitelist (combine with existing MATH_CONSTANTS and
MATH_FUNCTIONS); add resource limits by using mathjs evaluate options or a
wrapper to enforce a timeout and a complexity check (e.g., node-side AST
traversal/operation-count limit) to prevent expression bombs; and validate keys
on the context object (reject prototypes or keys like __proto__, constructor) to
prevent prototype pollution before passing the context to evaluate(). Ensure
these changes touch the evaluate call site and the context construction logic
that references MATH_CONSTANTS, MATH_FUNCTIONS, and
CalculatorToolContext.maxExpressionLength.
In `@src/mastra/tools/calendar-tool.ts`:
- Line 400: Remove the extraneous blank line immediately before the execute
function declaration in the CalendarTool implementation (the execute method) so
the method is directly adjacent to the preceding code; after removing the blank
line, run the project's formatter (Prettier/ESLint --fix) to ensure consistent
formatting.
In `@src/mastra/tools/chartjs.tool.ts`:
- Around line 231-253: The map conversions use redundant Number(...) around
already-cast values; update the mappings for macd, signal, and histogram to
directly cast the properties from macdResult (e.g., m.MACD as number, m.signal
as number, m.histogram as number) instead of wrapping them with Number(),
keeping the same variable names (macdResult, macd, signal, histogram) and
ensuring the resulting arrays are typed as number[] or (number | null)[]
consistent with closePrices and the padding logic.
In `@src/mastra/tools/text-analysis.tool.ts`:
- Around line 391-393: The thrown error in the default case currently uses a
truncated message ("Unknown operation: ") which omits the actual operation
value; update the default branch in the switch (the block that throws new
Error(`Unknown operation: `)) to include the operation variable (e.g.,
`operation` or whatever identifier is being switched on) in the error message so
the thrown Error reads something like "Unknown operation: <operationValue>" to
aid debugging.
In `@src/mastra/tools/web-scraper-tool.ts`:
- Line 51: Remove the unused import "inspect" from "node:util" in the imports of
the web-scraper-tool module: locate the import line that reads "import { inspect
} from 'node:util'" and delete it (or remove "inspect" from the import
specifier) so the file no longer imports an unused symbol.
📜 Review details
Configuration used: Organization UI
Review profile: ASSERTIVE
Plan: Pro
⛔ Files ignored due to path filters (2)
convex/_generated/api.d.tsis excluded by!**/_generated/**package-lock.jsonis excluded by!**/package-lock.json
📒 Files selected for processing (21)
convex.jsonconvex/mastra/storage.tsconvex/schema.tsmdx-components.tsxnext.config.tspackage.jsonsrc/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/components/ai-elements/tools/types.tssrc/components/ai-elements/tools/web-scraper-tool.tsxsrc/mastra/agents/copywriterAgent.tssrc/mastra/tools/arxiv.tool.tssrc/mastra/tools/calculator.tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/chartjs.tool.tssrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/code-chunking.tssrc/mastra/tools/code-search.tool.tssrc/mastra/tools/technical-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/web-scraper-tool.ts
🧰 Additional context used
📓 Path-based instructions (27)
src/mastra/**/*
📄 CodeRabbit inference engine (src/AGENTS.md)
mastramodules can import fromutils, but must not import fromapporcli(excepttypes)
Files:
src/mastra/tools/code-search.tool.tssrc/mastra/agents/copywriterAgent.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/technical-analysis.tool.tssrc/mastra/tools/code-chunking.tssrc/mastra/tools/calculator.tool.tssrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/chartjs.tool.tssrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/arxiv.tool.ts
**/*.{js,ts,tsx,jsx,py,java,cs,go,rb,php,swift,kt}
📄 CodeRabbit inference engine (.github/instructions/code-review-generic.instructions.md)
**/*.{js,ts,tsx,jsx,py,java,cs,go,rb,php,swift,kt}: Use descriptive and meaningful names for variables, functions, and classes
Apply Single Responsibility Principle: each function/class should do one thing well
Avoid code duplication (DRY principle)
Keep functions small and focused, ideally under 20-30 lines
Avoid deeply nested code with maximum 3-4 levels of nesting
Avoid magic numbers and strings; use named constants instead
Code should be self-documenting; use comments only when necessary for non-obvious logic
Implement proper error handling at appropriate levels with meaningful error messages
Avoid silent failures and ignored exceptions; fail fast and validate inputs early
Use appropriate error types/exceptions rather than generic error handling
Validate and sanitize all user inputs
Use parameterized queries to prevent SQL injection; never use string concatenation for SQL
Implement proper authentication checks before accessing resources
Verify users have proper authorization permissions before allowing actions
Use established cryptography libraries; never implement custom cryptographic algorithms
Avoid N+1 query problems; use proper indexing and eager loading strategies
Use appropriate algorithms with suitable time/space complexity for the use case
Utilize caching for expensive or repeated operations
Ensure proper cleanup of connections, files, and streams
Implement pagination for large result sets
Load data only when needed (lazy loading)
Document all public APIs with clear purpose, parameters, and return values
Include explanatory comments for complex logic that is not immediately obvious
Files:
src/mastra/tools/code-search.tool.tssrc/mastra/agents/copywriterAgent.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/technical-analysis.tool.tssrc/mastra/tools/code-chunking.tssrc/mastra/tools/calculator.tool.tssrc/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/chartjs.tool.tssrc/components/ai-elements/tools/web-scraper-tool.tsxmdx-components.tsxconvex/mastra/storage.tssrc/components/ai-elements/tools/types.tsnext.config.tsconvex/schema.tssrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/arxiv.tool.ts
**/*.{js,ts,tsx,jsx,py,java,cs,go,rb,php,swift,kt,json,yaml,yml,env,properties,xml}
📄 CodeRabbit inference engine (.github/instructions/code-review-generic.instructions.md)
Never include passwords, API keys, tokens, or personally identifiable information (PII) in code or logs
Files:
src/mastra/tools/code-search.tool.tssrc/mastra/agents/copywriterAgent.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/technical-analysis.tool.tsconvex.jsonsrc/mastra/tools/code-chunking.tssrc/mastra/tools/calculator.tool.tssrc/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/chartjs.tool.tssrc/components/ai-elements/tools/web-scraper-tool.tsxmdx-components.tsxconvex/mastra/storage.tssrc/components/ai-elements/tools/types.tsnext.config.tsconvex/schema.tspackage.jsonsrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/arxiv.tool.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
**/*.{ts,tsx,js,jsx}: Usenext/dynamicfor lazy loading components to improve initial load time (e.g.,dynamic(() => import('../components/MyComponent')))
Use React Context, Zustand, Jotai, or Recoil for managing global state instead of Redux for smaller Next.js projects
Avoid over-fetching data—only fetch the data that is needed by the component
Avoid blocking the main thread with long-running synchronous operations
Usetry...catchblocks for handling errors in asynchronous operations
Use immutable data structures and avoid mutating data directly to prevent unexpected side effects
Implement secure authentication and authorization mechanisms; avoid storing secrets in client-side code
Always validate user input on the server-side for security; use client-side validation only for immediate feedback
Configure ESLint with recommended rules for JavaScript and React, and integrate it into the build process
Centralize error logging to a service like Sentry or Bugsnag for tracking and analyzing issues
Remove unused code using tree shaking to reduce bundle size
Files:
src/mastra/tools/code-search.tool.tssrc/mastra/agents/copywriterAgent.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/technical-analysis.tool.tssrc/mastra/tools/code-chunking.tssrc/mastra/tools/calculator.tool.tssrc/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/chartjs.tool.tssrc/components/ai-elements/tools/web-scraper-tool.tsxmdx-components.tsxconvex/mastra/storage.tssrc/components/ai-elements/tools/types.tsnext.config.tsconvex/schema.tssrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/arxiv.tool.ts
**/*.{ts,js}
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
Encrypt sensitive data at rest and in transit
Files:
src/mastra/tools/code-search.tool.tssrc/mastra/agents/copywriterAgent.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/technical-analysis.tool.tssrc/mastra/tools/code-chunking.tssrc/mastra/tools/calculator.tool.tssrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/chartjs.tool.tsconvex/mastra/storage.tssrc/components/ai-elements/tools/types.tsnext.config.tsconvex/schema.tssrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/arxiv.tool.ts
**/*.{ts,tsx,js,jsx,json,css,scss}
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
Use a code formatter like Prettier to automatically format code on save
Files:
src/mastra/tools/code-search.tool.tssrc/mastra/agents/copywriterAgent.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/technical-analysis.tool.tsconvex.jsonsrc/mastra/tools/code-chunking.tssrc/mastra/tools/calculator.tool.tssrc/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/chartjs.tool.tssrc/components/ai-elements/tools/web-scraper-tool.tsxmdx-components.tsxconvex/mastra/storage.tssrc/components/ai-elements/tools/types.tsnext.config.tsconvex/schema.tspackage.jsonsrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/arxiv.tool.ts
**/*.{js,jsx,ts,tsx,py,java,c,cpp,cs,go,rb,php,swift,kt,scala,rs}
📄 CodeRabbit inference engine (.github/instructions/self-explanatory-code-commenting.instructions.md)
**/*.{js,jsx,ts,tsx,py,java,c,cpp,cs,go,rb,php,swift,kt,scala,rs}: Avoid obvious comments that state what the code already clearly expresses (e.g., 'Increment counter by one' for counter++).
Avoid redundant comments that simply repeat what the code already expresses.
Keep comments accurate and update them when code changes to avoid outdated comments that no longer match the implementation.
Write comments that explain WHY specific calculations or business logic is implemented the way it is, especially for complex or non-obvious approaches.
Comment non-obvious algorithms to explain the algorithm choice and why it was selected for the problem.
Comment regex patterns to explain what patterns they match and their intended purpose.
Comment API constraints, rate limits, gotchas, and external dependencies to explain non-obvious external requirements.
Comment configuration constants and magic numbers to explain their source, reasoning, or constraints.
Use annotation comments (TODO, FIXME, HACK, NOTE, WARNING, PERF, SECURITY, BUG, REFACTOR, DEPRECATED) to mark code requiring attention or special consideration.
Never comment out code; remove it instead and use version control history if needed.
Avoid using changelog comments in code; maintain version history in commit messages and documentation instead.
Avoid decorative divider comments (like //====); use code organization and clear function/class names instead.
Ensure comments are grammatically correct, clear, and use professional language.
Place comments appropriately above the code they describe, not inline or after code when possible.
Files:
src/mastra/tools/code-search.tool.tssrc/mastra/agents/copywriterAgent.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/technical-analysis.tool.tssrc/mastra/tools/code-chunking.tssrc/mastra/tools/calculator.tool.tssrc/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/chartjs.tool.tssrc/components/ai-elements/tools/web-scraper-tool.tsxmdx-components.tsxconvex/mastra/storage.tssrc/components/ai-elements/tools/types.tsnext.config.tsconvex/schema.tssrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/arxiv.tool.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/instructions/self-explanatory-code-commenting.instructions.md)
**/*.{ts,tsx}: Use TSDoc standards for documenting public APIs in TypeScript, including@param,@returns,@throws,@example, and@seetags.
Include file headers with@fileoverview,@author,@copyright, and@licenseTSDoc tags for TypeScript files.
Document interface and type definitions with TSDoc comments explaining their purpose and usage.
Use@templatetags to document generic type parameters in TypeScript functions and types.
Document type guards with clear explanations of validation logic and return type predicates.
Comment advanced type definitions to explain their purpose and when they should be used.
**/*.{ts,tsx}: Use strict equality (eqeqeq: ['error', 'always']) — always use===and!==instead of==and!=
Require curly braces for all blocks (curly: ['error', 'all']) — even single-statement blocks must have braces
Avoid unused variables (@typescript-eslint/no-unused-vars: ['warn', {}]) — remove all unused variable declarations
Avoid explicitanytypes (@typescript-eslint/no-explicit-any: 'warn') — use proper types orunknowninstead
Use object shorthand syntax (object-shorthand: 'error') — use{ name }instead of{ name: name }
Prefer arrow functions in callbacks (prefer-arrow-callback: 'error') — use=>syntax instead of function expressions
Useconstwhen possible (prefer-const: 'warn') — preferconstoverletfor variables that are not reassigned
Preferinterfacefor type definitions (@typescript-eslint/consistent-type-definitions: ['error', 'interface']) — use interfaces for object shapes in public APIs
Useimport typefor type-only imports — always useimport type { T } from 'module'for type declarations
Use optional chaining (?.) for nullable access — useobj?.propinstead ofobj && obj.prop
Use nullish coalescing (??) for defaults — prefervalue ?? defaultValueovervalue || defaultValuefor null checks
Require explicit return types for public functions — all public function declaratio...
Files:
src/mastra/tools/code-search.tool.tssrc/mastra/agents/copywriterAgent.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/technical-analysis.tool.tssrc/mastra/tools/code-chunking.tssrc/mastra/tools/calculator.tool.tssrc/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/chartjs.tool.tssrc/components/ai-elements/tools/web-scraper-tool.tsxmdx-components.tsxconvex/mastra/storage.tssrc/components/ai-elements/tools/types.tsnext.config.tsconvex/schema.tssrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/arxiv.tool.ts
**/*.{ts,tsx,js,jsx,mjs,cjs,py,java,cs,go,rb,php,rs,cpp,c,h,hpp}
📄 CodeRabbit inference engine (.github/instructions/update-docs-on-code-change.instructions.md)
Use automated documentation generation tools appropriate for the language: JSDoc/TSDoc for JavaScript/TypeScript, Sphinx/pdoc for Python, Javadoc for Java, xmldoc for C#, godoc for Go, rustdoc for Rust
Files:
src/mastra/tools/code-search.tool.tssrc/mastra/agents/copywriterAgent.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/technical-analysis.tool.tssrc/mastra/tools/code-chunking.tssrc/mastra/tools/calculator.tool.tssrc/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/chartjs.tool.tssrc/components/ai-elements/tools/web-scraper-tool.tsxmdx-components.tsxconvex/mastra/storage.tssrc/components/ai-elements/tools/types.tsnext.config.tsconvex/schema.tssrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/arxiv.tool.ts
src/mastra/tools/**/*.ts
📄 CodeRabbit inference engine (AGENTS.md)
src/mastra/tools/**/*.ts: Implement tools usingcreateTool({ id, description, inputSchema, outputSchema, execute })with strict Zod schemas — all tools must follow this pattern
Use strict Zod schemas for all tool input and output validation — defineinputSchemaandoutputSchemawith proper type inference
src/mastra/tools/**/*.ts: Create tools using thecreateToolpattern with explicit Zod schemas for input/output validation
Keep tools small and side-effect-free when possible; delegate complex orchestration to agents
Files:
src/mastra/tools/code-search.tool.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/technical-analysis.tool.tssrc/mastra/tools/code-chunking.tssrc/mastra/tools/calculator.tool.tssrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/chartjs.tool.tssrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/arxiv.tool.ts
src/mastra/{tools,config}/**
📄 CodeRabbit inference engine (src/mastra/AGENTS.md)
When adding new tools or providers, add environment variable placeholders to
.envand document them insrc/mastra/config/AGENTS.md
Files:
src/mastra/tools/code-search.tool.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/technical-analysis.tool.tssrc/mastra/tools/code-chunking.tssrc/mastra/tools/calculator.tool.tssrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/chartjs.tool.tssrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/arxiv.tool.ts
src/mastra/tools/**/*.{ts,tsx}
📄 CodeRabbit inference engine (src/mastra/tools/AGENTS.md)
src/mastra/tools/**/*.{ts,tsx}: ImportSpanTypefrom@mastra/core/observabilityandTracingContextfrom@mastra/core/observabilityto maintain consistency and compatibility across the codebase
All tools must use Mastra's tracing helpers and execution-providedtracingContextinstead of importing or using OpenTelemetry APIs directly (do NOT import@opentelemetry/api)
Define a typedRequestContextinterface extendingRequestContextfor each tool to ensure type safety and clear documentation of expected context values
Create a child span usingtracingContext?.currentSpan?.createChildSpan()withtype: SpanType.TOOL_CALLfor the primary operation and passrequestContext: context?.requestContextfor automatic metadata extraction
Includetool.id,user.id, andworkspace.idin span metadata where applicable
Emitdata-tool-progressevents at the start and completion of tool execution withstatus('in-progress' or 'done') andstagematching the tool id
RespectabortSignalearly (fail fast) in tool execution and record cancellations in spans before long-running operations
Progress event format must haveidat the top level of the object (outsidedata), not inside thedataobject
Lifecycle hooks must be declared in order:onInputStart,onInputDelta,onInputAvailablebefore theexecuteproperty, andonOutputafterexecute
All lifecycle hooks (onInputStart,onInputDelta,onInputAvailable,onOutput) must be implemented with structured logging using the Mastra logger
Uselog.info()from the Mastra logger with structured logging objects containingtoolCallId,messageCount,inputData,abortSignal, andhookproperties in lifecycle hooks
Extract typed context in execute function with pattern:const requestContext = context?.requestContext as ToolNameContext
Provide sensible defaults for optional RequestContext properties (e.g.,const temperatureUnit = requestContext?.temperatureUnit ?? 'celsius')
Update spans...
Files:
src/mastra/tools/code-search.tool.tssrc/mastra/tools/weather-tool.tssrc/mastra/tools/technical-analysis.tool.tssrc/mastra/tools/code-chunking.tssrc/mastra/tools/calculator.tool.tssrc/mastra/tools/code-analysis.tool.tssrc/mastra/tools/text-analysis.tool.tssrc/mastra/tools/chartjs.tool.tssrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.tssrc/mastra/tools/arxiv.tool.ts
src/mastra/agents/**/*.ts
📄 CodeRabbit inference engine (AGENTS.md)
Implement agents using
new Agent({ id, name, description, instructions, model, tools, memory })— all agents must follow this patternWire tools together into agents to create higher-level behaviors; use
RequestContextor agent-specific runtime context types (e.g.,EditorRuntimeContext) to enforce access control
Files:
src/mastra/agents/copywriterAgent.ts
**/*-tool.ts
📄 CodeRabbit inference engine (AGENTS.md)
Name tool implementation files with
-tool.tssuffix (e.g.,weather-tool.ts)
Files:
src/mastra/tools/weather-tool.tssrc/mastra/tools/web-scraper-tool.tssrc/mastra/tools/calendar-tool.ts
**/{components,src/components,ui}/**/*.{jsx,tsx}
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
Name components using PascalCase (e.g.,
ComponentName.jsxorComponentName.tsx)
Files:
src/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/components/ai-elements/tools/web-scraper-tool.tsx
**/{components,pages,app}/**/*.{tsx,jsx}
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
**/{components,pages,app}/**/*.{tsx,jsx}: Usenext/imagecomponent for automatic image optimization, including lazy loading and responsive images
UseSWRorReact Queryfor client-side data fetching and caching
Usereact-hook-formfor managing forms and validation
Always usesetStateor hooks to update state; never mutate state directly
UseReact.memoto memoize components and prevent unnecessary re-renders
Never write server-side code in client components to avoid exposing secrets or causing unexpected behavior
Create reusable error boundary components and implementgetDerivedStateFromErrororcomponentDidCatchlifecycle methods
Use the<Link prefetch>tag to prefetch pages that are likely to be visited for improved performance
Minimize re-renders by only updating state when necessary to reduce the number of re-renders
Use Intersection Observer API for manual lazy loading of content beyond image and component lazy loading
Sanitize user input to prevent Cross-Site Scripting (XSS) attacks, especially when rendering HTML directly from user input
Write unit tests for individual components using React Testing Library to test from a user perspective
Separate components that handle data fetching and state management (container components) from those that only render UI (presentational components)
Favor composition over inheritance to create flexible and reusable components
Group files by feature rather than by type (e.g.,components/user-profile/instead ofcomponents/button,components/form)
Files:
src/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/components/ai-elements/tools/web-scraper-tool.tsx
**/*.{tsx,jsx,module.css,module.scss}
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
Use CSS Modules, Styled Components, or Tailwind CSS for component-level styling, with Tailwind CSS preferred for rapid development
Files:
src/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/components/ai-elements/tools/web-scraper-tool.tsxmdx-components.tsx
**/*.{tsx,jsx}
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
**/*.{tsx,jsx}: Use complete dependency arrays inuseEffecthooks to prevent unexpected behavior and infinite loops
Clean up event listeners and timers inuseEffecthooks to avoid memory leaks
Files:
src/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/components/ai-elements/tools/web-scraper-tool.tsxmdx-components.tsx
**/{components,lib,app}/**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
Store authentication tokens securely in HTTP-only cookies or local storage
Files:
src/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/components/ai-elements/tools/web-scraper-tool.tsxsrc/components/ai-elements/tools/types.ts
**/{components,app,pages}/**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
Use a validation library like
zodoryupfor validating user input
Files:
src/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/components/ai-elements/tools/web-scraper-tool.tsxsrc/components/ai-elements/tools/types.ts
**/{components,src/components,ui}/**/*.{tsx,jsx}
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
Organize components into atoms, molecules, organisms, templates, and pages using atomic design principles
Files:
src/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/components/ai-elements/tools/web-scraper-tool.tsx
**/{components,pages,app}/**/*
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
Keep related components, styles, and tests in the same directory through co-location
Files:
src/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/components/ai-elements/tools/web-scraper-tool.tsxsrc/components/ai-elements/tools/types.ts
**/*.tsx
📄 CodeRabbit inference engine (AGENTS.md)
Use kebab-case for directory names containing components (e.g.,
ai-elements/,public-components/)
Files:
src/components/ai-elements/tools/e2b-sandbox-tool.tsxsrc/components/ai-elements/tools/web-scraper-tool.tsxmdx-components.tsx
next.config.{ts,js}
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
next.config.{ts,js}: Configure caching headers to improve performance and reduce server load
Optimize build settings for production by enabling minification and tree shaking
Files:
next.config.ts
{package.json,package-lock.json,yarn.lock,requirements.txt,requirements-*.txt,Pipfile,Pipfile.lock,build.gradle,pom.xml,*.gemfile,composer.json,Cargo.toml,go.mod,go.sum}
📄 CodeRabbit inference engine (.github/instructions/code-review-generic.instructions.md)
Keep dependencies up-to-date and monitor for known security vulnerabilities
Files:
package.json
{package.json,package-lock.json,yarn.lock}
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
Regularly update dependencies to patch security vulnerabilities
Files:
package.json
package.json
📄 CodeRabbit inference engine (.github/instructions/next-js.instructions.md)
Use a build script to automate the build process
Files:
package.json
🧬 Code graph analysis (2)
src/mastra/tools/code-chunking.ts (1)
src/mastra/config/logger.ts (1)
log(16-36)
src/mastra/tools/arxiv.tool.ts (1)
src/mastra/lib/http-client.ts (1)
HttpFetchResponse(34-43)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (5)
- GitHub Check: CodeQL analysis (javascript-typescript)
- GitHub Check: Codacy Security Scan
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: Codacy Security Scan
- GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (39)
src/mastra/tools/code-chunking.ts (1)
204-209: LGTM!The error handling improvement correctly normalizes the error message extraction using the standard
instanceof Errorpattern. This ensures clean, consistent warning output regardless of whether a nativeErroror another throwable type is caught, aligning with the standardized error messaging patterns across other mastra tools.src/components/ai-elements/tools/e2b-sandbox-tool.tsx (2)
83-83: LGTM!The change from destructuring to direct property access is functionally equivalent and acceptable.
39-43: Component rename verification complete—no breaking changes found.The rename from
E2bSandboxTooltoE2bSandboxToolComponenthas been applied safely. No remaining references to the old component name exist in the codebase, and no files import the old export, indicating all consumers have already been updated or this component was not actively referenced elsewhere.src/mastra/tools/arxiv.tool.ts (2)
406-411: LGTM!Correct usage of the
isErrCanceledhelper for consistent cancellation detection.
658-682: LGTM!Good use of explicit
HttpFetchResponsetyping and consistent cancellation handling withisErrCanceled.convex/mastra/storage.ts (1)
1-3: LGTM!Formatting-only changes adding consistent semicolons.
src/mastra/tools/weather-tool.ts (1)
115-129: LGTM! Consistent tracing context propagation.The change to use
context?.tracingContextdirectly ingetOrCreateSpanaligns with the project-wide pattern for root span creation. The tool properly implements all tracing guidelines including span metadata, error handling, and progress events.src/mastra/tools/technical-analysis.tool.ts (2)
538-545: LGTM! Explicit typing improves type safety.Replacing the permissive
anytype with an explicit interface that matches the ZodoutputSchemais a good improvement. The type correctly captures the optional pivot types (StandardPivot,WoodiePivot,CamarillaPivot,FibonacciPivot) and aligns with the schema defined at lines 451-498.
1564-1572: LGTM! Type cast ensures proper type inference.Casting
candlesRawtoHeikinAshiOutput[]before mapping ensures proper type safety when accessing the candle fields. TheNumber()conversions provide additional runtime safety for the mapped values.convex.json (1)
3-3: Node.js 20 is required for Convex compatibility.Convex officially supports only Node.js 20 and 22. Node.js 24 is not in Convex's supported runtime list, so this downgrade is necessary for the project to work correctly.
Likely an incorrect or invalid review comment.
package.json (3)
162-162: LGTM!The
mathjsdependency addition aligns with the calculator tool refactoring to usemathjs.evaluate()for safer expression evaluation.
133-133: LGTM!Minor version update for
convexfrom 1.26.2 to 1.31.4. This aligns with the newmastraWorkflowSnapshotsTableaddition mentioned in the PR summary.
229-229: @types/node version is compatible with the codebase.The downgrade to
@types/nodev22 does not introduce type mismatches. The codebase uses only stable, longstanding Node.js APIs (fs, fs/promises, path, stream/promises, crypto, process) that existed well before v22 and are fully compatible with theengines.noderequirement of>=20.9.0. No v24-specific APIs are used in the code.src/mastra/tools/text-analysis.tool.ts (2)
88-88: LGTM!The change from global
mastrareference to explicittracingContextpropagation aligns with the broader refactoring pattern across tools, improving testability and avoiding reliance on global state. Based on coding guidelines, tools should use Mastra's tracing helpers and execution-providedtracingContext.
327-327: LGTM!Consistent with the tracing context propagation pattern applied to
textAnalysisTool.mdx-components.tsx (2)
49-56: LGTM!Defensive href handling ensures type safety when href might not be a string. Using
'#'as a fallback prevents runtime errors.
79-88: LGTM!The explicit typing with
{ children?: ReactNode; className?: string }and the improved inline code detection usingtypeof className !== 'string'correctly handles cases whereclassNameis undefined or not a string.src/mastra/tools/code-search.tool.ts (1)
159-159: LGTM!Consistent application of the tracing context propagation pattern, replacing global
mastrareference with explicitcontext?.tracingContext.src/mastra/tools/calculator.tool.ts (2)
206-206: LGTM!Using
String(from)andString(to)in error messages provides defensive handling, even though TypeScript types should prevent non-string values from reaching these default cases.Also applies to: 218-218
242-244: LGTM!The
Array.frompattern is cleaner and more idiomatic than nestednew Array().fill()calls, avoiding the common pitfall wherefill()with objects creates shared references.convex/schema.ts (3)
1-2: LGTM!The imports from
convex/serverandconvex/valuesare correctly structured for defining a Convex schema with custom tables.
13-24: Explicit table definition with comprehensive indexes.The explicit definition of
mastraWorkflowSnapshotsTableis well-structured with appropriate field types and indexes. The comment explaining the rationale (ensuringidfield exists for downstream Convex schema variants) is helpful for future maintainers.A few observations:
v.any()forsnapshotis appropriate for storing arbitrary workflow state, though it bypasses type validation.- The indexes cover common query patterns (by_record_id, by_workflow_run, by_workflow, by_resource, by_created).
26-35: LGTM!The schema export correctly includes all tables, with the new
mastra_workflow_snapshotstable integrated alongside existing tables.next.config.ts (1)
4-4: LGTM!Adding explicit
Configurationtyping for the webpack config function improves type safety and IDE support.Also applies to: 42-42
src/mastra/tools/calendar-tool.ts (2)
180-180: LGTM!The
tracingContextis correctly passed togetOrCreateSpan, aligning with the PR-wide refactor for consistent tracing context propagation.
242-250: LGTM!The
onOutputhook follows the coding guidelines with proper structured logging containingtoolCallId,toolName,eventsFound,abortSignal, andhookproperties.src/mastra/tools/code-analysis.tool.ts (1)
454-456: LGTM!The change from global
mastrareference to explicittracingContext: context?.tracingContextaligns with the PR-wide refactor for consistent tracing context propagation. This is the recommended pattern per coding guidelines.src/mastra/tools/chartjs.tool.ts (5)
162-162: LGTM!Explicitly typing
indicatorDataasArray<number | null>improves type safety and matches the output schema.
168-188: LGTM!The SMA calculation is correctly implemented with:
- Scoped block for variable isolation
- Defensive
?? []fallback- Proper null padding to align with price series length
- Explicit type casting for the concatenated array
189-206: LGTM!The EMA calculation follows the same correct pattern as SMA.
207-229: LGTM!The RSI calculation is correctly implemented with proper typing and the
yAxisID: 'y1'assignment for the separate oscillator axis.
282-330: LGTM!The Bollinger Bands calculation is correctly implemented with explicit typing and proper length alignment. The
fill: '-1'for the lower band creates the visual fill effect between bands.src/mastra/tools/web-scraper-tool.ts (7)
26-47: LGTM! Good type safety improvement.The explicit type casts through
unknowneliminate unsafeanyusage while maintaining compatibility with test mocks. The dual constructor/factory pattern is appropriate for the mocking scenarios described.
898-904: LGTM! Good type narrowing.The explicit type cast with
userData?: Record<string, unknown>provides safer access to the request's userData while avoidingany. The optional chaining on line 902-903 correctly handles the case where userData may be undefined.
921-1043: Well-structured link enqueue refactoring.The manual link collection approach with explicit typing provides better control over the crawling behavior:
- Local type definitions (
EnqueueLinksOptions,EnqueueLinksFn) provide type safety without relying on library internals- URL validation with
ValidationUtils.isUrlAllowedensures domain allowlist compliance- The
transformRequestFunctioncorrectly handles both string URLs and structured request objectsThe defensive empty string fallback on line 1009 (
nextUrl = orig?.url ?? '') is appropriate since it will be caught by the validation at line 1019.
1192-1195: LGTM! Good type safety practice.Explicitly typing
JSON.parse()result asunknowninstead of implicitanyaligns with TypeScript best practices and the coding guidelines to avoid explicitanytypes.
1923-1937: LGTM! Improved error message extraction.The explicit type checking pattern for error handling is more robust:
- Checks
instanceof Errorfor proper Error objects- Handles string errors directly
- Falls back to a descriptive default for unknown error types
This avoids potential issues with
String()coercion on unusual error values.
2560-2569: LGTM!Consistent typed destructuring pattern for the request handler parameters.
2931-2950: LGTM! Defensive error message construction.The explicit type checking with JSON.stringify fallback handles edge cases gracefully, including potential circular references. While Zod validation should prevent invalid formats from reaching this code path, the defensive approach is appropriate for error handling robustness.
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
|
|
||
| // Sanitize resolve.alias so values are serializable for Turbopack/worker cloning | ||
| // Ensure resolve exists and normalize alias values to strings/arrays of strings | ||
| const existingResolve = config.resolve ?? {} | ||
| const aliasObj = (existingResolve as unknown as Record<string, unknown>).alias ?? {} | ||
| if (typeof aliasObj === 'object' && aliasObj !== null) { | ||
| const normalized: Record<string, string | string[]> = {} | ||
| for (const [k, v] of Object.entries(aliasObj as Record<string, unknown>)) { | ||
| if (Array.isArray(v)) { | ||
| normalized[k] = v.map((x) => String(x)) | ||
| } else if (typeof v === 'object' && v !== null) { | ||
| // For objects, stringify to avoid '[object Object]' implicit string coercion | ||
| try { | ||
| normalized[k] = JSON.stringify(v) | ||
| } catch { | ||
| normalized[k] = '' | ||
| } | ||
| } else if (typeof v === 'function') { | ||
| // For functions, prefer the function name to avoid serializing the entire function | ||
| // Narrow to an object with an optional name property to avoid using the broad Function type | ||
| const fnName = (v as { name?: string })?.name ?? '' | ||
| normalized[k] = fnName | ||
| } else if (v === null || v === undefined) { | ||
| // Keep null/undefined normalized to an empty string | ||
| normalized[k] = '' | ||
| } else { | ||
| // At this point, expect primitives (string/number/boolean/symbol/bigint). | ||
| // Guard against objects to avoid default Object stringification '[object Object]'. | ||
| const t = typeof v | ||
| if (t === 'string' || t === 'number' || t === 'boolean' || t === 'symbol' || t === 'bigint') { | ||
| // Narrow the type for the linter to avoid base-to-string coercion warnings | ||
| normalized[k] = String(v as string | number | boolean | symbol | bigint) | ||
| } else { | ||
| // Fallback for unexpected non-serializable values | ||
| try { | ||
| normalized[k] = JSON.stringify(v) | ||
| } catch { | ||
| normalized[k] = '' | ||
| } | ||
| } | ||
| } | ||
| } | ||
| config.resolve = { ...existingResolve, alias: normalized } as Configuration['resolve'] | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Alias normalization may break legitimate webpack alias functionality.
The sanitization logic converts all alias values to strings, but this approach has several issues:
-
Object aliases (lines 66-72): Webpack supports object aliases with
{ name, alias, onlyModule }structure. Converting these to JSON strings will break the resolution. -
Function aliases (lines 73-77): Webpack uses function aliases for custom resolution logic. Replacing them with the function name string removes this functionality entirely.
-
Empty string fallbacks (lines 78-80, 92-94): Setting aliases to empty strings may cause webpack to attempt resolving empty paths, leading to unexpected errors.
-
Potential silent failures: Legitimate aliases might be silently converted to non-functional values without warnings.
Consider a more targeted approach that only removes truly non-serializable values while preserving valid string/path aliases:
💡 Suggested safer approach
if (typeof aliasObj === 'object' && aliasObj !== null) {
- const normalized: Record<string, string | string[]> = {}
+ const normalized: Record<string, string | string[] | false> = {}
for (const [k, v] of Object.entries(aliasObj as Record<string, unknown>)) {
if (Array.isArray(v)) {
- normalized[k] = v.map((x) => String(x))
+ // Only include if all elements are strings
+ if (v.every((x) => typeof x === 'string')) {
+ normalized[k] = v as string[]
+ }
+ // Skip non-string arrays (non-serializable)
- } else if (typeof v === 'object' && v !== null) {
- // For objects, stringify to avoid '[object Object]' implicit string coercion
- try {
- normalized[k] = JSON.stringify(v)
- } catch {
- normalized[k] = ''
- }
- } else if (typeof v === 'function') {
- // For functions, prefer the function name to avoid serializing the entire function
- // Narrow to an object with an optional name property to avoid using the broad Function type
- const fnName = (v as { name?: string })?.name ?? ''
- normalized[k] = fnName
- } else if (v === null || v === undefined) {
- // Keep null/undefined normalized to an empty string
- normalized[k] = ''
- } else {
- // At this point, expect primitives (string/number/boolean/symbol/bigint).
- // Guard against objects to avoid default Object stringification '[object Object]'.
- const t = typeof v
- if (t === 'string' || t === 'number' || t === 'boolean' || t === 'symbol' || t === 'bigint') {
- // Narrow the type for the linter to avoid base-to-string coercion warnings
- normalized[k] = String(v as string | number | boolean | symbol | bigint)
- } else {
- // Fallback for unexpected non-serializable values
- try {
- normalized[k] = JSON.stringify(v)
- } catch {
- normalized[k] = ''
- }
- }
+ } else if (typeof v === 'string') {
+ normalized[k] = v
+ } else if (v === false) {
+ // `false` is valid in webpack to ignore a module
+ normalized[k] = false
}
+ // Skip functions, objects, and other non-serializable values
+ // Log warning for skipped aliases in development
}
config.resolve = { ...existingResolve, alias: normalized } as Configuration['resolve']
}🤖 Prompt for AI Agents
In `@next.config.ts` around lines 56 - 99, The current alias sanitization in the
config.resolve block (aliasObj -> normalized -> config.resolve) indiscriminately
converts object and function aliases to strings and replaces null/invalid
entries with empty strings, which breaks valid webpack alias types; instead,
update the loop that builds normalized to: detect and preserve valid webpack
alias shapes (keep objects that match { name, alias, onlyModule } or other
object aliases), keep functions (do not stringify) but mark them as
non-cloneable so Turbopack gets a placeholder/removed entry, and only remove or
replace truly non-serializable values (e.g., circular objects) by deleting the
key or setting it to undefined; also emit a warning (console.warn or
processLogger.warn) mentioning the alias key when you drop/replace an alias so
failures aren’t silent. Ensure you update the code paths referencing aliasObj,
normalized, and config.resolve accordingly so only unsupported values are
stripped and valid objects/functions are preserved.
| "@xyflow/react": "^12.10.0", | ||
| "a2a-ai-provider": "^0.4.0-alpha.2", | ||
| "ai": "^5.0.121", | ||
| "ai": "^6.0.37", |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🌐 Web query:
vercel ai sdk version 6 breaking changes migration guide
💡 Result:
Summary of v6 breaking changes + migration steps
- Key changes to expect
- v6 implements the v3 Language Model Specification (agents, tool-calling, tool approval, structured outputs). This introduces new Agent abstractions (e.g., ToolLoopAgent) and updated tool APIs. [1][2]
- Some provider/package APIs and package versions were bumped; update ai and
@ai-sdk/* packages. [2] - Codemods are provided to automate most renames and API adjustments (v5 → v6). [2][3]
- Minimal migration steps
- Upgrade packages in package.json to the v6-compatible versions (ai@^6.0.0 and matching
@ai-sdk/* packages). [2] - Run the automated codemod from your project root: npx
@ai-sdk/codemodv6 (or run specific codemods). Review changes and commit. [2][3] - Update agent/tool usage to the new Agent abstractions (replace older generateText/streamText patterns where codemods didn’t cover manual agent integrations). Test tool approval flows and structured outputs. [1][2]
- Run your test suite, fix type/API errors, and verify runtime behavior (especially tool calls and streaming). Backup/branch before large changes. [2]
- Helpful links
- Vercel blog overview for AI SDK 6 (explains agents & high-level changes). [1]
- Official migration guide: “Migrate AI SDK 5.x to 6.0” (package list, codemod usage, recommended process). [2]
- Codemod release / changelog showing v5→v6 codemods. [3]
If you want, I can: run the exact codemod command and show the list of files it would change (dry-run), or extract the specific codemod names you’ll likely need based on a small sample of your code—which would let me give precise edit suggestions.
Sources:
[1] Vercel blog — AI SDK 6. (vercel.com)
[2] AI SDK migration guide — Migrate AI SDK 5.x to 6.0. (ai-sdk.dev)
[3] @ai-sdk/codemod release notes (v6 codemods). (newreleases.io)
Citations:
- 1: https://vercel.com/blog/ai-sdk-6?utm_source=openai
- 2: https://ai-sdk.dev/docs/migration-guides/migration-guide-6-0?utm_source=openai
- 3: https://newreleases.io/project/github/vercel/ai/release/%40ai-sdk/codemod%403.0.0?utm_source=openai
🏁 Script executed:
# Find files that import or use the ai package
rg "from\s+['\"]ai['\"]|require\(['\"]ai['\"]" --type ts --type tsx --type js --type jsx -A 3 -B 1Repository: ssdeanx/AgentStack
Length of output: 89
🏁 Script executed:
# Search for ai package usage patterns to understand compatibility
rg "generateObject|streamObject|generateText|streamText" --type ts --type tsx --type js --type jsx | head -20Repository: ssdeanx/AgentStack
Length of output: 89
🏁 Script executed:
# Search for ai package imports and usage
rg "from\s+['\"]ai['\"]|require\(['\"]ai['\"]" -A 5 -B 1 | head -50Repository: ssdeanx/AgentStack
Length of output: 4169
🏁 Script executed:
# Find TypeScript/JS files and check for ai package usage
fd -e ts -e js -e tsx -e jsx -x grep -l "from ['\"]ai['\"]" {} \;Repository: ssdeanx/AgentStack
Length of output: 1215
🏁 Script executed:
# Check if codemod has been applied by looking for v6 specific APIs (e.g., ToolLoopAgent)
rg "ToolLoopAgent|streamObject|generateObject" -A 2 -B 1 | head -30Repository: ssdeanx/AgentStack
Length of output: 698
🏁 Script executed:
# Check streamUtils.ts for ai package usage
cat -n ./src/utils/streamUtils.ts | head -100Repository: ssdeanx/AgentStack
Length of output: 3935
🏁 Script executed:
# Check the main API chat route
cat -n ./app/api/chat/route.ts | head -150Repository: ssdeanx/AgentStack
Length of output: 2328
🏁 Script executed:
# Search for generateText or streamText usage (v5 patterns)
rg "generateText|streamText|experimental_generateObject" -B 2 -A 5 | head -100Repository: ssdeanx/AgentStack
Length of output: 1623
Ensure ai v6 API migration is complete—breaking changes exist and a codemod is available.
The ai package v6 introduces significant breaking changes including new Agent abstractions and updated tool APIs. An official codemod (npx @ai-sdk/codemod v6) is available to automate the migration. The codebase is already using some v6 APIs (e.g., createUIMessageStream, createUIMessageStreamResponse), but verify all usages are compatible, particularly where documentation references v5 patterns (e.g., experimental_generateObject). Run the codemod, review generated changes, and test thoroughly to ensure tool-calling and streaming work as expected.
Also applies to: 255-255
🤖 Prompt for AI Agents
In `@package.json` at line 114, The package.json pin for "ai" was bumped to v6 but
the codebase may still use v5 patterns; run the official codemod (npx
`@ai-sdk/codemod` v6), then search and update all usages of ai APIs—notably
replace or verify createUIMessageStream, createUIMessageStreamResponse, and
remove/replace any experimental_generateObject calls—ensuring agent/tool calling
and streaming APIs follow v6 signatures; run tests and manual stream/tool flows,
review codemod changes, and fix any remaining type/signature mismatches reported
by the compiler or runtime.
| export type ColorChangeUITool = InferUITool<typeof colorChangeTool> | ||
| export type ContentCleanerUITool = InferUITool<typeof contentCleanerTool> | ||
| export type ConvertDataFormatUITool = InferUITool<typeof convertDataFormatTool> | ||
| //export type ConvertDataFormatUITool = InferUITool<typeof convertDataFormatTool> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🛠️ Refactor suggestion | 🟠 Major
Remove commented-out code instead of leaving it in place.
Per coding guidelines, commented-out code should be removed entirely rather than left in the codebase. Version control history preserves the removed code if needed later. Additionally, since convertDataFormatTool was removed from the imports, uncommenting this line would cause a compilation error.
🧹 Proposed fix
-//export type ConvertDataFormatUITool = InferUITool<typeof convertDataFormatTool>📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| //export type ConvertDataFormatUITool = InferUITool<typeof convertDataFormatTool> |
🤖 Prompt for AI Agents
In `@src/components/ai-elements/tools/types.ts` at line 173, Remove the
commented-out export line referencing ConvertDataFormatUITool in types.ts;
delete the line "//export type ConvertDataFormatUITool = InferUITool<typeof
convertDataFormatTool>" so no stale/commented code remains (the symbol
ConvertDataFormatUITool and the now-unimported convertDataFormatTool should not
be referenced); rely on VCS history if this type needs restoring later.
| const content = output.content || {} | ||
| const { | ||
| extractedData, | ||
| rawContent, | ||
| markdownContent, | ||
| } = content | ||
|
|
||
| const { | ||
| metadata, | ||
| images, | ||
| structuredData, | ||
| } = output | ||
| } = output.analysis || {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Runtime crash: extractedData can be undefined when output.content is missing.
When output.content is undefined, the fallback {} yields undefined for extractedData. This causes TypeError at lines 93, 145, and 151 where .length and .map() are called without null checks.
🐛 Proposed fix: provide default values during destructuring
const content = output.content || {}
const {
- extractedData,
+ extractedData = [],
rawContent,
markdownContent,
} = content
const {
metadata,
images,
- structuredData,
+ structuredData, // Note: currently unused - consider removing
} = output.analysis || {}🤖 Prompt for AI Agents
In `@src/components/ai-elements/tools/web-scraper-tool.tsx` around lines 67 - 78,
The crash happens because destructuring from output.content and output.analysis
can yield undefined values (e.g., extractedData), so update the destructuring
where output.content and output.analysis are read to provide safe defaults (for
example: extractedData = [], rawContent = '', markdownContent = '' and metadata
= {}, images = [], structuredData = {}), and ensure any later uses of .length or
.map (references: extractedData, images) rely on these defaults or have null
checks before calling .length/.map so the code in web-scraper-tool.tsx no longer
throws when output.content or output.analysis are missing.
| structuredData, | ||
| } = output | ||
| } = output.analysis || {} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 Nitpick | 🔵 Trivial
Unused variable: structuredData is destructured but never used.
Remove the unused variable to satisfy the no-unused-vars rule. As per coding guidelines, all unused variable declarations should be removed.
🧹 Proposed fix
const {
metadata,
images,
- structuredData,
} = output.analysis || {}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| structuredData, | |
| } = output | |
| } = output.analysis || {} | |
| const { | |
| metadata, | |
| images, | |
| } = output.analysis || {} |
🤖 Prompt for AI Agents
In `@src/components/ai-elements/tools/web-scraper-tool.tsx` around lines 77 - 78,
Remove the unused destructured variable `structuredData` from the destructuring
of `output.analysis` (where `structuredData, } = output.analysis || {}` appears)
so the `no-unused-vars` rule is satisfied; update the destructuring to only
capture the used properties (or omit `output.analysis` entirely if none are
used) in the `web-scraper-tool` component.
| import type { InferUITool } from '@mastra/core/tools' | ||
| import { createTool } from '@mastra/core/tools' | ||
| import { z } from 'zod' | ||
| import { evaluate } from 'mathjs' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
fd calculator.tool.tsRepository: ssdeanx/AgentStack
Length of output: 97
🏁 Script executed:
cat -n src/mastra/tools/calculator.tool.ts | head -160Repository: ssdeanx/AgentStack
Length of output: 4734
🌐 Web query:
mathjs evaluate security sandbox arbitrary code execution arbitrary expressions
💡 Result:
Short answer: mathjs’s expression parser is designed as a sandbox but has had real arbitrary-code-execution and prototype-pollution vulnerabilities in the past — so treating it as fully safe by default is unsafe. Use hardened configuration, strict scoping, process isolation, and keep the package patched. [1][2][3][4]
What to do (concise mitigations)
- Upgrade to a non‑vulnerable mathjs release (patches exist for known RCEs). Verify your installed version against advisories. [3][4]
- Disable high‑risk functions (import, createUnit, evaluate/parse/simplify/derivative) by overriding them in math.import before exposing user input. Example pattern shown in the official docs. [2]
- Provide a strict scope (use a Map or object) and never pass untrusted function objects in the scope; validate/whitelist allowed identifiers. [1][4]
- Run expression evaluation in an isolated worker/child process (or container) with time/memory limits so heavy or malicious expressions can’t crash or access main process secrets. [1]
- Defend against prototype/property attacks: validate keys and disallow weird/unicode property names; keep dependency transitive fixes updated. [4]
- If you need maximal assurance, avoid server‑side evaluation of user expressions entirely or use an external sandbox service/VM.
Sources
- mathjs security docs (official guidance + sandbox notes). [1]
- mathjs example: disabling risky functions (more_secure_eval). [2]
- CVE-2017-1001002 (historical arbitrary code execution). [3]
- Snyk advisories summarizing multiple mathjs RCE/PP issues and recommended versions. [4]
If you want, tell me: your mathjs version and whether evaluations run server‑side or in-browser — I’ll give exact upgrade/mitigation commands and a minimal safe example.
Disable high-risk mathjs functions and add resource limits to prevent expression evaluation exploits.
The mathjs.evaluate() function has had real arbitrary-code-execution vulnerabilities (CVE-2017-1001002). While the code limits the context to MATH_CONSTANTS and MATH_FUNCTIONS, this basic scoping is insufficient. Implement these mitigations:
- Explicitly disable high-risk functions by overriding them in the context before calling
evaluate()(import, createUnit, parse, simplify, derivative) - Verify mathjs version is patched against known RCE advisories
- Add expression validation: length limits (already present in
CalculatorToolContext.maxExpressionLength) and whitelist allowed identifiers - Enforce resource limits: timeout and complexity constraints to prevent expression bombs
- Validate context object keys to prevent prototype pollution attacks
The current context-scoping approach provides baseline protection but requires explicit hardening per mathjs security guidance.
🤖 Prompt for AI Agents
In `@src/mastra/tools/calculator.tool.ts` at line 7, The mathjs evaluate usage
must be hardened: before calling evaluate() in the Calculator tool, explicitly
override high-risk functions (import, createUnit, parse, simplify, derivative)
in the evaluation context to no-op/throw; verify the installed mathjs version at
runtime or in package metadata is not a vulnerable release; enforce expression
validation by checking CalculatorToolContext.maxExpressionLength and rejecting
expressions containing identifiers not in your whitelist (combine with existing
MATH_CONSTANTS and MATH_FUNCTIONS); add resource limits by using mathjs evaluate
options or a wrapper to enforce a timeout and a complexity check (e.g.,
node-side AST traversal/operation-count limit) to prevent expression bombs; and
validate keys on the context object (reject prototypes or keys like __proto__,
constructor) to prevent prototype pollution before passing the context to
evaluate(). Ensure these changes touch the evaluate call site and the context
construction logic that references MATH_CONSTANTS, MATH_FUNCTIONS, and
CalculatorToolContext.maxExpressionLength.
| ), | ||
| count: z.number(), | ||
| }), | ||
|
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 Nitpick | 🔵 Trivial
Extraneous whitespace.
Minor formatting issue - there's an extra blank line before the execute function.
🤖 Prompt for AI Agents
In `@src/mastra/tools/calendar-tool.ts` at line 400, Remove the extraneous blank
line immediately before the execute function declaration in the CalendarTool
implementation (the execute method) so the method is directly adjacent to the
preceding code; after removing the blank line, run the project's formatter
(Prettier/ESLint --fix) to ensure consistent formatting.
| const macdResult = (MACD.calculate({ | ||
| fastPeriod: ind.fastPeriod ?? 12, | ||
| slowPeriod: ind.slowPeriod ?? 26, | ||
| signalPeriod: ind.signalPeriod ?? 9, | ||
| values: closePrices, | ||
| SimpleMAOscillator: false, | ||
| SimpleMASignal: false, | ||
| }) | ||
| const macd = macdResult.map((m) => m.MACD) | ||
| const signal = macdResult.map((m) => m.signal) | ||
| const histogram = macdResult.map((m) => m.histogram) | ||
| }) ?? []) as Array<Record<string, unknown>> | ||
|
|
||
| // Ensure the mapped series are typed as numbers to avoid `any[]` assignments | ||
| const macd = macdResult.map((m: Record<string, unknown>) => | ||
| Number((m.MACD) as number) | ||
| ) | ||
| const signal = macdResult.map((m: Record<string, unknown>) => | ||
| Number((m.signal) as number) | ||
| ) | ||
| const histogram = macdResult.map((m: Record<string, unknown>) => | ||
| Number((m.histogram) as number) | ||
| ) | ||
|
|
||
| const padding = Array( | ||
| closePrices.length - macd.length | ||
| ).fill(null) | ||
| ).fill(null) as Array<number | null> |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧹 Nitpick | 🔵 Trivial
Redundant Number() conversion on already-cast values.
The pattern Number((m.MACD) as number) is redundant - if the value is already cast as number, wrapping it in Number() is unnecessary. The cast alone would suffice to satisfy TypeScript.
♻️ Simplified approach
- const macd = macdResult.map((m: Record<string, unknown>) =>
- Number((m.MACD) as number)
- )
- const signal = macdResult.map((m: Record<string, unknown>) =>
- Number((m.signal) as number)
- )
- const histogram = macdResult.map((m: Record<string, unknown>) =>
- Number((m.histogram) as number)
- )
+ const macd = macdResult.map((m) => m.MACD as number)
+ const signal = macdResult.map((m) => m.signal as number)
+ const histogram = macdResult.map((m) => m.histogram as number)🤖 Prompt for AI Agents
In `@src/mastra/tools/chartjs.tool.ts` around lines 231 - 253, The map conversions
use redundant Number(...) around already-cast values; update the mappings for
macd, signal, and histogram to directly cast the properties from macdResult
(e.g., m.MACD as number, m.signal as number, m.histogram as number) instead of
wrapping them with Number(), keeping the same variable names (macdResult, macd,
signal, histogram) and ensuring the resulting arrays are typed as number[] or
(number | null)[] consistent with closePrices and the padding logic.
| default: | ||
| throw new Error(`Unknown operation: ${operation}`) | ||
| throw new Error(`Unknown operation: `) | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Bug: Error message is incomplete — missing the operation value.
The error message string is truncated and doesn't include the actual unknown operation, making debugging difficult.
🐛 Proposed fix
default:
- throw new Error(`Unknown operation: `)
+ throw new Error(`Unknown operation: ${operation}`)📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| default: | |
| throw new Error(`Unknown operation: ${operation}`) | |
| throw new Error(`Unknown operation: `) | |
| } | |
| default: | |
| throw new Error(`Unknown operation: ${operation}`) | |
| } |
🤖 Prompt for AI Agents
In `@src/mastra/tools/text-analysis.tool.ts` around lines 391 - 393, The thrown
error in the default case currently uses a truncated message ("Unknown
operation: ") which omits the actual operation value; update the default branch
in the switch (the block that throws new Error(`Unknown operation: `)) to
include the operation variable (e.g., `operation` or whatever identifier is
being switched on) in the error message so the thrown Error reads something like
"Unknown operation: <operationValue>" to aid debugging.
| import { marked } from 'marked' | ||
| import * as fs from 'node:fs/promises' | ||
| import * as path from 'node:path' | ||
| import { inspect } from 'node:util' |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unused import detected.
The inspect function from node:util is imported but never used in this file. Remove unused imports to reduce bundle size and improve code clarity.
🧹 Proposed fix
-import { inspect } from 'node:util'📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| import { inspect } from 'node:util' |
🤖 Prompt for AI Agents
In `@src/mastra/tools/web-scraper-tool.ts` at line 51, Remove the unused import
"inspect" from "node:util" in the imports of the web-scraper-tool module: locate
the import line that reads "import { inspect } from 'node:util'" and delete it
(or remove "inspect" from the import specifier) so the file no longer imports an
unused symbol.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Pull request overview
This pull request focuses on improving type safety and code quality across the codebase by replacing any types with explicit type definitions, removing unsafe type assertions, and updating dependencies. The changes span tool implementations, React components, Next.js configuration, and Convex schema definitions.
Changes:
- Upgraded major dependencies (
aifrom v5 to v6,convexfrom v1.26 to v1.31,@types/nodedowngraded from v24 to v22) - Replaced
anytypes with explicit TypeScript types across multiple tool files - Improved error handling with proper type guards
- Refactored webpack configuration to handle alias serialization
- Updated Convex schema to include explicit field definitions
Reviewed changes
Copilot reviewed 21 out of 23 changed files in this pull request and generated 14 comments.
Show a summary per file
| File | Description |
|---|---|
| package.json | Updated ai, convex, @types/node versions; added mathjs dependency |
| src/mastra/tools/web-scraper-tool.ts | Improved type safety for JSDOM, enqueueLinks, XML export, and JSON parsing |
| src/mastra/tools/weather-tool.ts | Fixed tracingContext reference |
| src/mastra/tools/text-analysis.tool.ts | Fixed tracingContext and removed error message content |
| src/mastra/tools/technical-analysis.tool.ts | Replaced any types with explicit types |
| src/mastra/tools/code-*.ts | Fixed tracingContext references |
| src/mastra/tools/chartjs.tool.ts | Added explicit typing for indicator data arrays |
| src/mastra/tools/calendar-tool.ts | Removed mastra: (globalThis as any).mastra and moved hook definitions |
| src/mastra/tools/calculator.tool.ts | Replaced custom eval with mathjs evaluate |
| src/mastra/tools/arxiv.tool.ts | Improved error handling and type safety |
| src/components/ai-elements/tools/*.tsx | Fixed component naming and property access |
| next.config.ts | Added webpack alias normalization logic |
| mdx-components.tsx | Improved type safety for MDX component props |
| convex/schema.ts | Added explicit mastraWorkflowSnapshotsTable definition |
| convex.json | Changed Node version from 24 to 20 |
| break | ||
| default: | ||
| throw new Error(`Unknown operation: ${operation}`) | ||
| throw new Error(`Unknown operation: `) |
Copilot
AI
Jan 15, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The error message is missing the operation value that caused the error. This makes debugging impossible as you cannot identify which operation was invalid.
| throw new Error(`Unknown operation: `) | |
| throw new Error(`Unknown operation: ${operation}`) |
| (err && | ||
| typeof err === 'object' && | ||
| 'code' in err && | ||
| (err as any).code === 'ERR_CANCELED') ?? |
Copilot
AI
Jan 15, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The nullish coalescing operator (??) has incorrect precedence here. The condition should use logical OR (||) instead. The current code will always evaluate to true when the Error check passes, even if the first condition is false (not just nullish).
| (err as any).code === 'ERR_CANCELED') ?? | |
| (err as any).code === 'ERR_CANCELED') || |
|
|
||
| // Helper to safely detect cancellation errors without using `any` | ||
| function isErrCanceled(err: unknown): boolean { | ||
| if (err instanceof Error && err.name === 'AbortError') {return true} |
Copilot
AI
Jan 15, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing space after return statement. The closing brace should be on a new line to match the project's code style.
| if (err instanceof Error && err.name === 'AbortError') {return true} | |
| if (err instanceof Error && err.name === 'AbortError') { | |
| return true | |
| } |
| const context = { ...createSafeContext(), ...variables } | ||
| const func = new Function(...Object.keys(context), `return ${cleanExpr}`) | ||
|
|
||
| try { | ||
| const result = func(...Object.values(context)) | ||
| const result = evaluate(expression, context) |
Copilot
AI
Jan 15, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Using mathjs evaluate() with user-provided context variables could be unsafe if the variables contain malicious values. The createSafeContext() function is merged with user variables, potentially allowing context pollution. Consider validating that variables only contain numeric values.
| import { marked } from 'marked' | ||
| import * as fs from 'node:fs/promises' | ||
| import * as path from 'node:path' | ||
| import { inspect } from 'node:util' |
Copilot
AI
Jan 15, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The 'inspect' import from 'node:util' is added but never used in the file. This should be removed to avoid unused imports.
| import { inspect } from 'node:util' |
| }) ?? []) as Array<Record<string, unknown>> | ||
|
|
||
| // Ensure the mapped series are typed as numbers to avoid `any[]` assignments | ||
| const macd = macdResult.map((m: Record<string, unknown>) => | ||
| Number((m.MACD) as number) | ||
| ) | ||
| const signal = macdResult.map((m: Record<string, unknown>) => | ||
| Number((m.signal) as number) | ||
| ) | ||
| const histogram = macdResult.map((m: Record<string, unknown>) => | ||
| Number((m.histogram) as number) |
Copilot
AI
Jan 15, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Redundant type assertion: casting to number and then wrapping with Number() is unnecessary. If m.MACD is already typed as number, just use Number(m.MACD) without the assertion.
| }) ?? []) as Array<Record<string, unknown>> | |
| // Ensure the mapped series are typed as numbers to avoid `any[]` assignments | |
| const macd = macdResult.map((m: Record<string, unknown>) => | |
| Number((m.MACD) as number) | |
| ) | |
| const signal = macdResult.map((m: Record<string, unknown>) => | |
| Number((m.signal) as number) | |
| ) | |
| const histogram = macdResult.map((m: Record<string, unknown>) => | |
| Number((m.histogram) as number) | |
| }) ?? []) as Array<{ MACD: number; signal: number; histogram: number }> | |
| // Ensure the mapped series are typed as numbers to avoid `any[]` assignments | |
| const macd = macdResult.map((m) => | |
| Number(m.MACD) | |
| ) | |
| const signal = macdResult.map((m) => | |
| Number(m.signal) | |
| ) | |
| const histogram = macdResult.map((m) => | |
| Number(m.histogram) |
| // createToneScorer, | ||
| //} from '../evals/scorers/prebuilt' | ||
| import { chartSupervisorTool } from '../tools/financial-chart-tools' | ||
| import { convexMemory } from '../config/convex' |
Copilot
AI
Jan 15, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
'convexMemory' is defined but never used.
| import { convexMemory } from '../config/convex' |
| } | ||
| } | ||
| } catch { | ||
| } catch (err) { |
Copilot
AI
Jan 15, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
'err' is defined but never used.
| } catch (err) { | |
| } catch { |
| (err && | ||
| typeof err === 'object' && | ||
| 'code' in err && | ||
| (err as any).code === 'ERR_CANCELED') ?? |
Copilot
AI
Jan 15, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Unexpected any. Specify a different type.
| (err as any).code === 'ERR_CANCELED') ?? | |
| (err as { code?: string }).code === 'ERR_CANCELED') ?? |
| opts?: { contentType?: string; includeNodeLocations?: boolean } | ||
| ) => JSDOM | ||
| return new Ctor(html, options) | ||
| } catch (e) { |
Copilot
AI
Jan 15, 2026
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
'e' is defined but never used.
| } catch (e) { | |
| } catch { |

No description provided.