Skip to content

mcp-prep#1740

Merged
MrgSub merged 1 commit intostagingfrom
07-15-mcp-prep
Jul 16, 2025
Merged

mcp-prep#1740
MrgSub merged 1 commit intostagingfrom
07-15-mcp-prep

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Jul 16, 2025

Gmail Search Query Builder and MCP Tool Registration Improvements

Description

This PR adds a dedicated Gmail search query builder tool and improves the Model Context Protocol (MCP) agent implementation. The changes include:

  1. Added a new BuildGmailSearchQuery tool that leverages AI to help users construct effective Gmail search queries
  2. Migrated MCP agent tools to use the newer registerTool method with proper descriptions and input schemas
  3. Added initial message handling for AI sidebar component
  4. Reduced thread sync max count from 40 to 5 to improve performance during development

Type of Change

  • ✨ New feature (non-breaking change which adds functionality)
  • ⚡ Performance improvement

Areas Affected

  • Email Integration (Gmail, IMAP, etc.)
  • User Interface/Experience
  • API Endpoints

Testing Done

  • Manual testing performed

Checklist

  • I have performed a self-review of my code
  • My changes generate no new warnings

Additional Notes

The Gmail search query builder tool helps users construct more effective search queries by translating natural language requests into Gmail's search syntax. This should improve the user experience when trying to find specific emails.

The MCP tool registration improvements provide better documentation and type safety for the available tools.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 16, 2025

Walkthrough

A new AI-powered tool, buildGmailSearchQuery, was introduced to generate Gmail search queries. The tool is registered with detailed metadata and integrated into the server's toolset. Tool registration in the MCP was refactored for richer descriptions and schemas. Minor UI and configuration adjustments were also made.

Changes

File(s) Change Summary
apps/server/src/routes/agent/tools.ts, apps/server/src/types.ts Added buildGmailSearchQuery tool and corresponding enum; updated tool exports.
apps/server/src/routes/chat.ts Refactored tool registration in MCP, removed legacy tool definitions, added metadata, and improved error handling.
apps/mail/components/ui/ai-sidebar.tsx Updated hook to set initial messages; reordered CSS classes.
apps/server/wrangler.jsonc Changed THREAD_SYNC_MAX_COUNT from "40" to "5" in local environment settings.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant AISidebar
    participant Server
    participant MCP
    participant AIModel

    User->>AISidebar: Initiate Gmail search query tool
    AISidebar->>Server: Request buildGmailSearchQuery with query parameter
    Server->>MCP: Route tool request with metadata/schema
    MCP->>AIModel: Generate search query using system prompt
    AIModel-->>MCP: Return generated search query
    MCP-->>Server: Return search query result
    Server-->>AISidebar: Respond with generated query
    AISidebar-->>User: Display Gmail search query
Loading

Possibly related PRs

  • Improve Search #1188: Updates the GmailSearchAssistantSystemPrompt used by the new buildGmailSearchQuery tool, directly affecting its AI-generated outputs.
  • Replace callDriver with direct mail manager methods #1466: Refactors ZeroAgent and related mail operations, including changes to Gmail query generation methods, overlapping with this PR's changes.
  • Typo #1608: Refactors and enhances tool registration and chat-related methods in apps/server/src/routes/chat.ts, related to the removal and replacement of deprecated thread fetching methods.

Poem

In the warren of code, a new tool appears,
To craft Gmail queries with AI in your ears.
With schemas and prompts, registration anew,
The agent now smarter, with tasks it can do!
🐇✨
"Hop-hop," says the rabbit, "search made light for you!"

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Collaborator Author

MrgSub commented Jul 16, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

@MrgSub MrgSub marked this pull request as ready for review July 16, 2025 02:35
Copy link
Contributor

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

cursor[bot]

This comment was marked as outdated.

Copy link
Contributor

@cubic-dev-ai cubic-dev-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.

cubic reviewed 5 files and found no issues. Review PR in cubic.dev.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🔭 Outside diff range comments (1)
apps/server/src/routes/chat.ts (1)

1427-1450: Consider reusing the buildGmailSearchQuery implementation from tools.ts.

