Skip to content

feat: enhance tools with improved logging and context handling - #77

Merged
ssdeanx merged 1 commit into
mainfrom
develop
Jan 8, 2026
Merged

ssdeanx merged 1 commit into
mainfrom
develop

Conversation

@ssdeanx

@ssdeanx ssdeanx commented Jan 8, 2026

Copy link
Copy Markdown
Owner
  • Updated polygon-tools.ts to use nullish coalescing operator for better default value handling.
  • Refactored random-generator.tool.ts to improve context handling and logging, including removing redundant logging statements.
  • Enhanced text-analysis.tool.ts by introducing a new context interface and improving error logging.
  • Updated url-tool.ts to improve context handling and added detailed logging for input and output events.
  • Improved weather-tool.ts by refining context management and enhancing logging for input and output events.
  • Refactored web-scraper-tool.ts to simplify cancellation checks during crawling.
  • Enhanced write-note.ts with improved logging for input and output events.
  • Added a new GitHub Actions workflow for opencode functionality to automate code reviews and comments.

- Updated polygon-tools.ts to use nullish coalescing operator for better default value handling.
- Refactored random-generator.tool.ts to improve context handling and logging, including removing redundant logging statements.
- Enhanced text-analysis.tool.ts by introducing a new context interface and improving error logging.
- Updated url-tool.ts to improve context handling and added detailed logging for input and output events.
- Improved weather-tool.ts by refining context management and enhancing logging for input and output events.
- Refactored web-scraper-tool.ts to simplify cancellation checks during crawling.
- Enhanced write-note.ts with improved logging for input and output events.
- Added a new GitHub Actions workflow for opencode functionality to automate code reviews and comments.
Copilot AI review requested due to automatic review settings January 8, 2026 11:39
@continue

continue Bot commented Jan 8, 2026

Copy link
Copy Markdown

All Green - Keep your PRs mergeable

Learn more

All Green is an AI agent that automatically:

✅ Addresses code review comments

✅ Fixes failing CI checks

✅ Resolves merge conflicts


Unsubscribe from All Green comments

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @ssdeanx, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@github-actions

github-actions Bot commented Jan 8, 2026

Copy link
Copy Markdown

🤖 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.

@coderabbitai

coderabbitai Bot commented Jan 8, 2026 •

Copy link
Copy Markdown

Caution

Review failed

The pull request is closed.

Summary by CodeRabbit

  • New Features

    • Added specialized subagents (Next.js Developer, React Engineer, QA-Agent, etc.)
    • Added GitHub Actions workflow for OpenCode integration
    • Added streaming lifecycle hooks to tools for enhanced observability
    • Added explicit context interfaces for improved tool configuration handling
  • Documentation

    • Expanded tool creation and RequestContext usage patterns
  • Bug Fixes

    • Improved abortSignal handling with safer optional chaining
    • Enhanced error logging across tools
  • Chores

    • Removed obsolete OTEL instrumentation
    • Updated dependencies to newer beta versions
    • Adjusted token limits and memory configurations
    • Reorganized tool hook declarations for consistency

✏️ Tip: You can customize this high-level summary in your review settings.

Walkthrough

Multi-file refactoring migrating tool context handling from Zod schemas to explicit interfaces extending RequestContext, reorganizing lifecycle hooks placement, and removing Vercel OTEL instrumentation. Includes new GitHub Actions workflow for opencode integration, dependency version updates, and reduced token limit in ACP agent.

Changes

