Skip to content

Sweetmantech/myc 3783 email pass input text html to recoup agent call#74

Merged
sweetmantech merged 4 commits intotestfrom
sweetmantech/myc-3783-email-pass-input-text-html-to-recoup-agent-call
Dec 17, 2025
Merged

Sweetmantech/myc 3783 email pass input text html to recoup agent call#74
sweetmantech merged 4 commits intotestfrom
sweetmantech/myc-3783-email-pass-input-text-html-to-recoup-agent-call

Conversation

@sweetmantech
Copy link
Contributor

@sweetmantech sweetmantech commented Dec 17, 2025

Note

Fetches inbound email body from Resend and uses it to drive agent-generated thread replies.

  • Emails — Inbound handling:
    • Add lib/emails/inbound/getEmailContent.ts to retrieve email body via Resend Receiving API (prefers text, falls back to html).
    • Update respondToInboundEmail to:
      • Use email_id to fetch emailText and feed it into getMessages and agent generate prompt.
      • Simplify reply payload HTML to agent response text.
      • Maintain thread headers with In-Reply-To.

Written by Cursor Bugbot for commit 987022b. This will update automatically on new commits. Configure here.

Summary by CodeRabbit

  • New Features

    • Added inbound email handling with automatic AI-powered replies
    • Integrated email service for sending and receiving emails
    • Enhanced chat system with image support and improved context awareness
    • Added email validation and error handling for webhook processing
  • Chores

    • Added email and MCP client dependencies

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

@vercel
Copy link
Contributor

vercel bot commented Dec 17, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Review Updated (UTC)
recoup-api Ready Ready Preview Dec 17, 2025 9:59pm

@coderabbitai
Copy link

coderabbitai bot commented Dec 17, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

This PR introduces a complete inbound email processing system with agent-based chat routing. It adds webhook handling for Resend email events, a general agent factory that orchestrates tool setup and system prompt construction, supporting utilities for chat validation and prompt building, email client infrastructure, and updates to database queries and type definitions. Two new dependencies (@ai-sdk/mcp and resend) are added.

Changes

Cohort / File(s) Summary
Email Inbound Webhook & Route Handler
app/api/emails/inbound/route.ts
Adds POST handler that accepts inbound email webhooks and delegates to handleInboundEmail.
Email Processing Core
lib/emails/inbound/handleInboundEmail.ts, lib/emails/inbound/respondToInboundEmail.ts, lib/emails/validateInboundEmailEvent.ts
Validates and processes Resend email events; constructs account-scoped chat-based replies and sends via Resend API.
Email Client & Utilities
lib/emails/client.ts, lib/emails/sendEmail.ts
Email service client initialization and shared send function with error handling.
Chat Agent Factory & Routing
lib/agents/generalAgent/getGeneralAgent.ts
Constructs a ToolLoopAgent with model, tools, system prompt, and instructions for chat routing.
Chat Validation & Schema
lib/chat/validateChatRequest.ts, lib/chat/types.ts
Zod-based validation for chat payloads and RoutingDecision type definition.
Tool Management
lib/chat/setupToolsForRequest.ts, lib/chat/filterExcludedTools.ts
Fetches MCP tools and filters excluded ones; creates MCP client via HTTP transport.
System Prompt Building
lib/chat/const.ts, lib/prompts/getSystemPrompt.ts, lib/chat/buildSystemPromptWithImages.ts
Defines base system prompt; constructs context-aware prompts with user details, artist info, and image URLs.
Message & File Processing
lib/messages/getMessages.ts, lib/messages/extractImageUrlsFromMessages.ts, lib/files/getKnowledgeBaseText.ts
Utilities for creating message objects, extracting image URLs, and fetching knowledge base text.
Database & Account Queries
lib/supabase/account_emails/selectAccountEmails.ts, lib/supabase/accounts/getAccountWithDetails.ts
Updates selectAccountEmails to support filtering by accountIds; refactors AccountWithDetails as a type alias combining related tables.
Utilities
lib/uuid/generateUUID.ts
UUID v4 generation with crypto fallback.
Dependencies
package.json
Adds @ai-sdk/mcp and resend.

Sequence Diagram