This implementation duplicates the logic from apps/server/src/routes/agent/tools.ts. Consider importing and reusing the tool instead of duplicating the code.

🧹 Nitpick comments (2)
apps/server/src/routes/agent/tools.ts (1)

384-398: Consider improving error handling and model configuration.

The implementation looks good, but there are two areas for improvement:

  1. The environment variable OPENAI_MODEL is used for an Anthropic model, which is confusing
  2. No error handling for the generateText call
 const buildGmailSearchQuery = () =>
   tool({
     description: 'Build Gmail search query using AI assistance',
     parameters: z.object({
       query: z.string(),
     }),
     execute: async ({ query }) => {
-      const result = await generateText({
-        model: anthropic(env.OPENAI_MODEL || 'claude-3-5-haiku-latest'),
-        system: GmailSearchAssistantSystemPrompt(),
-        prompt: query,
-      });
-      return result.text;
+      try {
+        const result = await generateText({
+          model: anthropic(env.ANTHROPIC_MODEL || env.OPENAI_MODEL || 'claude-3-5-haiku-latest'),
+          system: GmailSearchAssistantSystemPrompt(),
+          prompt: query,
+        });
+        return result.text;
+      } catch (error) {
+        console.error('Error generating Gmail search query:', error);
+        throw new Error('Failed to generate Gmail search query');
+      }
     },
   });
apps/server/src/routes/chat.ts (1)

1714-1778: Clean up or document the commented-out tools.

The bulkDelete and bulkArchive tools are commented out but fully implemented. Either remove them if they're no longer needed or add a comment explaining why they're disabled.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8d7bb25 and 293692d.