Cohort / File(s) Summary
GitHub & Workflow Configuration
.github/agents/gpt-5-beast-mode.agent.md, .github/workflows/opencode.yml
Added new subagents section with specialized agent invocations (Expert Next.js Developer, QA-Agent, etc.); expanded tool namespaces. Introduced new opencode GitHub Actions workflow triggered on issue/PR comment commands (/oc, /opencode).
Instrumentation & Core Config
src/instrumentation.ts, src/mastra/index.ts, src/mastra/agents/acpAgent.ts
Removed Vercel OTEL integration file. Removed explicit readOnly: false from chatRoute memory configs. Reduced ACP agent token limit from 1048576 to 128576.
Dependency Management
package.json
Bumped project version to 1.1.1. Updated Mastra packages to newer beta versions (beta.13), updated @ai-sdk/react, framer-motion, motion, and body-parser overrides.
Tool Context Refactoring
src/mastra/tools/calculator.tool.ts, src/mastra/tools/datetime.tool.ts, src/mastra/tools/git-local.tool.ts, src/mastra/tools/text-analysis.tool.ts, src/mastra/tools/url-tool.ts, src/mastra/tools/weather-tool.ts
Replaced Zod-based context schemas with explicit interfaces extending RequestContext. Added optional context fields (defaultTimezone, allowLocalhost, temperatureUnit, etc.) with sensible defaults. Updated execute logic to read from context.requestContext.
Tool Hook Reorganization
src/mastra/tools/alpha-vantage.tool.ts, src/mastra/tools/copywriter-agent-tool.ts, src/mastra/tools/fs.ts, src/mastra/tools/jwt-auth.tool.ts, src/mastra/tools/write-note.ts
Relocated or reintroduced lifecycle hooks (onInputStart, onInputDelta, onInputAvailable, onOutput) to positions after execute methods. Updated hook logging payloads with enriched data (abortSignal status, input/output details).
Tool Safety & Cleanup
src/mastra/tools/color-change-tool.ts, src/mastra/tools/polygon-tools.ts, src/mastra/tools/random-generator.tool.ts, src/mastra/tools/web-scraper-tool.ts
Removed duplicate execute implementations; standardized abort signal checks using optional chaining (abortSignal?.aborted). Replaced logical OR (`
Documentation
src/mastra/tools/AGENTS.md
Expanded tool creation documentation with lifecycle hook guidance, RequestContext usage patterns, hook generator utility examples, and implementation checklists.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • Develop #76: Overlapping tool refactoring changes across multiple Mastra tool modules with similar context interface migrations and lifecycle hook reorganization patterns.
  • Develop #52: Shared modifications to the same tool implementations regarding RequestContext usage, lifecycle hooks, and streaming progress conventions.
  • feat: update querySimilarDocuments function to specify result type #26: Related changes to the same agent configuration file (.github/agents/gpt-5-beast-mode.agent.md) affecting agent metadata and tool definitions.

Poem

🐰 Refactoring tools with graceful might,
From schemas Zod to contexts bright,
Hooks relocated in their place,
Context flows through every space,
Safer signals, cleaner code—
Mastra hops along the road!

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch develop

📜 Recent review details

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 681668a and 48b5949.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (22)
  • .github/agents/gpt-5-beast-mode.agent.md
  • .github/workflows/opencode.yml
  • instrumentation.ts
  • package.json
  • src/mastra/agents/acpAgent.ts
  • src/mastra/index.ts
  • src/mastra/tools/AGENTS.md
  • src/mastra/tools/alpha-vantage.tool.ts
  • src/mastra/tools/calculator.tool.ts
  • src/mastra/tools/color-change-tool.ts
  • src/mastra/tools/copywriter-agent-tool.ts
  • src/mastra/tools/datetime.tool.ts
  • src/mastra/tools/fs.ts
  • src/mastra/tools/git-local.tool.ts
  • src/mastra/tools/jwt-auth.tool.ts
  • src/mastra/tools/polygon-tools.ts
  • src/mastra/tools/random-generator.tool.ts
  • src/mastra/tools/text-analysis.tool.ts
  • src/mastra/tools/url-tool.ts
  • src/mastra/tools/weather-tool.ts
  • src/mastra/tools/web-scraper-tool.ts
  • src/mastra/tools/write-note.ts

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@greptile-apps greptile-apps Bot left a comment

Copy link
Copy Markdown

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.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @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 focuses on a comprehensive enhancement of the existing toolset, primarily by standardizing and improving logging practices, refining context handling mechanisms, and updating core dependencies. The changes aim to increase the observability, maintainability, and robustness of the tools, making them more reliable and easier to debug. Additionally, agent configurations and tool development documentation have been updated to reflect these improvements and introduce new capabilities.

Highlights

  • Enhanced Tool Logging & Context Handling: Significant refactoring across multiple tools (e.g., random-generator, text-analysis, url-tool, weather-tool, calculator, datetime, git-local) to standardize logging with detailed input/output events and improve context management using a new RequestContext interface.
  • Dependency Updates: Upgraded various @mastra and @ai-sdk packages, along with framer-motion, motion, and body-parser to their latest versions, and updated the project version to 1.1.1.
  • Simplified Cancellation Checks: Refined logic for abort signals in fs, jwt-auth, polygon-tools, web-scraper, and weather-tool for cleaner and more robust cancellation handling.
  • Improved Code Robustness: Introduced nullish coalescing operators (??) for better default value handling and enhanced error logging with more contextual information in several tools.
  • Agent Configuration Updates: The GPT 5 Beast Mode agent now includes new tools (ast-grep-mcp, uv-toolkit) and documentation for subagents, while acpAgent's token limiter was adjusted and readOnly: false was removed from agent configurations.
  • Documentation for Tool Development: The AGENTS.md file has been updated with comprehensive guidelines for createTool() usage, including lifecycle hooks and RequestContext patterns, and a new requirement for hook declaration order.
  • Removed OTEL Instrumentation: The instrumentation.ts file, which handled Vercel OTEL configuration, has been removed, centralizing OTEL configuration within Mastra.
Ignored Files
  • Ignored by pattern: .github/workflows/** (1)
    • .github/workflows/opencode.yml
Using Gemini Code Assist

The 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 /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

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 .gemini/ folder in the base of the repository. Detailed instructions can be found here.

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

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@github-actions

github-actions Bot commented Jan 8, 2026

Copy link
Copy Markdown

🤖 I'm sorry @ssdeanx, but I was unable to process your request. Please see the logs for more details.

@ssdeanx
ssdeanx merged commit 70a6fd2 into main Jan 8, 2026
24 of 31 checks passed

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

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 series of valuable enhancements across multiple tools, focusing on improved logging, standardized context handling, and better type safety. The refactoring to move lifecycle hooks after the execute function and the adoption of typed RequestContext interfaces are great changes that improve consistency and maintainability. The move to structured logging is also a welcome improvement for observability.

I've identified a few minor issues, mainly related to unused variables and a missing type definition, which should be straightforward to address. Overall, this is a solid set of improvements that enhances the quality and robustness of the toolset.

},
execute: async (inputData, context) => {
const writer = context?.writer
const requestContext = context?.requestContext as RandomGeneratorRequestContext

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

The type RandomGeneratorRequestContext is used in the type assertion as RandomGeneratorRequestContext, but it is not defined or imported in this file. This will cause a compilation error. Please define this interface or import it from its source location. Based on changes in other files, you should add the following before the randomGeneratorTool definition:

import type { RequestContext } from '@mastra/core/request-context';

export interface RandomGeneratorRequestContext extends RequestContext {
  locale?: string;
}

const requestCtx = context?.requestContext as DateTimeToolContext | undefined
const defaultTimezone = requestCtx?.defaultTimezone ?? 'UTC'
const defaultLocale = requestCtx?.defaultLocale ?? 'en-US'
const allowFutureDates = requestCtx?.allowFutureDates ?? true

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The allowFutureDates variable is extracted from the context but is never used within the execute function. The log message at line 99 suggests this might be to avoid a linter warning, but it indicates dead code. If this flag is intended to be used for date validation (e.g., in the 'parse' or 'add' operations), that logic should be implemented. Otherwise, the variable and its extraction should be removed to improve code clarity.

error: z.string().optional(),
}),
execute: async (inputData, context) => {
const startTime = Date.now()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The startTime variable is declared but never used within the execute function of polygonCryptoAggregatesTool. This appears to be dead code and should be removed to improve code clarity.

error: z.string().optional(),
}),
execute: async (inputData, context) => {
const startTime = Date.now()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The startTime variable is declared but never used within the execute function of polygonCryptoSnapshotsTool. This appears to be dead code and should be removed to improve code clarity.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

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 refactors tool implementations to improve context handling and logging consistency across the Mastra toolset. The key changes include:

  • Replacing Zod-based context schemas with TypeScript interfaces for better type safety and reduced runtime overhead
  • Adopting nullish coalescing operator (??) for more precise default value handling
  • Reordering lifecycle hooks to follow the documented pattern (execute before hooks)
  • Adding comprehensive RequestContext documentation
  • Updating multiple Mastra and dependency packages to latest beta versions
  • Adding a new GitHub Actions workflow for OpenCode functionality
  • Removing obsolete instrumentation.ts file

Reviewed changes

Copilot reviewed 22 out of 23 changed files in this pull request and generated 11 comments.

Show a summary per file
File Description
src/mastra/tools/write-note.ts Reordered lifecycle hooks to come after execute function
src/mastra/tools/web-scraper-tool.ts Simplified abort signal checks using nullish coalescing
src/mastra/tools/weather-tool.ts Refactored from Zod schema to TypeScript interface for context, added abortSignal to fetch calls
src/mastra/tools/url-tool.ts Replaced Zod schema with TypeScript interface, improved type safety with explicit union types
src/mastra/tools/text-analysis.tool.ts Migrated to interface-based context, enhanced error logging, improved code formatting
src/mastra/tools/random-generator.tool.ts Adopted nullish coalescing throughout, removed redundant logging
src/mastra/tools/polygon-tools.ts Applied nullish coalescing for cleaner default handling
src/mastra/tools/jwt-auth.tool.ts Reordered hooks after execute, improved nullish coalescing usage
src/mastra/tools/git-local.tool.ts Migrated to TypeScript interface, standardized tracer versioning, improved type annotations
src/mastra/tools/fs.ts Reordered lifecycle hooks, simplified abort signal checks
src/mastra/tools/datetime.tool.ts Replaced Zod schema with interface, added context value logging
src/mastra/tools/copywriter-agent-tool.ts Reordered lifecycle hooks consistently
src/mastra/tools/color-change-tool.ts Moved execute function before lifecycle hooks
src/mastra/tools/calculator.tool.ts Migrated to interface-based context, improved formatting and type safety
src/mastra/tools/alpha-vantage.tool.ts Reordered hooks for consistency
src/mastra/tools/AGENTS.md Added comprehensive createTool() documentation and RequestContext usage patterns
src/mastra/index.ts Removed readOnly property from agent memory configurations
src/mastra/agents/acpAgent.ts Adjusted TokenLimiterProcessor value from 1048576 to 128576
package.json Updated version to 1.1.1, upgraded multiple @mastra/* packages and dependencies
package-lock.json Synchronized lockfile with package.json changes
instrumentation.ts Removed entire file (Vercel OTEL configuration)
.github/workflows/opencode.yml Added new workflow for OpenCode comment-triggered functionality
.github/agents/gpt-5-beast-mode.agent.md Updated tool list and added subagent documentation

)
const requestCtx = context?.requestContext as CalculatorToolContext | undefined
const precision = requestCtx?.precision ?? 6
const allowComplexExpressions = requestCtx?.allowComplexExpressions ?? true

Copilot AI Jan 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'allowComplexExpressions' is assigned a value but never used.

Suggested change
const allowComplexExpressions = requestCtx?.allowComplexExpressions ?? true

Copilot uses AI. Check for mistakes.
@@ -545,9 +544,9 @@ export const gitCommitTool = createTool({
const writer = context?.writer
const requestContext = context?.requestContext

Copilot AI Jan 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'requestContext' is assigned a value but never used.

Suggested change
const requestContext = context?.requestContext

Copilot uses AI. Check for mistakes.
@@ -771,9 +770,9 @@ export const gitLogTool = createTool({
const writer = context?.writer
const requestContext = context?.requestContext

Copilot AI Jan 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'requestContext' is assigned a value but never used.

Suggested change
const requestContext = context?.requestContext

Copilot uses AI. Check for mistakes.
try {
const cwd = inputData.repoPath || process.cwd()
const cwd = inputData.repoPath ?? process.cwd()
let result: any = {}

Copilot AI Jan 8, 2026

Copy link

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.

Suggested change
let result: any = {}
let result: Record<string, unknown> = {}

Copilot uses AI. Check for mistakes.
hook: 'onInputDelta',
})
},
onInputAvailable: ({ input, toolCallId, messages, abortSignal }) => {

Copilot AI Jan 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'input' is defined but never used.

Suggested change
onInputAvailable: ({ input, toolCallId, messages, abortSignal }) => {
onInputAvailable: ({ toolCallId, messages, abortSignal }) => {

Copilot uses AI. Check for mistakes.
import { trace } from '@opentelemetry/api'
import { z } from 'zod'
import { log } from '../config/logger'
import { log, logError } from '../config/logger'

Copilot AI Jan 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'logError' is defined but never used.

Suggested change
import { log, logError } from '../config/logger'
import { log } from '../config/logger'

Copilot uses AI. Check for mistakes.
import { log, logError } from '../config/logger'

// Define the Zod schema for the runtime context
const randomToolContextSchema = z.object({

Copilot AI Jan 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'randomToolContextSchema' is assigned a value but only used as a type.

Copilot uses AI. Check for mistakes.
execute: async (inputData, context) => {
const writer = context?.writer
const requestContext = context?.requestContext as RandomGeneratorRequestContext
const localeFromContext = requestContext?.locale ?? 'en'

Copilot AI Jan 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'localeFromContext' is assigned a value but never used.

Suggested change
const localeFromContext = requestContext?.locale ?? 'en'

Copilot uses AI. Check for mistakes.
@@ -407,6 +408,7 @@ function countParagraphs(text: string): number {
}

function calculateReadability(text: string, language: string) {

Copilot AI Jan 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'language' is defined but never used.

Suggested change
function calculateReadability(text: string, language: string) {
function calculateReadability(text: string, language: string) {
log.debug('Calculating readability', { language })

Copilot uses AI. Check for mistakes.
@@ -457,6 +459,7 @@ function calculateReadability(text: string, language: string) {
}

function analyzeSentiment(text: string, language: string) {

Copilot AI Jan 8, 2026

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

'language' is defined but never used.

Copilot uses AI. Check for mistakes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants