Skip to content

GOWA - WhatsApp REST API with support for UI, Multi Account, Webhooks, and MCP, and Chatwoot. Built with Golang for efficient memory use.

feat: add comprehensive MCP tools for app management, group operations, and query functionality

Aldino Kemal91716a12e631
diff --git a/.gitignore b/.gitignore
index 688eac45..d40855cb 100644
Binary files a/.gitignore and b/.gitignore differ
diff --git a/readme.md b/readme.md
index 0acc4b54..cf4525ae 100644
--- a/readme.md
+++ b/readme.md
@@ -198,10 +198,46 @@ standardized protocol.
#### Available MCP Tools
-- `whatsapp_send_text` - Send text messages
-- `whatsapp_send_contact` - Send contact cards
-- `whatsapp_send_link` - Send links with captions
-- `whatsapp_send_location` - Send location coordinates
+The WhatsApp MCP server provides comprehensive tools for AI agents to interact with WhatsApp through a standardized protocol. Below is the complete list of available tools:
+
+##### **πŸ“± Connection Management**
+
+- `whatsapp_connection_status` - Check whether the WhatsApp client is connected and logged in
+- `whatsapp_login_qr` - Initiate QR code based login flow with image output
+- `whatsapp_login_with_code` - Generate pairing code for multi-device login using phone number
+- `whatsapp_logout` - Sign out the current WhatsApp session
+- `whatsapp_reconnect` - Attempt to reconnect to WhatsApp using stored session
+
+##### **πŸ’¬ Messaging & Communication**
+
+- `whatsapp_send_text` - Send text messages with reply and forwarding support
+- `whatsapp_send_contact` - Send contact cards with name and phone number
+- `whatsapp_send_link` - Send links with custom captions
+- `whatsapp_send_location` - Send location coordinates (latitude/longitude)
+- `whatsapp_send_image` - Send images with captions, compression, and view-once options
+
+##### **πŸ“‹ Chat & Contact Management**
+
+- `whatsapp_list_contacts` - Retrieve all contacts in your WhatsApp account
+- `whatsapp_list_chats` - Get recent chats with pagination and search filters
+- `whatsapp_get_chat_messages` - Fetch messages from specific chats with time/media filtering
+- `whatsapp_download_message_media` - Download images/videos from messages
+
+##### **πŸ‘₯ Group Management**
+
+- `whatsapp_group_create` - Create new groups with optional initial participants
+- `whatsapp_group_join_via_link` - Join groups using invite links
+- `whatsapp_group_leave` - Leave groups by group ID
+- `whatsapp_group_participants` - List all participants in a group
+- `whatsapp_group_manage_participants` - Add, remove, promote, or demote group members
+- `whatsapp_group_invite_link` - Get or reset group invite links
+- `whatsapp_group_info` - Get detailed group information
+- `whatsapp_group_set_name` - Update group display name
+- `whatsapp_group_set_topic` - Update group description/topic
+- `whatsapp_group_set_locked` - Toggle admin-only group info editing
+- `whatsapp_group_set_announce` - Toggle announcement-only mode
+- `whatsapp_group_join_requests` - List pending join requests
+- `whatsapp_group_manage_join_requests` - Approve or reject join requests
#### MCP Endpoints
diff --git a/src/cmd/mcp.go b/src/cmd/mcp.go
index 7c88b64f..9a380ffb 100644
--- a/src/cmd/mcp.go
+++ b/src/cmd/mcp.go
@@ -44,6 +44,15 @@ func mcpServer(_ *cobra.Command, _ []string) {
sendHandler := mcp.InitMcpSend(sendUsecase)
sendHandler.AddSendTools(mcpServer)
+ queryHandler := mcp.InitMcpQuery(chatUsecase, userUsecase, messageUsecase)
+ queryHandler.AddQueryTools(mcpServer)
+
+ appHandler := mcp.InitMcpApp(appUsecase)
+ appHandler.AddAppTools(mcpServer)
+
+ groupHandler := mcp.InitMcpGroup(groupUsecase)
+ groupHandler.AddGroupTools(mcpServer)
+
// Create SSE server
sseServer := server.NewSSEServer(
mcpServer,
diff --git a/src/ui/mcp/app.go b/src/ui/mcp/app.go
new file mode 100644
index 00000000..801e2eee
--- /dev/null
+++ b/src/ui/mcp/app.go
@@ -0,0 +1,165 @@
+package mcp
+
+import (
+ "context"
+ "encoding/base64"
+ "fmt"
+ "os"
+ "strings"
+
+ domainApp "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/app"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/infrastructure/whatsapp"
+ "github.com/mark3labs/mcp-go/mcp"
+ "github.com/mark3labs/mcp-go/server"
+)
+
+type AppHandler struct {
+ appService domainApp.IAppUsecase
+}
+
+func InitMcpApp(appService domainApp.IAppUsecase) *AppHandler {
+ return &AppHandler{appService: appService}
+}
+
+func (h *AppHandler) AddAppTools(mcpServer *server.MCPServer) {
+ mcpServer.AddTool(h.toolConnectionStatus(), h.handleConnectionStatus)
+ mcpServer.AddTool(h.toolLoginWithQR(), h.handleLoginWithQR)
+ mcpServer.AddTool(h.toolLoginWithCode(), h.handleLoginWithCode)
+ mcpServer.AddTool(h.toolLogout(), h.handleLogout)
+ mcpServer.AddTool(h.toolReconnect(), h.handleReconnect)
+}
+
+func (h *AppHandler) toolConnectionStatus() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_connection_status",
+ mcp.WithDescription("Check whether the WhatsApp client is connected and logged in."),
+ mcp.WithTitleAnnotation("Connection Status"),
+ mcp.WithReadOnlyHintAnnotation(true),
+ mcp.WithDestructiveHintAnnotation(false),
+ mcp.WithIdempotentHintAnnotation(true),
+ )
+}
+
+func (h *AppHandler) handleConnectionStatus(_ context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ isConnected, isLoggedIn, deviceID := whatsapp.GetConnectionStatus()
+
+ structured := map[string]any{
+ "is_connected": isConnected,
+ "is_logged_in": isLoggedIn,
+ }
+ if deviceID != "" {
+ structured["device_id"] = deviceID
+ }
+
+ fallback := fmt.Sprintf("connected=%t logged_in=%t", isConnected, isLoggedIn)
+ return mcp.NewToolResultStructured(structured, fallback), nil
+}
+
+func (h *AppHandler) toolLoginWithQR() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_login_qr",
+ mcp.WithDescription("Initiate a QR code based login flow. Returns the QR image and pairing code."),
+ mcp.WithTitleAnnotation("Login With QR"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ )
+}
+
+func (h *AppHandler) handleLoginWithQR(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ resp, err := h.appService.Login(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ fallback := fmt.Sprintf("Scan the QR image to log in (expires in ~%d seconds)", int(resp.Duration.Seconds()))
+ structured := map[string]any{
+ "qr_image_path": resp.ImagePath,
+ "qr_code": resp.Code,
+ "expires_in": int(resp.Duration.Seconds()),
+ }
+
+ qrBytes, readErr := os.ReadFile(resp.ImagePath)
+ if readErr != nil {
+ return mcp.NewToolResultStructured(structured, fallback), nil
+ }
+
+ encoded := base64.StdEncoding.EncodeToString(qrBytes)
+ result := mcp.NewToolResultImage(fallback, encoded, "image/png")
+ result.StructuredContent = structured
+ return result, nil
+}
+
+func (h *AppHandler) toolLoginWithCode() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_login_with_code",
+ mcp.WithDescription("Generate a pairing code for WhatsApp multi-device login using a phone number."),
+ mcp.WithTitleAnnotation("Login With Pairing Code"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("phone",
+ mcp.Description("Phone number in international format (e.g. +628123456789)."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *AppHandler) handleLoginWithCode(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ phone, err := request.RequireString("phone")
+ if err != nil {
+ return nil, err
+ }
+
+ trimmedPhone := strings.TrimSpace(phone)
+ pairCode, err := h.appService.LoginWithCode(ctx, trimmedPhone)
+ if err != nil {
+ return nil, err
+ }
+
+ structured := map[string]any{
+ "phone": trimmedPhone,
+ "pair_code": pairCode,
+ }
+
+ fallback := fmt.Sprintf("Pair code %s generated for %s", pairCode, trimmedPhone)
+ return mcp.NewToolResultStructured(structured, fallback), nil
+}
+
+func (h *AppHandler) toolLogout() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_logout",
+ mcp.WithDescription("Sign out the current WhatsApp session and clear stored credentials."),
+ mcp.WithTitleAnnotation("Logout"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ )
+}
+
+func (h *AppHandler) handleLogout(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ if err := h.appService.Logout(ctx); err != nil {
+ return nil, err
+ }
+
+ return mcp.NewToolResultText("Logged out successfully"), nil
+}
+
+func (h *AppHandler) toolReconnect() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_reconnect",
+ mcp.WithDescription("Attempt to reconnect to WhatsApp using the stored session."),
+ mcp.WithTitleAnnotation("Reconnect"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(false),
+ mcp.WithIdempotentHintAnnotation(true),
+ )
+}
+
+func (h *AppHandler) handleReconnect(ctx context.Context, _ mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ if err := h.appService.Reconnect(ctx); err != nil {
+ return nil, err
+ }
+
+ return mcp.NewToolResultText("Reconnect initiated"), nil
+}
diff --git a/src/ui/mcp/group.go b/src/ui/mcp/group.go
new file mode 100644
index 00000000..2a82b812
--- /dev/null
+++ b/src/ui/mcp/group.go
@@ -0,0 +1,713 @@
+package mcp
+
+import (
+ "context"
+ "fmt"
+ "strings"
+
+ domainGroup "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/group"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/mark3labs/mcp-go/mcp"
+ "github.com/mark3labs/mcp-go/server"
+ "go.mau.fi/whatsmeow"
+)
+
+type GroupHandler struct {
+ groupService domainGroup.IGroupUsecase
+}
+
+func InitMcpGroup(groupService domainGroup.IGroupUsecase) *GroupHandler {
+ return &GroupHandler{groupService: groupService}
+}
+
+func (h *GroupHandler) AddGroupTools(mcpServer *server.MCPServer) {
+ mcpServer.AddTool(h.toolCreateGroup(), h.handleCreateGroup)
+ mcpServer.AddTool(h.toolJoinGroup(), h.handleJoinGroup)
+ mcpServer.AddTool(h.toolLeaveGroup(), h.handleLeaveGroup)
+ mcpServer.AddTool(h.toolGetParticipants(), h.handleGetParticipants)
+ mcpServer.AddTool(h.toolManageParticipants(), h.handleManageParticipants)
+ mcpServer.AddTool(h.toolGetInviteLink(), h.handleGetInviteLink)
+ mcpServer.AddTool(h.toolGroupInfo(), h.handleGroupInfo)
+ mcpServer.AddTool(h.toolSetGroupName(), h.handleSetGroupName)
+ mcpServer.AddTool(h.toolSetGroupTopic(), h.handleSetGroupTopic)
+ mcpServer.AddTool(h.toolSetGroupLocked(), h.handleSetGroupLocked)
+ mcpServer.AddTool(h.toolSetGroupAnnounce(), h.handleSetGroupAnnounce)
+ mcpServer.AddTool(h.toolListGroupJoinRequests(), h.handleListGroupJoinRequests)
+ mcpServer.AddTool(h.toolManageGroupJoinRequests(), h.handleManageGroupJoinRequests)
+}
+
+func (h *GroupHandler) toolCreateGroup() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_create",
+ mcp.WithDescription("Create a new WhatsApp group with an optional participant list."),
+ mcp.WithTitleAnnotation("Create Group"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("title",
+ mcp.Description("Group subject/title."),
+ mcp.Required(),
+ ),
+ mcp.WithArray("participants",
+ mcp.Description("Phone numbers to add during creation (without @s.whatsapp.net suffix)."),
+ mcp.WithStringItems(),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleCreateGroup(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ title, err := request.RequireString("title")
+ if err != nil {
+ return nil, err
+ }
+
+ var participants []string
+ if args := request.GetArguments(); args != nil {
+ if raw, ok := args["participants"]; ok {
+ participants, err = toStringSlice(raw)
+ if err != nil {
+ return nil, err
+ }
+ }
+ }
+
+ groupID, err := h.groupService.CreateGroup(ctx, domainGroup.CreateGroupRequest{
+ Title: strings.TrimSpace(title),
+ Participants: participants,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ structured := map[string]any{
+ "group_id": groupID,
+ "title": strings.TrimSpace(title),
+ "members": len(participants),
+ }
+
+ fallback := fmt.Sprintf("Created group %s with %d members", groupID, len(participants))
+ return mcp.NewToolResultStructured(structured, fallback), nil
+}
+
+func (h *GroupHandler) toolJoinGroup() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_join_via_link",
+ mcp.WithDescription("Join a group using an invite link."),
+ mcp.WithTitleAnnotation("Join Group"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("invite_link",
+ mcp.Description("WhatsApp group invite link."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleJoinGroup(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ link, err := request.RequireString("invite_link")
+ if err != nil {
+ return nil, err
+ }
+
+ groupID, err := h.groupService.JoinGroupWithLink(ctx, domainGroup.JoinGroupWithLinkRequest{Link: strings.TrimSpace(link)})
+ if err != nil {
+ return nil, err
+ }
+
+ structured := map[string]any{
+ "group_id": groupID,
+ "invite_link": link,
+ }
+
+ fallback := fmt.Sprintf("Joined group %s", groupID)
+ return mcp.NewToolResultStructured(structured, fallback), nil
+}
+
+func (h *GroupHandler) toolLeaveGroup() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_leave",
+ mcp.WithDescription("Leave a WhatsApp group by its ID."),
+ mcp.WithTitleAnnotation("Leave Group"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("group_id",
+ mcp.Description("Group JID or numeric ID."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleLeaveGroup(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ groupID, err := request.RequireString("group_id")
+ if err != nil {
+ return nil, err
+ }
+
+ trimmed := strings.TrimSpace(groupID)
+ utils.SanitizePhone(&trimmed)
+
+ if err := h.groupService.LeaveGroup(ctx, domainGroup.LeaveGroupRequest{GroupID: trimmed}); err != nil {
+ return nil, err
+ }
+
+ return mcp.NewToolResultText(fmt.Sprintf("Left group %s", trimmed)), nil
+}
+
+func (h *GroupHandler) toolGetParticipants() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_participants",
+ mcp.WithDescription("Retrieve the participant list for a group."),
+ mcp.WithTitleAnnotation("List Participants"),
+ mcp.WithReadOnlyHintAnnotation(true),
+ mcp.WithDestructiveHintAnnotation(false),
+ mcp.WithIdempotentHintAnnotation(true),
+ mcp.WithString("group_id",
+ mcp.Description("Group JID or numeric ID."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleGetParticipants(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ groupID, err := request.RequireString("group_id")
+ if err != nil {
+ return nil, err
+ }
+
+ trimmed := strings.TrimSpace(groupID)
+ utils.SanitizePhone(&trimmed)
+
+ resp, err := h.groupService.GetGroupParticipants(ctx, domainGroup.GetGroupParticipantsRequest{GroupID: trimmed})
+ if err != nil {
+ return nil, err
+ }
+
+ fallback := fmt.Sprintf("Group %s has %d participants", resp.GroupID, len(resp.Participants))
+ return mcp.NewToolResultStructured(resp, fallback), nil
+}
+
+func (h *GroupHandler) toolManageParticipants() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_manage_participants",
+ mcp.WithDescription("Add, remove, promote, or demote group participants."),
+ mcp.WithTitleAnnotation("Manage Participants"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("group_id",
+ mcp.Description("Group JID or numeric ID."),
+ mcp.Required(),
+ ),
+ mcp.WithArray("participants",
+ mcp.Description("Phone numbers of participants to modify (without suffix)."),
+ mcp.Required(),
+ mcp.WithStringItems(),
+ ),
+ mcp.WithString("action",
+ mcp.Description("Participant action: add, remove, promote, or demote."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleManageParticipants(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ groupID, err := request.RequireString("group_id")
+ if err != nil {
+ return nil, err
+ }
+
+ var participants []string
+
+ args := request.GetArguments()
+ if args == nil {
+ return nil, fmt.Errorf("participants are required")
+ }
+
+ rawParticipants, exists := args["participants"]
+ if !exists {
+ return nil, fmt.Errorf("participants are required")
+ }
+
+ participants, err = toStringSlice(rawParticipants)
+ if err != nil {
+ return nil, err
+ }
+ if len(participants) == 0 {
+ return nil, fmt.Errorf("participants cannot be empty")
+ }
+
+ actionStr, err := request.RequireString("action")
+ if err != nil {
+ return nil, err
+ }
+
+ change, err := parseParticipantChange(actionStr)
+ if err != nil {
+ return nil, err
+ }
+
+ trimmed := strings.TrimSpace(groupID)
+ utils.SanitizePhone(&trimmed)
+
+ result, err := h.groupService.ManageParticipant(ctx, domainGroup.ParticipantRequest{
+ GroupID: trimmed,
+ Participants: participants,
+ Action: change,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ fallback := fmt.Sprintf("Applied %s to %d participants in %s", strings.ToLower(actionStr), len(participants), trimmed)
+ return mcp.NewToolResultStructured(result, fallback), nil
+}
+
+func (h *GroupHandler) toolGetInviteLink() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_invite_link",
+ mcp.WithDescription("Fetch the invite link for a group, optionally resetting it."),
+ mcp.WithTitleAnnotation("Get Invite Link"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("group_id",
+ mcp.Description("Group JID or numeric ID."),
+ mcp.Required(),
+ ),
+ mcp.WithBoolean("reset",
+ mcp.Description("If true, reset the invite link."),
+ mcp.DefaultBool(false),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleGetInviteLink(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ groupID, err := request.RequireString("group_id")
+ if err != nil {
+ return nil, err
+ }
+
+ reset := false
+ if rawArgs := request.GetArguments(); rawArgs != nil {
+ if val, ok := rawArgs["reset"]; ok {
+ parsed, err := toBool(val)
+ if err != nil {
+ return nil, err
+ }
+ reset = parsed
+ }
+ }
+
+ trimmed := strings.TrimSpace(groupID)
+ utils.SanitizePhone(&trimmed)
+
+ resp, err := h.groupService.GetGroupInviteLink(ctx, domainGroup.GetGroupInviteLinkRequest{
+ GroupID: trimmed,
+ Reset: reset,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ fallback := fmt.Sprintf("Invite link for %s: %s", trimmed, resp.InviteLink)
+ return mcp.NewToolResultStructured(resp, fallback), nil
+}
+
+func (h *GroupHandler) toolGroupInfo() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_info",
+ mcp.WithDescription("Retrieve detailed WhatsApp group information."),
+ mcp.WithTitleAnnotation("Group Info"),
+ mcp.WithReadOnlyHintAnnotation(true),
+ mcp.WithDestructiveHintAnnotation(false),
+ mcp.WithIdempotentHintAnnotation(true),
+ mcp.WithString("group_id",
+ mcp.Description("Group JID or numeric ID."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleGroupInfo(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ groupID, err := request.RequireString("group_id")
+ if err != nil {
+ return nil, err
+ }
+
+ trimmed := strings.TrimSpace(groupID)
+ utils.SanitizePhone(&trimmed)
+
+ resp, err := h.groupService.GroupInfo(ctx, domainGroup.GroupInfoRequest{GroupID: trimmed})
+ if err != nil {
+ return nil, err
+ }
+
+ fallback := fmt.Sprintf("Fetched group info for %s", trimmed)
+ return mcp.NewToolResultStructured(resp, fallback), nil
+}
+
+func (h *GroupHandler) toolSetGroupName() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_set_name",
+ mcp.WithDescription("Update the group's display name."),
+ mcp.WithTitleAnnotation("Set Group Name"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("group_id",
+ mcp.Description("Group JID or numeric ID."),
+ mcp.Required(),
+ ),
+ mcp.WithString("name",
+ mcp.Description("New group name."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleSetGroupName(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ groupID, err := request.RequireString("group_id")
+ if err != nil {
+ return nil, err
+ }
+
+ name, err := request.RequireString("name")
+ if err != nil {
+ return nil, err
+ }
+
+ trimmed := strings.TrimSpace(groupID)
+ utils.SanitizePhone(&trimmed)
+
+ if err := h.groupService.SetGroupName(ctx, domainGroup.SetGroupNameRequest{GroupID: trimmed, Name: strings.TrimSpace(name)}); err != nil {
+ return nil, err
+ }
+
+ return mcp.NewToolResultText(fmt.Sprintf("Updated group %s name to %s", trimmed, strings.TrimSpace(name))), nil
+}
+
+func (h *GroupHandler) toolSetGroupTopic() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_set_topic",
+ mcp.WithDescription("Update the group's topic or description."),
+ mcp.WithTitleAnnotation("Set Group Topic"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("group_id",
+ mcp.Description("Group JID or numeric ID."),
+ mcp.Required(),
+ ),
+ mcp.WithString("topic",
+ mcp.Description("New group topic/description."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleSetGroupTopic(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ groupID, err := request.RequireString("group_id")
+ if err != nil {
+ return nil, err
+ }
+
+ topic, err := request.RequireString("topic")
+ if err != nil {
+ return nil, err
+ }
+
+ trimmed := strings.TrimSpace(groupID)
+ utils.SanitizePhone(&trimmed)
+
+ if err := h.groupService.SetGroupTopic(ctx, domainGroup.SetGroupTopicRequest{GroupID: trimmed, Topic: strings.TrimSpace(topic)}); err != nil {
+ return nil, err
+ }
+
+ return mcp.NewToolResultText(fmt.Sprintf("Updated group %s topic", trimmed)), nil
+}
+
+func (h *GroupHandler) toolSetGroupLocked() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_set_locked",
+ mcp.WithDescription("Toggle whether only admins can edit group info."),
+ mcp.WithTitleAnnotation("Set Group Locked"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("group_id",
+ mcp.Description("Group JID or numeric ID."),
+ mcp.Required(),
+ ),
+ mcp.WithBoolean("locked",
+ mcp.Description("Set to true to lock the group."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleSetGroupLocked(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ groupID, err := request.RequireString("group_id")
+ if err != nil {
+ return nil, err
+ }
+
+ args := request.GetArguments()
+ if args == nil {
+ return nil, fmt.Errorf("locked flag is required")
+ }
+
+ val, ok := args["locked"]
+ if !ok {
+ return nil, fmt.Errorf("locked flag is required")
+ }
+
+ locked, err := toBool(val)
+ if err != nil {
+ return nil, err
+ }
+
+ trimmed := strings.TrimSpace(groupID)
+ utils.SanitizePhone(&trimmed)
+
+ if err := h.groupService.SetGroupLocked(ctx, domainGroup.SetGroupLockedRequest{GroupID: trimmed, Locked: locked}); err != nil {
+ return nil, err
+ }
+
+ state := "unlocked"
+ if locked {
+ state = "locked"
+ }
+
+ return mcp.NewToolResultText(fmt.Sprintf("Group %s is now %s", trimmed, state)), nil
+}
+
+func (h *GroupHandler) toolSetGroupAnnounce() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_set_announce",
+ mcp.WithDescription("Toggle announcement-only mode."),
+ mcp.WithTitleAnnotation("Set Group Announce"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("group_id",
+ mcp.Description("Group JID or numeric ID."),
+ mcp.Required(),
+ ),
+ mcp.WithBoolean("announce",
+ mcp.Description("Set to true to allow only admins to send messages."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleSetGroupAnnounce(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ groupID, err := request.RequireString("group_id")
+ if err != nil {
+ return nil, err
+ }
+
+ args := request.GetArguments()
+ if args == nil {
+ return nil, fmt.Errorf("announce flag is required")
+ }
+
+ val, ok := args["announce"]
+ if !ok {
+ return nil, fmt.Errorf("announce flag is required")
+ }
+
+ announce, err := toBool(val)
+ if err != nil {
+ return nil, err
+ }
+
+ trimmed := strings.TrimSpace(groupID)
+ utils.SanitizePhone(&trimmed)
+
+ if err := h.groupService.SetGroupAnnounce(ctx, domainGroup.SetGroupAnnounceRequest{GroupID: trimmed, Announce: announce}); err != nil {
+ return nil, err
+ }
+
+ state := "regular chat"
+ if announce {
+ state = "announcement-only"
+ }
+
+ return mcp.NewToolResultText(fmt.Sprintf("Group %s is now in %s mode", trimmed, state)), nil
+}
+
+func (h *GroupHandler) toolListGroupJoinRequests() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_join_requests",
+ mcp.WithDescription("List pending requests to join a group."),
+ mcp.WithTitleAnnotation("List Join Requests"),
+ mcp.WithReadOnlyHintAnnotation(true),
+ mcp.WithDestructiveHintAnnotation(false),
+ mcp.WithIdempotentHintAnnotation(true),
+ mcp.WithString("group_id",
+ mcp.Description("Group JID or numeric ID."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleListGroupJoinRequests(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ groupID, err := request.RequireString("group_id")
+ if err != nil {
+ return nil, err
+ }
+
+ trimmed := strings.TrimSpace(groupID)
+ utils.SanitizePhone(&trimmed)
+
+ resp, err := h.groupService.GetGroupRequestParticipants(ctx, domainGroup.GetGroupRequestParticipantsRequest{GroupID: trimmed})
+ if err != nil {
+ return nil, err
+ }
+
+ fallback := fmt.Sprintf("Group %s has %d pending requests", trimmed, len(resp))
+ return mcp.NewToolResultStructured(resp, fallback), nil
+}
+
+func (h *GroupHandler) toolManageGroupJoinRequests() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_group_manage_join_requests",
+ mcp.WithDescription("Approve or reject pending group join requests."),
+ mcp.WithTitleAnnotation("Manage Join Requests"),
+ mcp.WithReadOnlyHintAnnotation(false),
+ mcp.WithDestructiveHintAnnotation(true),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("group_id",
+ mcp.Description("Group JID or numeric ID."),
+ mcp.Required(),
+ ),
+ mcp.WithArray("participants",
+ mcp.Description("Phone numbers of requesters (without suffix)."),
+ mcp.Required(),
+ mcp.WithStringItems(),
+ ),
+ mcp.WithString("action",
+ mcp.Description("Action to apply: approve or reject."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *GroupHandler) handleManageGroupJoinRequests(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ groupID, err := request.RequireString("group_id")
+ if err != nil {
+ return nil, err
+ }
+
+ args := request.GetArguments()
+ if args == nil {
+ return nil, fmt.Errorf("participants are required")
+ }
+
+ participantsRaw, ok := args["participants"]
+ if !ok {
+ return nil, fmt.Errorf("participants are required")
+ }
+
+ participants, err := toStringSlice(participantsRaw)
+ if err != nil {
+ return nil, err
+ }
+ if len(participants) == 0 {
+ return nil, fmt.Errorf("participants cannot be empty")
+ }
+
+ actionStr, err := request.RequireString("action")
+ if err != nil {
+ return nil, err
+ }
+
+ change, err := parseParticipantRequestChange(actionStr)
+ if err != nil {
+ return nil, err
+ }
+
+ trimmed := strings.TrimSpace(groupID)
+ utils.SanitizePhone(&trimmed)
+
+ result, err := h.groupService.ManageGroupRequestParticipants(ctx, domainGroup.GroupRequestParticipantsRequest{
+ GroupID: trimmed,
+ Participants: participants,
+ Action: change,
+ })
+ if err != nil {
+ return nil, err
+ }
+
+ actionLower := strings.ToLower(actionStr)
+ actionVerb := actionLower
+ switch actionLower {
+ case "approve":
+ actionVerb = "approved"
+ case "reject":
+ actionVerb = "rejected"
+ }
+
+ actionReadable := actionVerb
+ if len(actionVerb) > 0 {
+ actionReadable = strings.ToUpper(actionVerb[:1]) + actionVerb[1:]
+ }
+
+ fallback := fmt.Sprintf("%s %d pending requests for %s", actionReadable, len(participants), trimmed)
+ return mcp.NewToolResultStructured(result, fallback), nil
+}
+
+func parseParticipantChange(action string) (whatsmeow.ParticipantChange, error) {
+ switch strings.ToLower(strings.TrimSpace(action)) {
+ case "add":
+ return whatsmeow.ParticipantChangeAdd, nil
+ case "remove":
+ return whatsmeow.ParticipantChangeRemove, nil
+ case "promote":
+ return whatsmeow.ParticipantChangePromote, nil
+ case "demote":
+ return whatsmeow.ParticipantChangeDemote, nil
+ default:
+ return whatsmeow.ParticipantChange(""), fmt.Errorf("invalid participant action: %s", action)
+ }
+}
+
+func parseParticipantRequestChange(action string) (whatsmeow.ParticipantRequestChange, error) {
+ switch strings.ToLower(strings.TrimSpace(action)) {
+ case "approve":
+ return whatsmeow.ParticipantChangeApprove, nil
+ case "reject":
+ return whatsmeow.ParticipantChangeReject, nil
+ default:
+ return whatsmeow.ParticipantRequestChange(""), fmt.Errorf("invalid join request action: %s", action)
+ }
+}
+
+func toStringSlice(raw any) ([]string, error) {
+ if raw == nil {
+ return nil, nil
+ }
+
+ switch v := raw.(type) {
+ case []string:
+ result := make([]string, len(v))
+ for i, item := range v {
+ result[i] = strings.TrimSpace(item)
+ }
+ return result, nil
+ case []any:
+ result := make([]string, len(v))
+ for i, item := range v {
+ str, ok := item.(string)
+ if !ok {
+ return nil, fmt.Errorf("participants[%d] is not a string", i)
+ }
+ result[i] = strings.TrimSpace(str)
+ }
+ return result, nil
+ default:
+ return nil, fmt.Errorf("participants must be an array of strings")
+ }
+}
diff --git a/src/ui/mcp/query.go b/src/ui/mcp/query.go
new file mode 100644
index 00000000..95410a06
--- /dev/null
+++ b/src/ui/mcp/query.go
@@ -0,0 +1,287 @@
+package mcp
+
+import (
+ "context"
+ "fmt"
+ "strconv"
+ "strings"
+
+ domainChat "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/chat"
+ domainMessage "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/message"
+ domainUser "github.com/aldinokemal/go-whatsapp-web-multidevice/domains/user"
+ "github.com/aldinokemal/go-whatsapp-web-multidevice/pkg/utils"
+ "github.com/mark3labs/mcp-go/mcp"
+ "github.com/mark3labs/mcp-go/server"
+)
+
+type QueryHandler struct {
+ chatService domainChat.IChatUsecase
+ userService domainUser.IUserUsecase
+ messageService domainMessage.IMessageUsecase
+}
+
+func InitMcpQuery(chatService domainChat.IChatUsecase, userService domainUser.IUserUsecase, messageService domainMessage.IMessageUsecase) *QueryHandler {
+ return &QueryHandler{
+ chatService: chatService,
+ userService: userService,
+ messageService: messageService,
+ }
+}
+
+func (h *QueryHandler) AddQueryTools(mcpServer *server.MCPServer) {
+ mcpServer.AddTool(h.toolListContacts(), h.handleListContacts)
+ mcpServer.AddTool(h.toolListChats(), h.handleListChats)
+ mcpServer.AddTool(h.toolGetChatMessages(), h.handleGetChatMessages)
+ mcpServer.AddTool(h.toolDownloadMedia(), h.handleDownloadMedia)
+}
+
+func (h *QueryHandler) toolListContacts() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_list_contacts",
+ mcp.WithDescription("Retrieve all contacts available in the connected WhatsApp account."),
+ mcp.WithTitleAnnotation("List Contacts"),
+ mcp.WithReadOnlyHintAnnotation(true),
+ mcp.WithDestructiveHintAnnotation(false),
+ mcp.WithIdempotentHintAnnotation(true),
+ )
+}
+
+func (h *QueryHandler) handleListContacts(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ resp, err := h.userService.MyListContacts(ctx)
+ if err != nil {
+ return nil, err
+ }
+
+ fallback := fmt.Sprintf("Found %d contacts", len(resp.Data))
+ return mcp.NewToolResultStructured(resp, fallback), nil
+}
+
+func (h *QueryHandler) toolListChats() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_list_chats",
+ mcp.WithDescription("Retrieve recent chats with optional pagination and search filters."),
+ mcp.WithTitleAnnotation("List Chats"),
+ mcp.WithReadOnlyHintAnnotation(true),
+ mcp.WithDestructiveHintAnnotation(false),
+ mcp.WithIdempotentHintAnnotation(true),
+ mcp.WithNumber("limit",
+ mcp.Description("Maximum number of chats to return (default 25, max 100)."),
+ mcp.DefaultNumber(25),
+ ),
+ mcp.WithNumber("offset",
+ mcp.Description("Number of chats to skip from the start (default 0)."),
+ mcp.DefaultNumber(0),
+ ),
+ mcp.WithString("search",
+ mcp.Description("Filter chats whose name contains this text."),
+ ),
+ mcp.WithBoolean("has_media",
+ mcp.Description("If true, return only chats that contain media messages."),
+ mcp.DefaultBool(false),
+ ),
+ )
+}
+
+func (h *QueryHandler) handleListChats(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ var hasMedia bool
+ args := request.GetArguments()
+ if args != nil {
+ if value, ok := args["has_media"]; ok {
+ parsed, err := toBool(value)
+ if err != nil {
+ return nil, err
+ }
+ hasMedia = parsed
+ }
+ }
+
+ req := domainChat.ListChatsRequest{
+ Limit: request.GetInt("limit", 25),
+ Offset: request.GetInt("offset", 0),
+ Search: request.GetString("search", ""),
+ HasMedia: hasMedia,
+ }
+
+ resp, err := h.chatService.ListChats(ctx, req)
+ if err != nil {
+ return nil, err
+ }
+
+ fallback := fmt.Sprintf(
+ "Retrieved %d chats (offset %d, limit %d)",
+ len(resp.Data),
+ req.Offset,
+ req.Limit,
+ )
+ return mcp.NewToolResultStructured(resp, fallback), nil
+}
+
+func (h *QueryHandler) toolGetChatMessages() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_get_chat_messages",
+ mcp.WithDescription("Fetch messages from a specific chat, with optional pagination, search, and time filters."),
+ mcp.WithTitleAnnotation("Get Chat Messages"),
+ mcp.WithReadOnlyHintAnnotation(true),
+ mcp.WithDestructiveHintAnnotation(false),
+ mcp.WithIdempotentHintAnnotation(true),
+ mcp.WithString("chat_jid",
+ mcp.Description("The chat JID (e.g., [email protected] or [email protected])."),
+ mcp.Required(),
+ ),
+ mcp.WithNumber("limit",
+ mcp.Description("Maximum number of messages to return (default 50, max 100)."),
+ mcp.DefaultNumber(50),
+ ),
+ mcp.WithNumber("offset",
+ mcp.Description("Number of messages to skip from the start (default 0)."),
+ mcp.DefaultNumber(0),
+ ),
+ mcp.WithString("start_time",
+ mcp.Description("Filter messages sent after this RFC3339 timestamp."),
+ ),
+ mcp.WithString("end_time",
+ mcp.Description("Filter messages sent before this RFC3339 timestamp."),
+ ),
+ mcp.WithBoolean("media_only",
+ mcp.Description("If true, return only messages containing media."),
+ mcp.DefaultBool(false),
+ ),
+ mcp.WithBoolean("is_from_me",
+ mcp.Description("If provided, filter messages sent by you (true) or others (false)."),
+ ),
+ mcp.WithString("search",
+ mcp.Description("Full-text search within the chat history (case-insensitive)."),
+ ),
+ )
+}
+
+func (h *QueryHandler) handleGetChatMessages(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ chatJID, err := request.RequireString("chat_jid")
+ if err != nil {
+ return nil, err
+ }
+
+ args := request.GetArguments()
+
+ var startTimePtr *string
+ startTime := strings.TrimSpace(request.GetString("start_time", ""))
+ if startTime != "" {
+ startTimePtr = &startTime
+ }
+
+ var endTimePtr *string
+ endTime := strings.TrimSpace(request.GetString("end_time", ""))
+ if endTime != "" {
+ endTimePtr = &endTime
+ }
+
+ mediaOnly := false
+ if args != nil {
+ if value, ok := args["media_only"]; ok {
+ parsed, err := toBool(value)
+ if err != nil {
+ return nil, err
+ }
+ mediaOnly = parsed
+ }
+ }
+
+ var isFromMePtr *bool
+ if args != nil {
+ if value, ok := args["is_from_me"]; ok {
+ parsed, err := toBool(value)
+ if err != nil {
+ return nil, err
+ }
+ isFromMePtr = &parsed
+ }
+ }
+
+ req := domainChat.GetChatMessagesRequest{
+ ChatJID: chatJID,
+ Limit: request.GetInt("limit", 50),
+ Offset: request.GetInt("offset", 0),
+ StartTime: startTimePtr,
+ EndTime: endTimePtr,
+ MediaOnly: mediaOnly,
+ IsFromMe: isFromMePtr,
+ Search: request.GetString("search", ""),
+ }
+
+ resp, err := h.chatService.GetChatMessages(ctx, req)
+ if err != nil {
+ return nil, err
+ }
+
+ fallback := fmt.Sprintf(
+ "Retrieved %d messages from %s",
+ len(resp.Data),
+ chatJID,
+ )
+ return mcp.NewToolResultStructured(resp, fallback), nil
+}
+
+func (h *QueryHandler) toolDownloadMedia() mcp.Tool {
+ return mcp.NewTool(
+ "whatsapp_download_message_media",
+ mcp.WithDescription("Download media associated with a specific message and return the local file path."),
+ mcp.WithTitleAnnotation("Download Message Media"),
+ mcp.WithReadOnlyHintAnnotation(true),
+ mcp.WithDestructiveHintAnnotation(false),
+ mcp.WithIdempotentHintAnnotation(false),
+ mcp.WithString("message_id",
+ mcp.Description("The WhatsApp message ID that contains the media."),
+ mcp.Required(),
+ ),
+ mcp.WithString("phone",
+ mcp.Description("The target chat phone number or JID associated with the message."),
+ mcp.Required(),
+ ),
+ )
+}
+
+func (h *QueryHandler) handleDownloadMedia(ctx context.Context, request mcp.CallToolRequest) (*mcp.CallToolResult, error) {
+ messageID, err := request.RequireString("message_id")
+ if err != nil {
+ return nil, err
+ }
+
+ phone, err := request.RequireString("phone")
+ if err != nil {
+ return nil, err
+ }
+
+ utils.SanitizePhone(&phone)
+
+ req := domainMessage.DownloadMediaRequest{
+ MessageID: messageID,
+ Phone: phone,
+ }
+
+ resp, err := h.messageService.DownloadMedia(ctx, req)
+ if err != nil {
+ return nil, err
+ }
+
+ fallback := fmt.Sprintf("Media saved to %s (%s)", resp.FilePath, resp.MediaType)
+ return mcp.NewToolResultStructured(resp, fallback), nil
+}
+
+func toBool(value any) (bool, error) {
+ switch v := value.(type) {
+ case bool:
+ return v, nil
+ case string:
+ parsed, err := strconv.ParseBool(v)
+ if err != nil {
+ return false, fmt.Errorf("unable to parse boolean value %q", v)
+ }
+ return parsed, nil
+ case float64:
+ return v != 0, nil
+ case int:
+ return v != 0, nil
+ default:
+ return false, fmt.Errorf("unsupported boolean value type %T", value)
+ }
+}