Skip to content

feat: Enhance tools with improved context handling and logging#78

Merged
ssdeanx merged 1 commit intomainfrom
develop
Jan 8, 2026
Merged

feat: Enhance tools with improved context handling and logging#78
ssdeanx merged 1 commit intomainfrom
develop

Conversation

@ssdeanx
Copy link
Owner

@ssdeanx ssdeanx commented Jan 8, 2026

  • Added a new gitToolContextSchema to define optional properties for Git tools, including defaultBranch, allowForce, allowAmend, maxCommits, and timeout.
  • Updated the cwd assignment in multiple Git tools to use nullish coalescing (??) for better handling of undefined values.
  • Improved timeout handling in the gitBranchTool to use a default value if not provided.
  • Refactored the jsonToCsvTool to introduce a new JsonToCsvRequestContext interface, allowing for better context management.
  • Removed redundant logging hooks in jsonToCsvTool and restructured the execution method for clarity.
  • Updated the randomGeneratorTool to use a more structured RandomToolContext interface, enhancing type safety and clarity.
  • Added detailed logging hooks for input and output events in randomGeneratorTool.
  • Introduced a new ScraperToolContext interface in web-scraper-tool.ts to manage context more effectively, including properties like allowedDomains, userAgent, and timeout.
  • Enhanced logging for various scraping tools, including detailed input and output logging for better traceability.
  • Added logging hooks for input and output events across multiple tools, including htmlToMarkdownTool, linkExtractorTool, and dataExporterTool, to improve monitoring and debugging capabilities.

- Added a new `gitToolContextSchema` to define optional properties for Git tools, including `defaultBranch`, `allowForce`, `allowAmend`, `maxCommits`, and `timeout`.
- Updated the `cwd` assignment in multiple Git tools to use nullish coalescing (`??`) for better handling of undefined values.
- Improved timeout handling in the `gitBranchTool` to use a default value if not provided.
- Refactored the `jsonToCsvTool` to introduce a new `JsonToCsvRequestContext` interface, allowing for better context management.
- Removed redundant logging hooks in `jsonToCsvTool` and restructured the execution method for clarity.
- Updated the `randomGeneratorTool` to use a more structured `RandomToolContext` interface, enhancing type safety and clarity.
- Added detailed logging hooks for input and output events in `randomGeneratorTool`.
- Introduced a new `ScraperToolContext` interface in `web-scraper-tool.ts` to manage context more effectively, including properties like `allowedDomains`, `userAgent`, and `timeout`.
- Enhanced logging for various scraping tools, including detailed input and output logging for better traceability.
- Added logging hooks for input and output events across multiple tools, including `htmlToMarkdownTool`, `linkExtractorTool`, and `dataExporterTool`, to improve monitoring and debugging capabilities.
Copilot AI review requested due to automatic review settings January 8, 2026 13:49
@continue
Copy link

continue bot commented Jan 8, 2026

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

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Sorry @ssdeanx, your pull request is larger than the review limit of 150000 diff characters

@github-actions
Copy link

github-actions bot commented Jan 8, 2026

🤖 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
Copy link

coderabbitai bot commented Jan 8, 2026

Caution

Review failed

The pull request is closed.

Summary by CodeRabbit

Release Notes

  • New Features

    • Tools now support per-request context configuration, allowing dynamic settings like API keys, timeouts, and user identification to be passed with each tool execution.
    • Enhanced tool execution logging and observability with lifecycle event hooks for improved debugging and monitoring.
  • Improvements

    • Better cancellation handling and user-aware operation tracing across tools.

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

Walkthrough

This PR systematically enhances tool observability and request context handling across 17+ tool files by: introducing new typed RequestContext interfaces with tool-specific optional fields (userId, apiKey, theme, seed, etc.), standardizing execute signatures from inputData to input parameters, adding lifecycle hooks (onInputStart/Delta/Available/Output) for streaming visibility, extracting and integrating requestContext into tracing spans and debug logs, and updating parameter resolution to prefer context-provided values with fallbacks to defaults or environment variables.

Changes