📒 Files selected for processing (5)
  • apps/mail/components/ui/ai-sidebar.tsx (2 hunks)
  • apps/server/src/routes/agent/tools.ts (3 hunks)
  • apps/server/src/routes/chat.ts (14 hunks)
  • apps/server/src/types.ts (1 hunks)
  • apps/server/wrangler.jsonc (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
apps/server/src/routes/chat.ts (1)
Learnt from: retrogtx
PR: Mail-0/Zero#1468
File: apps/server/src/trpc/routes/mail.ts:386-391
Timestamp: 2025-06-27T04:59:29.731Z
Learning: In apps/server/src/trpc/routes/mail.ts, the attachment processing logic conditionally handles mixed attachment types - it preserves existing File-like objects with arrayBuffer methods while only converting serialized attachments that need processing through toAttachmentFiles.
🧬 Code Graph Analysis (1)
apps/server/src/routes/agent/tools.ts (1)
apps/server/src/lib/prompts.ts (1)
  • GmailSearchAssistantSystemPrompt (233-279)
⏰ 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). (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Cursor BugBot
🔇 Additional comments (7)
apps/server/wrangler.jsonc (1)

104-104: Confirm that the reduced THREAD_SYNC_MAX_COUNT is for testing purposes only.

The value has been reduced from 40 to 5 in the local environment while staging (line 237) and production (line 366) retain the value of 40. Please confirm this change is intentional for testing and won't impact production behavior.

apps/server/src/types.ts (1)

229-229: LGTM!

The new enum member follows the established naming convention and correctly represents the new Gmail search query builder tool.

apps/mail/components/ui/ai-sidebar.tsx (2)

355-357: Good practice: Explicit initial messages initialization.

Making the initial messages explicitly an empty array improves code clarity and prevents potential undefined behavior.


476-476: CSS class reordering has no functional impact.

The reordering of Tailwind CSS classes maintains the same styling while potentially improving readability.

apps/server/src/routes/chat.ts (3)

361-375: Clarify the status of the registerZeroMCP method.

The method is implemented but commented out in onStart(). Is this intentional for a phased rollout, or should it be enabled?


417-420: Good addition of error logging.

The error handler improves observability. Note that errors are logged but not propagated, which may hide failures from the caller.


1354-1643: Excellent refactoring of tool registration.

The new approach with structured descriptions and zod schemas significantly improves:

  • Tool discoverability through clear descriptions
  • Input validation with type-safe schemas
  • Consistent response format

This will make the tools more reliable and easier to use.

Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Bug: Tool Processing Bypass Causes Inconsistency

The tool processing logic is broken. The ToolOrchestrator's processTools method is incorrectly called with an empty object, while the streamText function receives the unprocessed rawTools. This bypasses the orchestrator's intended tool processing, creating an inconsistency where processToolCalls operates on an empty set of tools and streamText uses unprocessed tools, potentially leading to broken tool functionality.

apps/server/src/routes/chat.ts#L397-L415

const rawTools = {
...(await authTools(this, connectionId)),
};
const tools = orchestrator.processTools({});
const processedMessages = await processToolCalls(
{
messages: this.messages,
dataStream,
tools,
},
{},
);
const result = streamText({
model: anthropic(env.OPENAI_MODEL || 'claude-3-5-haiku-latest'),
maxSteps: 10,
messages: processedMessages,
tools: rawTools,

Fix in CursorFix in Web


Was this report helpful? Give feedback by reacting with 👍 or 👎

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 293692d and 9e71610.

📒 Files selected for processing (5)
  • apps/mail/components/ui/ai-sidebar.tsx (2 hunks)
  • apps/server/src/routes/agent/tools.ts (3 hunks)
  • apps/server/src/routes/chat.ts (15 hunks)
  • apps/server/src/types.ts (1 hunks)
  • apps/server/wrangler.jsonc (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (4)
  • apps/server/wrangler.jsonc
  • apps/server/src/types.ts
  • apps/mail/components/ui/ai-sidebar.tsx
  • apps/server/src/routes/agent/tools.ts
🧰 Additional context used
🧠 Learnings (1)
apps/server/src/routes/chat.ts (1)
Learnt from: retrogtx
PR: Mail-0/Zero#1468
File: apps/server/src/trpc/routes/mail.ts:386-391
Timestamp: 2025-06-27T04:59:29.731Z
Learning: In apps/server/src/trpc/routes/mail.ts, the attachment processing logic conditionally handles mixed attachment types - it preserves existing File-like objects with arrayBuffer methods while only converting serialized attachments that need processing through toAttachmentFiles.
⏰ 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). (2)
  • GitHub Check: Cursor BugBot
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (8)
apps/server/src/routes/chat.ts (8)

26-26: LGTM - Import additions support new functionality.

The new imports for DurableObjectOAuthClientProvider and withRetry are appropriate for the OAuth authentication and retry logic being added.

Also applies to: 34-34


361-375: Clarify the status of MCP OAuth integration.

The registerZeroMCP method is implemented but commented out in onStart(). Is this intentionally disabled for testing, or should it be enabled? The OAuth integration looks properly implemented but appears to be in a transitional state.


417-419: Good addition of error handling.

The error handling for the streamText call is a valuable improvement that will help with debugging and monitoring.


1354-1425: Excellent tool registration improvements.

The refactoring from this.server.tool to this.server.registerTool with detailed descriptions and zod input schemas significantly improves code quality, validation, and maintainability.


1427-1450: Well-implemented Gmail search query tool.

The direct implementation of buildGmailSearchQuery using generateText with the Anthropic model is clean and follows the established pattern. Good centralization of the Gmail search functionality.


1454-1603: Thread management tools are well-structured.

The thread management tools (listThreads, getThread, markThreadsRead, markThreadsUnread, modifyLabels) are properly enhanced with descriptions and input validation. The implementation is clean and follows consistent patterns.


1605-1708: Utility tools are properly implemented.

The utility tools (getCurrentDate, getUserLabels, getLabel, createLabel) are well-structured with appropriate error handling, especially in the createLabel tool which properly catches and handles errors.


1710-1774: Clarify the status of commented bulk operations.

The bulkDelete and bulkArchive tools are commented out. Are these intentionally disabled for testing, being deprecated, or should they be re-enabled? Consider either removing the commented code or adding a TODO comment explaining their status.

Copy link
Collaborator Author

MrgSub commented Jul 16, 2025

Merge activity

  • Jul 16, 3:04 AM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jul 16, 3:04 AM UTC: @MrgSub merged this pull request with Graphite.

@MrgSub MrgSub merged commit aa694e9 into staging Jul 16, 2025
8 checks passed
@MrgSub MrgSub deleted the 07-15-mcp-prep branch July 16, 2025 03:04
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