Skip to content

Comments

Add email actions to AI router#1198

Merged
MrgSub merged 1 commit intostagingfrom
06-03-simple_ai_router
Jun 4, 2025
Merged

Add email actions to AI router#1198
MrgSub merged 1 commit intostagingfrom
06-03-simple_ai_router

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Jun 4, 2025

Implement AI Email Actions API Endpoint

Description

This PR adds a new /do/:action endpoint to the AI router that enables email-related functionality through the MCP service. The endpoint supports three main actions:

  • Listing email threads from the inbox
  • Composing new emails with AI assistance
  • Sending emails to recipients

Additionally, it exports the getDriverFromConnectionId function from the MCP service to make it accessible to the new endpoint and adds the required ElevenLabs API key to the environment variables.

Type of Change

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

Areas Affected

  • Email Integration (Gmail, IMAP, etc.)
  • API Endpoints

Testing Done

  • Manual testing performed

Security Considerations

  • No sensitive data is exposed
  • Authentication checks are in place (via X-Connection-Id header)
  • Input validation is implemented

Checklist

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

Additional Notes

The new endpoint requires a valid connection ID in the X-Connection-Id header for authentication. It returns appropriate error responses when the connection ID is missing or invalid.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 4, 2025

Walkthrough

A new POST route /do/:action was added to the AI router to handle various email-related AI actions, utilizing an exported getDriverFromConnectionId function. The wrangler configuration was updated to include a new environment variable for local development.

Changes

File(s) Change Summary
apps/server/src/routes/ai.ts Added a POST /do/:action route to handle multiple AI-driven email actions.
apps/server/src/services/mcp-service/mcp.ts Exported the getDriverFromConnectionId function for use in other modules.
apps/server/wrangler.jsonc Added ELEVENLABS_API_KEY environment variable to the local configuration.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant aiRouter
    participant mcpService
    participant Driver
    participant composeEmail

    Client->>aiRouter: POST /do/:action (action, body, X-Connection-Id)
    aiRouter->>mcpService: getDriverFromConnectionId(connectionId)
    mcpService-->>aiRouter: Driver instance
    aiRouter->>aiRouter: switch(action)
    alt ListThreads
        aiRouter->>Driver: listThreads("inbox")
        Driver-->>aiRouter: threads metadata
    else ComposeEmail
        aiRouter->>composeEmail: composeEmail(prompt, subject, username, connectionId)
        composeEmail-->>aiRouter: composed email body
    else SendEmail
        aiRouter->>Driver: sendEmail(to, subject, message, [], {})
        Driver-->>aiRouter: send result
    else Unknown action
        aiRouter-->>Client: 400 Not implemented
    end
    aiRouter-->>Client: JSON response
Loading

Suggested reviewers

  • nizzyabi
  • ahmetskilinc

Poem

A new route hops in, swift and bright,
Handling emails by day and night.
Compose, send, or list a thread—
With drivers fetched, the code is led.
Eleven Labs key in the local den,
The rabbit’s code leaps forth again! 🐇✨

✨ 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 Jun 4, 2025

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

@MrgSub MrgSub marked this pull request as ready for review June 4, 2025 05:22
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: 4

🧹 Nitpick comments (1)
apps/server/wrangler.jsonc (1)

70-70: Replace placeholder API key with proper configuration.

The placeholder value "1234567890" should be replaced with a valid ElevenLabs API key for local development, or documented as a configuration requirement.

Consider adding a comment or documentation indicating this needs to be configured with an actual API key.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c0f972e and d32e71e.