Cohort / File(s) Summary
Context Interface + Parameter Standardization
src/mastra/tools/alpha-vantage.tool.ts, src/mastra/tools/arxiv.tool.ts, src/mastra/tools/browser-tool.ts, src/mastra/tools/calculator.tool.ts, src/mastra/tools/calendar-tool.ts, src/mastra/tools/code-analysis.tool.ts, src/mastra/tools/code-chunking.ts, src/mastra/tools/code-search.tool.ts
Added new exported RequestContext interfaces with tool-specific fields (e.g., AlphaVantageRequestContext extends RequestContext with optional apiKey). Updated execute signatures and integrated requestContext extraction with userId/apiKey logging.
Context + Lifecycle Hooks
src/mastra/tools/color-change-tool.ts, src/mastra/tools/copywriter-agent-tool.ts, src/mastra/tools/csv-to-json.tool.ts, src/mastra/tools/json-to-csv.tool.ts, src/mastra/tools/random-generator.tool.ts
Introduced new RequestContext interfaces with optional tool-specific fields. Changed execute from destructured input to input parameter. Added onInputStart/onInputDelta/onInputAvailable/onOutput lifecycle hooks for streaming visibility.
Comprehensive Tool Refactoring
src/mastra/tools/data-file-manager.ts, src/mastra/tools/finnhub-tools.ts, src/mastra/tools/web-scraper-tool.ts
Added new RequestContext interfaces and refactored all tool execute signatures. Integrated userId into span attributes. Updated lifecycle hooks across multiple tools. Modified parameter sourcing to use input-based access patterns.
Nullish Coalescing + Context Schema
src/mastra/tools/git-local.tool.ts
Replaced logical OR (||) with nullish coalescing (\?\?) for repoPath and timeout handling. Added gitToolContextSchema for validating context options.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🐰 Hopping through the tools, we trace and we see,
Each context now flows like a burrow so free,
Lifecycle hooks log each step of the race,
Request awareness in every small place! ✨🔍

✨ 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 70a6fd2 and 6091646.

📒 Files selected for processing (17)
  • src/mastra/tools/alpha-vantage.tool.ts
  • src/mastra/tools/arxiv.tool.ts
  • src/mastra/tools/browser-tool.ts
  • src/mastra/tools/calculator.tool.ts
  • src/mastra/tools/calendar-tool.ts
  • src/mastra/tools/code-analysis.tool.ts
  • src/mastra/tools/code-chunking.ts
  • src/mastra/tools/code-search.tool.ts
  • src/mastra/tools/color-change-tool.ts
  • src/mastra/tools/copywriter-agent-tool.ts
  • src/mastra/tools/csv-to-json.tool.ts
  • src/mastra/tools/data-file-manager.ts
  • src/mastra/tools/finnhub-tools.ts
  • src/mastra/tools/git-local.tool.ts
  • src/mastra/tools/json-to-csv.tool.ts
  • src/mastra/tools/random-generator.tool.ts
  • src/mastra/tools/web-scraper-tool.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.

Copy link

@greptile-apps greptile-apps bot left a 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.

@github-actions
Copy link

github-actions bot commented Jan 8, 2026

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

@ssdeanx ssdeanx merged commit 37c2f33 into main Jan 8, 2026
24 of 31 checks passed
@gemini-code-assist
Copy link
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 significantly enhances the flexibility, observability, and reliability of various tools within the system. By introducing structured request contexts, tools can now be configured dynamically with user-specific or runtime-specific parameters, leading to more adaptable and powerful functionalities. The changes also streamline logging practices and improve error handling, particularly around operation cancellation, making the system more robust and easier to debug.

Highlights

  • Enhanced Context Handling: Introduced new RequestContext interfaces across various tools (Alpha Vantage, Arxiv, Browser, Calculator, Code Analysis, Code Chunking, Code Search, Color Change, CSV/JSON Conversion, Data File Manager, Finnhub, Random Generator, Web Scraper) to allow dynamic configuration and user-specific settings, such as API keys, user IDs, chunking parameters, search options, and scraping rules.
  • Improved Logging and Observability: Refactored logging hooks (onInputStart, onInputDelta, onInputAvailable, onOutput) in numerous tools for better structure and consistency. Added detailed debug logs for requestContext and userId to enhance traceability and debugging capabilities during tool execution.
  • Robust Cancellation Handling: Implemented explicit abortSignal checks at the beginning of execute methods and propagated abortSignal to fetch calls in tools like Arxiv, Browser, Calculator, and Code Search, ensuring operations can be reliably cancelled.
  • Refined Git Tool Functionality: Added a gitToolContextSchema to define optional properties for Git tools, including defaultBranch, allowForce, allowAmend, maxCommits, and timeout. Updated cwd assignments to use nullish coalescing (??) and improved timeout handling in gitBranchTool with a default value.
  • Enhanced Type Safety and Nullish Coalescing: Improved type annotations in the randomGeneratorTool and adopted nullish coalescing (??) over logical OR (||) in several places to correctly handle null or undefined values without misinterpreting 0 or false as falsy fallbacks.
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.

