- Core/Documents/DocumentText: text of .docx (paragraphs, tables as rows), .xlsx (sheet by sheet, every cell at its column, stored values not formulas) and plain text/CSV. No DTD, no external references, every part bounded against zip bombs. PDF is named as not readable yet. - Mail: read_message lists attachments; read_attachment returns the text; save_attachment keeps the file in the agent's workspace (never over an existing file, never outside). - FileRW read/read_many return Word and Excel files as text; writing them stays refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
438 lines
20 KiB
C#
438 lines
20 KiB
C#
using System.Text.Json;
|
|
using ClawdDotNet.Core.Tools;
|
|
using MailKit;
|
|
using MailKit.Net.Imap;
|
|
using MailKit.Net.Smtp;
|
|
using MailKit.Search;
|
|
using Microsoft.Extensions.Logging;
|
|
using MimeKit;
|
|
|
|
using ClawdDotNet.Core.State;
|
|
|
|
namespace ClawdDotNet.Tools.Mail;
|
|
|
|
public sealed class MailTool : IAgentTool, IToolJobProvider
|
|
{
|
|
public string Name => "Mail";
|
|
|
|
/// <summary>#715: Brings text from outside into the context — mails from anyone.</summary>
|
|
public bool ReadsForeignContent => true;
|
|
|
|
public string Description => "Allows sending and receiving emails via SMTP and IMAP. read_message lists a message's attachments; read_attachment returns an attachment's text (Word, Excel, text and CSV files); save_attachment stores it in your workspace.";
|
|
|
|
public JsonElement InputSchema { get; } = JsonDocument.Parse("""
|
|
{
|
|
"type": "object",
|
|
"properties": {
|
|
"action": {
|
|
"type": "string",
|
|
"enum": ["send", "read_inbox", "read_message", "mark_read", "read_attachment", "save_attachment"],
|
|
"description": "The action to perform"
|
|
},
|
|
"to": {
|
|
"type": "string",
|
|
"description": "Recipient email (only for send)"
|
|
},
|
|
"subject": {
|
|
"type": "string",
|
|
"description": "Subject (only for send)"
|
|
},
|
|
"body": {
|
|
"type": "string",
|
|
"description": "Body of the email (only for send)"
|
|
},
|
|
"limit": {
|
|
"type": "integer",
|
|
"description": "Maximum number of emails to retrieve (only for read_inbox)"
|
|
},
|
|
"messageId": {
|
|
"type": "string",
|
|
"description": "The message ID (for read_message, mark_read, read_attachment, save_attachment)"
|
|
},
|
|
"attachment": {
|
|
"type": "string",
|
|
"description": "read_attachment, save_attachment: the attachment's number from read_message, or its file name"
|
|
},
|
|
"fileName": {
|
|
"type": "string",
|
|
"description": "save_attachment: the file name in your workspace (default: the attachment's name)"
|
|
}
|
|
},
|
|
"required": ["action"]
|
|
}
|
|
""").RootElement.Clone();
|
|
|
|
public async Task<ToolResult> ExecuteAsync(
|
|
JsonElement input,
|
|
AgentToolContext context,
|
|
CancellationToken ct)
|
|
{
|
|
var action = input.GetProperty("action").GetString()
|
|
?? throw new ArgumentException("'action' is required");
|
|
|
|
try
|
|
{
|
|
return action switch
|
|
{
|
|
"send" => await HandleSendAsync(input, context, ct),
|
|
"read_inbox" => await HandleReadInboxAsync(input, context, ct),
|
|
"read_message" => await HandleReadMessageAsync(input, context, ct),
|
|
"mark_read" => await HandleMarkReadAsync(input, context, ct),
|
|
"read_attachment" or "save_attachment" => await HandleAttachmentAsync(action, input, context, ct),
|
|
_ => ToolResult.Fail($"Unknown action: {action}")
|
|
};
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
context.Logger.LogError(ex, "Error during Mail action {Action}", action);
|
|
return ToolResult.Fail($"Error: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
private async Task<ToolResult> HandleSendAsync(JsonElement input, AgentToolContext context, CancellationToken ct)
|
|
{
|
|
var to = input.TryGetProperty("to", out var t) ? t.GetString() : null;
|
|
var subject = (input.TryGetProperty("subject", out var s) ? s.GetString() : null) ?? "(No Subject)";
|
|
var body = (input.TryGetProperty("body", out var b) ? b.GetString() : null) ?? "";
|
|
|
|
if (string.IsNullOrWhiteSpace(to)) return ToolResult.Fail("'to' is required.");
|
|
|
|
// Sicherheitsprüfung: Erlaubte Empfänger
|
|
if (!IsRecipientAllowed(to, context))
|
|
{
|
|
return ToolResult.Fail($"Security error: Sending to '{to}' is not allowed.");
|
|
}
|
|
|
|
if (!TryReadAccess(context, "smtpHost", "smtpPort", 587, out var access, out var fehlt))
|
|
return ToolResult.Fail(fehlt);
|
|
|
|
var message = new MimeMessage();
|
|
message.From.Add(new MailboxAddress("ClawdDotNet", access.UserName));
|
|
message.To.Add(MailboxAddress.Parse(to));
|
|
message.Subject = subject;
|
|
message.Body = new TextPart("plain") { Text = body };
|
|
|
|
using var client = new SmtpClient();
|
|
await client.ConnectAsync(access.Host, access.Port, true, ct);
|
|
await client.AuthenticateAsync(access.UserName, access.Password, ct);
|
|
await client.SendAsync(message, ct);
|
|
await client.DisconnectAsync(true, ct);
|
|
|
|
return ToolResult.Ok($"Email successfully sent to {to}.");
|
|
}
|
|
|
|
private async Task<ToolResult> HandleReadInboxAsync(JsonElement input, AgentToolContext context, CancellationToken ct)
|
|
{
|
|
var limit = input.TryGetProperty("limit", out var l) ? l.GetInt32() : 10;
|
|
|
|
if (!TryReadAccess(context, "imapHost", "imapPort", 993, out var access, out var fehlt))
|
|
return ToolResult.Fail(fehlt);
|
|
|
|
using var client = new ImapClient();
|
|
await client.ConnectAsync(access.Host, access.Port, true, ct);
|
|
await client.AuthenticateAsync(access.UserName, access.Password, ct);
|
|
|
|
await client.Inbox!.OpenAsync(FolderAccess.ReadOnly, ct);
|
|
var messages = new List<object>();
|
|
|
|
for (int i = client.Inbox!.Count - 1; i >= Math.Max(0, client.Inbox!.Count - limit); i--)
|
|
{
|
|
var msg = await client.Inbox!.GetMessageAsync(i, ct);
|
|
messages.Add(new
|
|
{
|
|
Id = i.ToString(),
|
|
Date = msg.Date,
|
|
From = msg.From.ToString(),
|
|
Subject = msg.Subject
|
|
});
|
|
}
|
|
|
|
await client.DisconnectAsync(true, ct);
|
|
return ToolResult.Ok(JsonSerializer.Serialize(messages, new JsonSerializerOptions { WriteIndented = true }));
|
|
}
|
|
|
|
private async Task<ToolResult> HandleReadMessageAsync(JsonElement input, AgentToolContext context, CancellationToken ct)
|
|
{
|
|
if (!input.TryGetProperty("messageId", out var mi) || !int.TryParse(mi.GetString(), out var index))
|
|
{
|
|
return ToolResult.Fail("'messageId' (index) is required.");
|
|
}
|
|
|
|
if (!TryReadAccess(context, "imapHost", "imapPort", 993, out var access, out var fehlt))
|
|
return ToolResult.Fail(fehlt);
|
|
|
|
using var client = new ImapClient();
|
|
await client.ConnectAsync(access.Host, access.Port, true, ct);
|
|
await client.AuthenticateAsync(access.UserName, access.Password, ct);
|
|
|
|
await client.Inbox!.OpenAsync(FolderAccess.ReadOnly, ct);
|
|
var msg = await client.Inbox!.GetMessageAsync(index, ct);
|
|
|
|
var result = new
|
|
{
|
|
Id = index.ToString(),
|
|
Date = msg.Date,
|
|
From = msg.From.ToString(),
|
|
Subject = msg.Subject,
|
|
Body = msg.TextBody,
|
|
// #692: what came with it — read with read_attachment, kept with save_attachment.
|
|
Attachments = Attachments(msg).Select((a, i) => new
|
|
{
|
|
Number = i + 1,
|
|
Name = a.FileName ?? $"attachment-{i + 1}",
|
|
Type = a.ContentType.MimeType,
|
|
Readable = ClawdDotNet.Core.Documents.DocumentText.Supports(a.FileName ?? "")
|
|
}).ToList()
|
|
};
|
|
|
|
await client.DisconnectAsync(true, ct);
|
|
return ToolResult.Ok(JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true }));
|
|
}
|
|
|
|
/// <summary>The largest attachment that is read or saved.</summary>
|
|
private const long MaxAttachmentBytes = 25L * 1024 * 1024;
|
|
|
|
/// <summary>The longest text an attachment hands to the model.</summary>
|
|
private const int MaxAttachmentChars = 60_000;
|
|
|
|
private static List<MimePart> Attachments(MimeMessage msg)
|
|
=> msg.Attachments.OfType<MimePart>().ToList();
|
|
|
|
/// <summary>
|
|
/// #692: The text of what really comes in — an order confirmation as a Word file, a price list
|
|
/// as a spreadsheet — or the file itself in the workspace. The text is a supplier's text:
|
|
/// the engine frames it as foreign content like every tool result.
|
|
/// </summary>
|
|
private async Task<ToolResult> HandleAttachmentAsync(string action, JsonElement input, AgentToolContext context, CancellationToken ct)
|
|
{
|
|
if (!input.TryGetProperty("messageId", out var mi) || !int.TryParse(mi.GetString(), out var index))
|
|
return ToolResult.Fail("'messageId' (index) is required.");
|
|
var wanted = input.TryGetProperty("attachment", out var at) ? at.ToString().Trim() : "";
|
|
if (wanted.Length == 0)
|
|
return ToolResult.Fail("'attachment' is required — its number from read_message, or its file name.");
|
|
|
|
if (!TryReadAccess(context, "imapHost", "imapPort", 993, out var access, out var fehlt))
|
|
return ToolResult.Fail(fehlt);
|
|
|
|
using var client = new ImapClient();
|
|
await client.ConnectAsync(access.Host, access.Port, true, ct);
|
|
await client.AuthenticateAsync(access.UserName, access.Password, ct);
|
|
await client.Inbox!.OpenAsync(FolderAccess.ReadOnly, ct);
|
|
var msg = await client.Inbox!.GetMessageAsync(index, ct);
|
|
await client.DisconnectAsync(true, ct);
|
|
|
|
var attachments = Attachments(msg);
|
|
var part = int.TryParse(wanted, out var number) && number >= 1 && number <= attachments.Count
|
|
? attachments[number - 1]
|
|
: attachments.FirstOrDefault(a => string.Equals(a.FileName, wanted, StringComparison.OrdinalIgnoreCase));
|
|
if (part is null)
|
|
return ToolResult.Fail($"Message {index} has no attachment '{wanted}' — it has {attachments.Count}.");
|
|
|
|
using var buffer = new MemoryStream();
|
|
await part.Content.DecodeToAsync(buffer, ct);
|
|
if (buffer.Length > MaxAttachmentBytes)
|
|
return ToolResult.Fail($"The attachment is {buffer.Length / 1024 / 1024} MB — more than {MaxAttachmentBytes / 1024 / 1024} MB are not taken.");
|
|
var name = part.FileName ?? $"attachment-{index}";
|
|
|
|
if (action == "read_attachment")
|
|
{
|
|
var text = ClawdDotNet.Core.Documents.DocumentText.Extract(buffer.ToArray(), name, MaxAttachmentChars);
|
|
if (!text.Ok)
|
|
return ToolResult.Fail($"{name}: {text.Problem} Keep it with save_attachment if a human should look at it.");
|
|
return ToolResult.Ok($"Attachment '{name}' ({text.Kind}) of message {index}" +
|
|
(text.Truncated ? $", first {MaxAttachmentChars} characters" : "") + ":\n" + text.Text);
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(context.WorkspacePath))
|
|
return ToolResult.Fail("You have no workspace to keep the attachment in.");
|
|
var requested = input.TryGetProperty("fileName", out var fn) ? fn.GetString() : null;
|
|
var fileName = SafeFileName(string.IsNullOrWhiteSpace(requested) ? name : requested);
|
|
Directory.CreateDirectory(context.WorkspacePath);
|
|
var target = Path.Combine(context.WorkspacePath, fileName);
|
|
// Never over an existing file: name.pdf, name (2).pdf, ...
|
|
for (var n = 2; File.Exists(target); n++)
|
|
target = Path.Combine(context.WorkspacePath, $"{Path.GetFileNameWithoutExtension(fileName)} ({n}){Path.GetExtension(fileName)}");
|
|
await File.WriteAllBytesAsync(target, buffer.ToArray(), ct);
|
|
return ToolResult.Ok($"Attachment '{name}' of message {index} saved in your workspace as '{Path.GetFileName(target)}' ({buffer.Length} bytes).");
|
|
}
|
|
|
|
/// <summary>A file name only — no directory, nothing that leaves the workspace.</summary>
|
|
public static string SafeFileName(string name)
|
|
{
|
|
// The same answer on every system: the last segment, and the characters any of them refuses replaced.
|
|
var bare = name.Replace('\\', '/').Split('/').Last().Trim();
|
|
bare = new string(bare.Select(c => c < 32 || "<>:\"|?*".Contains(c) ? '_' : c).ToArray());
|
|
bare = bare.TrimStart('.');
|
|
return bare.Length == 0 ? "attachment" : bare.Length > 120 ? bare[..120] : bare;
|
|
}
|
|
|
|
private async Task<ToolResult> HandleMarkReadAsync(JsonElement input, AgentToolContext context, CancellationToken ct)
|
|
{
|
|
if (!input.TryGetProperty("messageId", out var mi) || !int.TryParse(mi.GetString(), out var index))
|
|
{
|
|
return ToolResult.Fail("'messageId' (index) is required.");
|
|
}
|
|
|
|
if (!TryReadAccess(context, "imapHost", "imapPort", 993, out var access, out var fehlt))
|
|
return ToolResult.Fail(fehlt);
|
|
|
|
using var client = new ImapClient();
|
|
await client.ConnectAsync(access.Host, access.Port, true, ct);
|
|
await client.AuthenticateAsync(access.UserName, access.Password, ct);
|
|
|
|
await client.Inbox!.OpenAsync(FolderAccess.ReadWrite, ct);
|
|
await client.Inbox!.AddFlagsAsync(index, MessageFlags.Seen, true, ct);
|
|
|
|
await client.DisconnectAsync(true, ct);
|
|
return ToolResult.Ok($"Message {index} marked as read.");
|
|
}
|
|
|
|
/// <summary>Ein Zugang: Server, Port und Anmeldedaten — vollständig oder gar nicht.</summary>
|
|
private readonly record struct MailAccess(string Host, int Port, string UserName, string Password);
|
|
|
|
/// <summary>
|
|
/// Liest Server und Anmeldedaten aus der Werkzeug-Konfiguration.
|
|
///
|
|
/// <para>Vorher standen die Werte an vier Stellen einzeln im Aufruf:
|
|
/// <c>config["smtpHost"]?.ToString()</c>. Das ging auf zwei Arten schief. Fehlte der
|
|
/// Schlüssel ganz, warf der Indexer eine <c>KeyNotFoundException</c>; war er leer,
|
|
/// ging <c>null</c> an MailKit — worauf der Compiler mit fünfzehn
|
|
/// Nullable-Warnungen hinwies. Beim Agenten kam beides als dieselbe unbrauchbare
|
|
/// Zeile an: „Fehler: …".</para>
|
|
///
|
|
/// <para>Hier fällt stattdessen die Antwort aus, die weiterhilft: welcher Schlüssel
|
|
/// fehlt. Der Port bleibt weich — dafür gibt es sinnvolle Vorgaben; Server und
|
|
/// Anmeldedaten kann niemand raten.</para>
|
|
/// </summary>
|
|
private static bool TryReadAccess(
|
|
AgentToolContext context, string hostKey, string portKey, int defaultPort,
|
|
out MailAccess access, out string error)
|
|
{
|
|
access = default;
|
|
|
|
var host = ReadSetting(context, hostKey);
|
|
var user = ReadSetting(context, "username");
|
|
var password = ReadSetting(context, "password");
|
|
|
|
var missing = new List<string>();
|
|
if (string.IsNullOrWhiteSpace(host)) missing.Add(hostKey);
|
|
if (string.IsNullOrWhiteSpace(user)) missing.Add("username");
|
|
if (string.IsNullOrWhiteSpace(password)) missing.Add("password");
|
|
|
|
if (missing.Count > 0)
|
|
{
|
|
error = "The mail tool is not fully configured. " +
|
|
$"Missing in tool configuration: {string.Join(", ", missing)}.";
|
|
return false;
|
|
}
|
|
|
|
access = new MailAccess(host!, ReadPort(context, portKey, defaultPort), user!, password!);
|
|
error = "";
|
|
return true;
|
|
}
|
|
|
|
private static string? ReadSetting(AgentToolContext context, string key)
|
|
=> context.ToolConfig.TryGetValue(key, out var value) ? value?.ToString() : null;
|
|
|
|
private static int ReadPort(AgentToolContext context, string key, int fallback)
|
|
=> context.ToolConfig.TryGetValue(key, out var value)
|
|
&& value is JsonElement { ValueKind: JsonValueKind.Number } je
|
|
&& je.TryGetInt32(out var port)
|
|
? port
|
|
: fallback;
|
|
|
|
private bool IsRecipientAllowed(string email, AgentToolContext context)
|
|
{
|
|
if (!context.ToolConfig.TryGetValue("allowedRecipients", out var val) || val is not JsonElement je)
|
|
{
|
|
return false;
|
|
}
|
|
|
|
var allowed = je.EnumerateArray().Select(x => x.GetString()?.ToLowerInvariant()).ToList();
|
|
return allowed.Contains(email.ToLowerInvariant());
|
|
}
|
|
|
|
public IReadOnlyList<ToolJobDefinition> GetJobDefinitions() =>
|
|
[
|
|
new("mail_check_unread", "Mail Check", "Periodically checks for new unread emails")
|
|
];
|
|
|
|
public async Task<ToolJobResult> ExecuteJobAsync(
|
|
string jobTypeId,
|
|
IReadOnlyDictionary<string, object?> toolConfig,
|
|
IStateStore stateStore,
|
|
ILogger logger,
|
|
CancellationToken ct,
|
|
string? agentId = null,
|
|
string? workspacePath = null)
|
|
{
|
|
if (jobTypeId != "mail_check_unread")
|
|
return ToolJobResult.NoAction($"Unknown job: {jobTypeId}");
|
|
|
|
try
|
|
{
|
|
using var client = new ImapClient();
|
|
var imapHost = toolConfig.TryGetValue("imapHost", out var h) ? h?.ToString() : null;
|
|
var imapPort = toolConfig.TryGetValue("imapPort", out var p) ? (p is long l ? (int)l : (p is int i ? i : 993)) : 993;
|
|
var username = toolConfig.TryGetValue("username", out var u) ? u?.ToString() : null;
|
|
var password = toolConfig.TryGetValue("password", out var pw) ? pw?.ToString() : null;
|
|
|
|
if (string.IsNullOrWhiteSpace(imapHost) || string.IsNullOrWhiteSpace(username))
|
|
return ToolJobResult.NoAction("Mail configuration incomplete");
|
|
|
|
await client.ConnectAsync(imapHost, imapPort, true, ct);
|
|
await client.AuthenticateAsync(username ?? "", password ?? "", ct);
|
|
|
|
await client.Inbox!.OpenAsync(FolderAccess.ReadOnly, ct);
|
|
|
|
// Wir suchen nach ungelesenen Nachrichten
|
|
var uids = await client.Inbox!.SearchAsync(SearchQuery.NotSeen, ct);
|
|
|
|
if (uids.Count == 0)
|
|
{
|
|
await client.DisconnectAsync(true, ct);
|
|
return ToolJobResult.NoAction("No new unread emails");
|
|
}
|
|
|
|
// Um zu vermeiden, dass wir bei jedem Tick für die gleichen Mails wecken,
|
|
// speichern wir die höchste UID, die wir bereits gemeldet haben.
|
|
var lastUidStr = await stateStore.GetAsync("mail_last_notified_uid", ct);
|
|
uint lastUid = uint.TryParse(lastUidStr, out var lu) ? lu : 0;
|
|
|
|
var newUids = uids.Where(uid => uid.Id > lastUid).OrderBy(uid => uid.Id).ToList();
|
|
|
|
if (newUids.Count == 0)
|
|
{
|
|
await client.DisconnectAsync(true, ct);
|
|
return ToolJobResult.NoAction("No new emails since last check");
|
|
}
|
|
|
|
// Die neuesten Nachrichten abrufen für die Zusammenfassung
|
|
var summary = new List<string>();
|
|
foreach (var uid in newUids.Take(5))
|
|
{
|
|
var msg = await client.Inbox!.GetMessageAsync(uid, ct);
|
|
summary.Add($"- From: {msg.From}, Subject: {msg.Subject}");
|
|
}
|
|
|
|
if (newUids.Count > 5) summary.Add($"- ... and {newUids.Count - 5} more");
|
|
|
|
// Höchste UID speichern
|
|
var maxUid = newUids.Max(u => u.Id);
|
|
await stateStore.SetAsync("mail_last_notified_uid", maxUid.ToString(), ct);
|
|
|
|
await client.DisconnectAsync(true, ct);
|
|
|
|
return ToolJobResult.Wake(
|
|
$"You have received {newUids.Count} new unread email(s):\n" + string.Join("\n", summary),
|
|
logSummary: $"{newUids.Count} new email(s) found"
|
|
);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
logger.LogError(ex, "Error in Mail background job");
|
|
return ToolJobResult.NoAction($"Error: {ex.Message}");
|
|
}
|
|
}
|
|
}
|