sequenceDiagram
    participant Resend as Resend Webhook
    participant Route as POST /api/emails/inbound
    participant Validator as validateInboundEmailEvent
    participant Handler as handleInboundEmail
    participant EmailProc as respondToInboundEmail
    participant ResendAPI as Resend API
    participant DB as Account/Email DB
    participant Agent as getGeneralAgent
    participant MCP as MCP Tools

    Resend->>Route: Email event (POST request)
    Route->>Handler: Delegate to handleInboundEmail
    Handler->>Validator: Validate event payload
    alt Validation fails
        Validator-->>Handler: NextResponse (400)
        Handler-->>Resend: Return error response
    else Validation succeeds
        Validator-->>Handler: Validated event
        Handler->>EmailProc: Process email.received event
        EmailProc->>ResendAPI: Fetch email content
        ResendAPI-->>EmailProc: Email text/HTML content
        EmailProc->>DB: Lookup sender account by email
        DB-->>EmailProc: Account details
        EmailProc->>Agent: Generate response (email as chat message)
        Agent->>MCP: Query available tools
        MCP-->>Agent: Tool definitions (ToolSet)
        Agent->>DB: Fetch account context, artist info, knowledge base
        DB-->>Agent: Context & instructions
        Agent-->>EmailProc: Response text & model info
        EmailProc->>ResendAPI: Send reply (In-Reply-To header)
        ResendAPI-->>EmailProc: Confirmation
        EmailProc-->>Handler: API response
        Handler-->>Resend: Return success
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45–60 minutes

  • Key areas requiring attention:
    • lib/agents/generalAgent/getGeneralAgent.ts — orchestrates multiple data fetches and agent construction; verify correct sequencing, null-checks, and error propagation
    • lib/emails/inbound/respondToInboundEmail.ts — complex error handling with external API calls; verify try/catch logic and error logging
    • lib/chat/setupToolsForRequest.ts — MCP client initialization and tool retrieval; verify transport configuration and tool merging logic
    • lib/supabase/accounts/getAccountWithDetails.ts — type alias refactoring; verify Partial composition and query correctness
    • Integration points between email handler and chat agent; verify request/response flow and data passing

Possibly related PRs

Poem

🐰 A rabbit hops through email thread,
With agents swift and tools well-fed,
From Resend hooks to prompts divine,
Each message woven, stitch by line!
Now chat and mail in harmony sing,
What wonder shall tomorrow bring? 🌟

Pre-merge checks and finishing touches

✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title directly references the main objective: passing email input text/HTML to the agent call for handling inbound emails, which aligns with the core changes adding email inbound handling and agent integration.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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.

@sweetmantech sweetmantech changed the base branch from main to test December 17, 2025 21:46
Copy link
Contributor

@vercel vercel bot left a comment

Choose a reason for hiding this comment

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

Additional Suggestion:

The response email exposes internal account_id to external email recipients, which is a security/information disclosure issue that should be removed or redacted.

View Details
📝 Patch Details
diff --git a/lib/emails/inbound/respondToInboundEmail.ts b/lib/emails/inbound/respondToInboundEmail.ts
index 866f31f..5238294 100644
--- a/lib/emails/inbound/respondToInboundEmail.ts
+++ b/lib/emails/inbound/respondToInboundEmail.ts
@@ -48,7 +48,7 @@ export async function respondToInboundEmail(
       from: "hi@recoupable.com",
       to: toArray,
       subject,
-      html: `<p>Thanks for your email!</p><p>account_id: ${accountId}</p><p>${chatResponse.text}</p>`,
+      html: `<p>Thanks for your email!</p><p>${chatResponse.text}</p>`,
       headers: {
         "In-Reply-To": messageId,
       },

Analysis

Information Disclosure: Internal account_id exposed in email response

What fails: respondToInboundEmail() in lib/emails/inbound/respondToInboundEmail.ts exposes the internal account_id to external email recipients via the HTML email body

How to reproduce:

  1. Send an email to the Resend inbound email endpoint (hi@recoupable.com or similar configured address)
  2. The webhook handler processes the email and calls respondToInboundEmail()
  3. The function retrieves the account_id from the database and includes it in the HTML response: html: '<p>Thanks for your email!</p><p>account_id:
  4. External email recipients receive an email containing the internal account_id

Result: Email response body contains: account_id: <uuid_or_id_value> sent to external email addresses

Expected: Email response should not expose internal identifiers to external parties. Only user-facing information should be in the email body.

Security Impact:

  • Information Disclosure: Exposes implementation details and internal system identifiers
  • Enumeration Risk: Attackers could potentially use exposed IDs for enumeration attacks
  • Violates security principle of not exposing internal identifiers in external communications

Fix: Removed the account_id from the HTML email template. The account_id is still available internally for processing and logging but is no longer exposed to external recipients.

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.

This PR is being reviewed by Cursor Bugbot

Details

You are on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle.

To receive Bugbot reviews on all of your PRs, visit the Cursor dashboard to activate Pro and start your 14-day free trial.

const chatResponse = await agent.generate({
prompt: "hello world",
prompt: emailText,
});
Copy link

Choose a reason for hiding this comment

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

Bug: Untrusted email drives tool-enabled agent

Inbound sender-controlled content from getEmailContent() is passed directly into getGeneralAgent() and agent.generate() as the prompt/messages. Because the agent is configured with external tools, this enables prompt-injection-driven tool use and unintended data disclosure/side effects during webhook processing.

Additional Locations (1)

Fix in Cursor Fix in Web

@sweetmantech sweetmantech merged commit 5edb7a3 into test Dec 17, 2025
4 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Dec 20, 2025
Merged
@coderabbitai coderabbitai bot mentioned this pull request Jan 27, 2026
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

Comments