Copy link
Contributor

Copilot AI left a 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 enhances multiple tools with improved context handling and logging capabilities. The main changes include introducing TypeScript interfaces for request contexts (replacing Zod schemas in some cases), standardizing parameter naming from inputData to input, repositioning logging hooks after the execute method, and improving null handling with nullish coalescing operators.

Key Changes:

  • Added request context interfaces (ScraperToolContext, RandomToolContext, JsonToCsvRequestContext, etc.) extending RequestContext for better type safety
  • Standardized execute function parameter naming to input across multiple tools
  • Moved logging hooks (onInputStart, onInputDelta, onInputAvailable, onOutput) after execute methods for better code organization
  • Improved timeout handling and null checks using nullish coalescing (??)

Reviewed changes

Copilot reviewed 17 out of 17 changed files in this pull request and generated 62 comments.

Show a summary per file
File Description
web-scraper-tool.ts Added ScraperToolContext interface; moved logging hooks; improved allowedDomains handling
random-generator.tool.ts Replaced Zod schema with TypeScript interface; improved type annotations; added logging hooks
json-to-csv.tool.ts Refactored to JsonToCsvRequestContext interface; repositioned logging hooks; removed outputSchema
git-local.tool.ts Added gitToolContextSchema (unused); improved timeout handling with nullish coalescing
finnhub-tools.ts Added FinnhubRequestContext; standardized to input parameter; moved logging hooks
data-file-manager.ts Added DataFileManagerContext usage; repositioned logging hooks across all file operations
csv-to-json.tool.ts Refactored context handling; removed outputSchema; moved logging hooks
copywriter-agent-tool.ts Added CopywriterRequestContext; simplified userId extraction logic
color-change-tool.ts Added ColorChangeRequestContext interface; minor refactoring
code-search.tool.ts Added CodeSearchRequestContext; integrated context defaults with input options
code-chunking.ts Added CodeChunkingRequestContext; integrated context for chunk sizing
code-analysis.tool.ts Added CodeAnalysisRequestContext; added userId logging
calendar-tool.ts Added CalendarRequestContext; added logging hooks for multiple calendar tools
calculator.tool.ts Enhanced CalculatorToolContext; added abort signal handling
browser-tool.ts Added BrowserRequestContext; added logging hooks for all browser tools
arxiv.tool.ts Added ArxivRequestContext; improved abort signal handling; added fetch signal
alpha-vantage.tool.ts Added AlphaVantageRequestContext; improved apiKey sourcing from context

@@ -44,53 +47,9 @@ export const csvToJsonTool = createTool({
skip_empty_lines: true,
}),
}),
Copy link

Copilot AI Jan 8, 2026

Choose a reason for hiding this comment

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

The missing outputSchema definition may cause runtime validation issues. The outputSchema was removed during the refactoring, but tool definitions should include both inputSchema and outputSchema for proper validation and type inference.

Suggested change
}),
}),
outputSchema: z.object({
data: z
.array(z.record(z.any()))
.describe('Parsed CSV records as an array of objects'),
}),