📒 Files selected for processing (3)
  • apps/server/src/routes/ai.ts (1 hunks)
  • apps/server/src/services/mcp-service/mcp.ts (1 hunks)
  • apps/server/wrangler.jsonc (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/server/src/routes/ai.ts (2)
apps/server/src/services/mcp-service/mcp.ts (1)
  • getDriverFromConnectionId (12-37)
apps/server/src/trpc/routes/ai/compose.ts (1)
  • composeEmail (29-106)
🪛 Biome (1.9.4)
apps/server/src/routes/ai.ts

[error] 26-35: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 38-43: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 46-55: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

🔇 Additional comments (1)
apps/server/src/services/mcp-service/mcp.ts (1)

12-12: LGTM! Export enables AI router integration.

The function export is necessary for the new AI router functionality while maintaining the existing logic and error handling.

Comment on lines +15 to +17
const action = c.req.param('action') as Tools;
const body = await c.req.json();
console.log('[DEBUG] action', action, body);
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation for request body.

The request body is parsed without validation, which could lead to runtime errors if required fields are missing.

Consider using a schema validation library like Zod to validate the request body based on the action type:

const bodySchema = z.object({
  prompt: z.string().optional(),
  emailSubject: z.string().optional(),
  to: z.array(z.object({
    name: z.string().optional(),
    email: z.string().email(),
  })).optional(),
  subject: z.string().optional(),
  message: z.string().optional(),
});

const body = bodySchema.parse(await c.req.json());
🤖 Prompt for AI Agents
In apps/server/src/routes/ai.ts around lines 15 to 17, the request body is
parsed without validation, which risks runtime errors if required fields are
missing. To fix this, define a Zod schema that matches the expected structure of
the request body, including optional and required fields as appropriate. Then,
replace the direct JSON parsing with a call to the schema's parse method to
validate and parse the input safely before using it.

const newBody = await composeEmail({
prompt: body.prompt,
emailSubject: body.emailSubject,
username: 'Nizar Abi Zaher',
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Remove hard-coded username.

The username 'Nizar Abi Zaher' is hard-coded and should be retrieved from the user's connection or profile data.

Consider retrieving the username from the database using the connection ID or from user authentication context.

🤖 Prompt for AI Agents
In apps/server/src/routes/ai.ts at line 41, replace the hard-coded username
'Nizar Abi Zaher' with a dynamic value retrieved from the user's connection or
authentication context. Modify the code to access the current user's profile or
session data to get the username, ensuring it reflects the actual connected user
instead of a fixed string.

const result = await driver.create({
to: body.to.map((to: any) => ({
name: to.name ?? to.email,
email: to.email ?? 'founders@0.email',
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove hard-coded fallback email address.

The fallback email 'founders@0.email' should not be hard-coded. This could lead to emails being sent to unintended recipients.

Either require a valid email or throw an error if none is provided:

-            email: to.email ?? 'founders@0.email',
+            email: to.email,

Add validation to ensure all recipients have valid email addresses before processing.

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

Suggested change
email: to.email ?? 'founders@0.email',
email: to.email,
🤖 Prompt for AI Agents
In apps/server/src/routes/ai.ts at line 49, remove the hard-coded fallback email
'founders@0.email'. Instead, add validation to check if to.email is present and
valid; if not, throw an error to prevent processing with an invalid or missing
email. This ensures no unintended recipients receive emails and enforces proper
input validation.

Comment on lines +24 to +59
switch (action) {
case Tools.ListThreads:
const threads = await Promise.all(
(await driver.list({ folder: 'inbox', maxResults: 5 })).threads.map((thread) =>
driver.get(thread.id).then((thread) => ({
id: thread.latest?.id,
subject: thread.latest?.subject,
sender: thread.latest?.sender,
date: thread.latest?.receivedOn,
})),
),
);
return c.json({ success: true, result: threads });
case Tools.ComposeEmail:
const newBody = await composeEmail({
prompt: body.prompt,
emailSubject: body.emailSubject,
username: 'Nizar Abi Zaher',
connectionId,
});
return c.json({ success: true, result: newBody });
case Tools.SendEmail:
const result = await driver.create({
to: body.to.map((to: any) => ({
name: to.name ?? to.email,
email: to.email ?? 'founders@0.email',
})),
subject: body.subject,
message: body.message,
attachments: [],
headers: {},
});
return c.json({ success: true, result });
default:
return c.json({ success: false, error: 'Not implemented' }, 400);
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix switch case variable declarations to prevent scope bleed.

The static analysis correctly identifies that variable declarations in switch cases can be accessed by other cases, which is a potential source of bugs.

Wrap each case in a block to scope the variables properly:

-    switch (action) {
-      case Tools.ListThreads:
-        const threads = await Promise.all(
+    switch (action) {
+      case Tools.ListThreads: {
+        const threads = await Promise.all(
           (await driver.list({ folder: 'inbox', maxResults: 5 })).threads.map((thread) =>
             driver.get(thread.id).then((thread) => ({
               id: thread.latest?.id,
               subject: thread.latest?.subject,
               sender: thread.latest?.sender,
               date: thread.latest?.receivedOn,
             })),
           ),
         );
         return c.json({ success: true, result: threads });
-      case Tools.ComposeEmail:
-        const newBody = await composeEmail({
+      }
+      case Tools.ComposeEmail: {
+        const newBody = await composeEmail({
           prompt: body.prompt,
           emailSubject: body.emailSubject,
           username: 'Nizar Abi Zaher',
           connectionId,
         });
         return c.json({ success: true, result: newBody });
-      case Tools.SendEmail:
-        const result = await driver.create({
+      }
+      case Tools.SendEmail: {
+        const result = await driver.create({
           to: body.to.map((to: any) => ({
             name: to.name ?? to.email,
             email: to.email ?? 'founders@0.email',
           })),
           subject: body.subject,
           message: body.message,
           attachments: [],
           headers: {},
         });
         return c.json({ success: true, result });
+      }
       default:
         return c.json({ success: false, error: 'Not implemented' }, 400);
     }
📝 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.

Suggested change
switch (action) {
case Tools.ListThreads:
const threads = await Promise.all(
(await driver.list({ folder: 'inbox', maxResults: 5 })).threads.map((thread) =>
driver.get(thread.id).then((thread) => ({
id: thread.latest?.id,
subject: thread.latest?.subject,
sender: thread.latest?.sender,
date: thread.latest?.receivedOn,
})),
),
);
return c.json({ success: true, result: threads });
case Tools.ComposeEmail:
const newBody = await composeEmail({
prompt: body.prompt,
emailSubject: body.emailSubject,
username: 'Nizar Abi Zaher',
connectionId,
});
return c.json({ success: true, result: newBody });
case Tools.SendEmail:
const result = await driver.create({
to: body.to.map((to: any) => ({
name: to.name ?? to.email,
email: to.email ?? 'founders@0.email',
})),
subject: body.subject,
message: body.message,
attachments: [],
headers: {},
});
return c.json({ success: true, result });
default:
return c.json({ success: false, error: 'Not implemented' }, 400);
}
switch (action) {
case Tools.ListThreads: {
const threads = await Promise.all(
(await driver.list({ folder: 'inbox', maxResults: 5 })).threads.map((thread) =>
driver.get(thread.id).then((thread) => ({
id: thread.latest?.id,
subject: thread.latest?.subject,
sender: thread.latest?.sender,
date: thread.latest?.receivedOn,
})),
),
);
return c.json({ success: true, result: threads });
}
case Tools.ComposeEmail: {
const newBody = await composeEmail({
prompt: body.prompt,
emailSubject: body.emailSubject,
username: 'Nizar Abi Zaher',
connectionId,
});
return c.json({ success: true, result: newBody });
}
case Tools.SendEmail: {
const result = await driver.create({
to: body.to.map((to: any) => ({
name: to.name ?? to.email,
email: to.email ?? 'founders@0.email',
})),
subject: body.subject,
message: body.message,
attachments: [],
headers: {},
});
return c.json({ success: true, result });
}
default:
return c.json({ success: false, error: 'Not implemented' }, 400);
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 26-35: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 38-43: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)


[error] 46-55: Other switch clauses can erroneously access this declaration.
Wrap the declaration in a block to restrict its access to the switch clause.

The declaration is defined in this switch clause:

Unsafe fix: Wrap the declaration in a block.

(lint/correctness/noSwitchDeclarations)

🤖 Prompt for AI Agents
In apps/server/src/routes/ai.ts between lines 24 and 59, the variables declared
inside each switch case are not scoped properly, which can cause them to be
accessible in other cases and lead to bugs. To fix this, wrap the code inside
each case block with curly braces {} to create a new block scope, ensuring
variables like threads, newBody, and result are confined to their respective
cases.

@MrgSub MrgSub changed the title Simple AI Router Add email actions to AI router Jun 4, 2025
Copy link
Collaborator Author

MrgSub commented Jun 4, 2025

Merge activity

  • Jun 4, 8:45 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jun 4, 8:45 PM UTC: @MrgSub merged this pull request with Graphite.

@MrgSub MrgSub merged commit defa336 into staging Jun 4, 2025
3 checks passed
@MrgSub MrgSub deleted the 06-03-simple_ai_router branch June 4, 2025 20:45
@coderabbitai coderabbitai bot mentioned this pull request Jul 13, 2025
6 tasks
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