Copilot uses AI. Check for mistakes.
inputSchema: batchWebScraperInputSchema,
outputSchema: batchWebScraperOutputSchema,
execute: async (inputData, context) => {
const requestContext = context?.requestContext as ScraperToolContext
Copy link

Copilot AI Jan 8, 2026

Choose a reason for hiding this comment

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

The requestContext variable is extracted but never used in this function. The variable should either be removed to avoid confusion, or the context should be utilized (e.g., for logging userId or applying context-specific configurations).

Suggested change
const requestContext = context?.requestContext as ScraperToolContext

Copilot uses AI. Check for mistakes.
inputSchema: siteMapExtractorInputSchema,
outputSchema: siteMapExtractorOutputSchema,
execute: async (inputData, context) => {
const requestContext = context?.requestContext as ScraperToolContext
Copy link

Copilot AI Jan 8, 2026

Choose a reason for hiding this comment

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

The requestContext variable is extracted but never used in this function. The variable should either be removed to avoid confusion, or the context should be utilized (e.g., for logging userId or applying context-specific configurations).

Suggested change
const requestContext = context?.requestContext as ScraperToolContext

Copilot uses AI. Check for mistakes.
inputSchema: linkExtractorInputSchema,
outputSchema: linkExtractorOutputSchema,
execute: async (inputData, context) => {
const requestContext = context?.requestContext as ScraperToolContext
Copy link

Copilot AI Jan 8, 2026

Choose a reason for hiding this comment

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

The requestContext variable is extracted but never used in this function. The variable should either be removed to avoid confusion, or the context should be utilized (e.g., for logging userId or applying context-specific configurations).

Suggested change
const requestContext = context?.requestContext as ScraperToolContext

Copilot uses AI. Check for mistakes.
Comment on lines +19 to +26
const gitToolContextSchema = z.object({
defaultBranch: z.string().optional(),
allowForce: z.boolean().optional(),
allowAmend: z.boolean().optional(),
maxCommits: z.number().optional(),
timeout: z.number().optional(),
})

Copy link

Copilot AI Jan 8, 2026

Choose a reason for hiding this comment

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

The gitToolContextSchema is defined but never used in the code. This schema was likely intended to validate the request context, but the code uses TypeScript interfaces (GitToolContext) for type checking instead. Either use this schema to validate runtime context or remove it to avoid dead code.

Suggested change
const gitToolContextSchema = z.object({
defaultBranch: z.string().optional(),
allowForce: z.boolean().optional(),
allowAmend: z.boolean().optional(),
maxCommits: z.number().optional(),
timeout: z.number().optional(),
})

Copilot uses AI. Check for mistakes.
}
});
},
onInputStart: ({ toolCallId, messages, abortSignal }) => {
Copy link

Copilot AI Jan 8, 2026

Choose a reason for hiding this comment

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

'abortSignal' is defined but never used.

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

Copilot AI Jan 8, 2026

Choose a reason for hiding this comment

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

'abortSignal' is defined but never used.

Copilot uses AI. Check for mistakes.
hook: 'onInputAvailable',
})
},
onOutput: ({ output, toolCallId, toolName, abortSignal }) => {
Copy link

Copilot AI Jan 8, 2026

Choose a reason for hiding this comment

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

'abortSignal' is defined but never used.

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

Copilot AI Jan 8, 2026

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.
@@ -1296,7 +1304,7 @@ export const gitBranchTool = createTool({
const mergeResult = await execa('git', args, {
Copy link

Copilot AI Jan 8, 2026

Choose a reason for hiding this comment

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

'mergeResult' is assigned a value but never used.

Suggested change
const mergeResult = await execa('git', args, {
await execa('git', args, {

Copilot uses AI. Check for mistakes.
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a 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 significant enhancements to tool execution context handling and logging across various tools, including Alpha Vantage, ArXiv, Browser, Calculator, Calendar, Code Analysis, Code Chunking, Code Search, Color Change, Copywriter Agent, CSV to JSON, Data File Manager, Finnhub, JSON to CSV, Random Generator, and Web Scraper. The primary changes involve defining new RequestContext interfaces for each tool (e.g., AlphaVantageRequestContext, ArxivRequestContext, BrowserRequestContext) to allow for passing tool-specific configuration and user context (like userId, apiKey, chunkSize, maxRows, allowedDomains, seed, etc.) through the context object. This enables more dynamic and user-aware tool behavior, such as prioritizing API keys from the request context or logging user-specific actions. Additionally, many tools had their onInputStart, onInputDelta, onInputAvailable, and onOutput logging hooks reordered to appear after the execute function definition, and several execute functions were refactored to explicitly destructure input and context properties, and to include log.debug statements for request context availability. Cancellation checks using abortSignal were also standardized to abortSignal?.aborted === true or abortSignal?.aborted. Review comments highlighted the removal of outputSchema for the CSV to JSON tool, noting that this reduces type safety and runtime validation, suggesting it should be retained for explicit contract definition.

Comment on lines 47 to -49
skip_empty_lines: true,
}),
}),
outputSchema: z.object({
data: z.array(z.any()).describe('Parsed JSON data'),
}),
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The outputSchema for this tool has been removed. While the tool might still function, removing the output schema reduces type safety and disables runtime validation of the tool's output. It's a good practice to keep it to ensure the tool's contract is explicit and enforced. Was this removal intentional?

Comment on lines 36 to -38
}),
}),
outputSchema: z.object({
csv: z.string().describe('Generated CSV string'),
}),
Copy link
Contributor

Choose a reason for hiding this comment

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

medium

The outputSchema for this tool has been removed. This weakens the tool's contract by removing runtime validation of the output. It's recommended to keep the output schema for type safety and to explicitly define the tool's expected output.

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.

1 participant